Tue Mar 18 12:39:27 CET 2008 Paolo Molaro <lupus@ximian.com>
[mono.git] / mono / mini / mini-amd64.c
1 /*
2  * mini-amd64.c: AMD64 backend for the Mono code generator
3  *
4  * Based on mini-x86.c.
5  *
6  * Authors:
7  *   Paolo Molaro (lupus@ximian.com)
8  *   Dietmar Maurer (dietmar@ximian.com)
9  *   Patrik Torstensson
10  *   Zoltan Varga (vargaz@gmail.com)
11  *
12  * (C) 2003 Ximian, Inc.
13  */
14 #include "mini.h"
15 #include <string.h>
16 #include <math.h>
17 #ifdef HAVE_UNISTD_H
18 #include <unistd.h>
19 #endif
20
21 #include <mono/metadata/appdomain.h>
22 #include <mono/metadata/debug-helpers.h>
23 #include <mono/metadata/threads.h>
24 #include <mono/metadata/profiler-private.h>
25 #include <mono/metadata/mono-debug.h>
26 #include <mono/utils/mono-math.h>
27
28 #include "trace.h"
29 #include "mini-amd64.h"
30 #include "inssel.h"
31 #include "cpu-amd64.h"
32
33 static gint lmf_tls_offset = -1;
34 static gint lmf_addr_tls_offset = -1;
35 static gint appdomain_tls_offset = -1;
36 static gint thread_tls_offset = -1;
37
38 #ifdef MONO_XEN_OPT
39 static gboolean optimize_for_xen = TRUE;
40 #else
41 #define optimize_for_xen 0
42 #endif
43
44 static gboolean use_sse2 = !MONO_ARCH_USE_FPSTACK;
45
46 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
47
48 #define IS_IMM32(val) ((((guint64)val) >> 32) == 0)
49
50 #define IS_REX(inst) (((inst) >= 0x40) && ((inst) <= 0x4f))
51
52 #ifdef PLATFORM_WIN32
53 /* Under windows, the default pinvoke calling convention is stdcall */
54 #define CALLCONV_IS_STDCALL(call_conv) (((call_conv) == MONO_CALL_STDCALL) || ((call_conv) == MONO_CALL_DEFAULT))
55 #else
56 #define CALLCONV_IS_STDCALL(call_conv) ((call_conv) == MONO_CALL_STDCALL)
57 #endif
58
59 /* This mutex protects architecture specific caches */
60 #define mono_mini_arch_lock() EnterCriticalSection (&mini_arch_mutex)
61 #define mono_mini_arch_unlock() LeaveCriticalSection (&mini_arch_mutex)
62 static CRITICAL_SECTION mini_arch_mutex;
63
64 MonoBreakpointInfo
65 mono_breakpoint_info [MONO_BREAKPOINT_ARRAY_SIZE];
66
67 #define ARGS_OFFSET 16
68 #define GP_SCRATCH_REG AMD64_R11
69
70 /*
71  * AMD64 register usage:
72  * - callee saved registers are used for global register allocation
73  * - %r11 is used for materializing 64 bit constants in opcodes
74  * - the rest is used for local allocation
75  */
76
77 /*
78  * Floating point comparison results:
79  *                  ZF PF CF
80  * A > B            0  0  0
81  * A < B            0  0  1
82  * A = B            1  0  0
83  * A > B            0  0  0
84  * UNORDERED        1  1  1
85  */
86
87 const char*
88 mono_arch_regname (int reg)
89 {
90         switch (reg) {
91         case AMD64_RAX: return "%rax";
92         case AMD64_RBX: return "%rbx";
93         case AMD64_RCX: return "%rcx";
94         case AMD64_RDX: return "%rdx";
95         case AMD64_RSP: return "%rsp";  
96         case AMD64_RBP: return "%rbp";
97         case AMD64_RDI: return "%rdi";
98         case AMD64_RSI: return "%rsi";
99         case AMD64_R8: return "%r8";
100         case AMD64_R9: return "%r9";
101         case AMD64_R10: return "%r10";
102         case AMD64_R11: return "%r11";
103         case AMD64_R12: return "%r12";
104         case AMD64_R13: return "%r13";
105         case AMD64_R14: return "%r14";
106         case AMD64_R15: return "%r15";
107         }
108         return "unknown";
109 }
110
111 static const char * xmmregs [] = {
112         "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7", "xmm8",
113         "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15"
114 };
115
116 const char*
117 mono_arch_fregname (int reg)
118 {
119         if (reg < AMD64_XMM_NREG)
120                 return xmmregs [reg];
121         else
122                 return "unknown";
123 }
124
125 G_GNUC_UNUSED static void
126 break_count (void)
127 {
128 }
129
130 G_GNUC_UNUSED static gboolean
131 debug_count (void)
132 {
133         static int count = 0;
134         count ++;
135
136         if (!getenv ("COUNT"))
137                 return TRUE;
138
139         if (count == atoi (getenv ("COUNT"))) {
140                 break_count ();
141         }
142
143         if (count > atoi (getenv ("COUNT"))) {
144                 return FALSE;
145         }
146
147         return TRUE;
148 }
149
150 static gboolean
151 debug_omit_fp (void)
152 {
153 #if 0
154         return debug_count ();
155 #else
156         return TRUE;
157 #endif
158 }
159
160 static inline gboolean
161 amd64_is_near_call (guint8 *code)
162 {
163         /* Skip REX */
164         if ((code [0] >= 0x40) && (code [0] <= 0x4f))
165                 code += 1;
166
167         return code [0] == 0xe8;
168 }
169
170 static inline void 
171 amd64_patch (unsigned char* code, gpointer target)
172 {
173         /* Skip REX */
174         if ((code [0] >= 0x40) && (code [0] <= 0x4f))
175                 code += 1;
176
177         if ((code [0] & 0xf8) == 0xb8) {
178                 /* amd64_set_reg_template */
179                 *(guint64*)(code + 1) = (guint64)target;
180         }
181         else if (code [0] == 0x8b) {
182                 /* mov 0(%rip), %dreg */
183                 *(guint32*)(code + 2) = (guint32)(guint64)target - 7;
184         }
185         else if ((code [0] == 0xff) && (code [1] == 0x15)) {
186                 /* call *<OFFSET>(%rip) */
187                 *(guint32*)(code + 2) = ((guint32)(guint64)target) - 7;
188         }
189         else if ((code [0] == 0xe8)) {
190                 /* call <DISP> */
191                 gint64 disp = (guint8*)target - (guint8*)code;
192                 g_assert (amd64_is_imm32 (disp));
193                 x86_patch (code, (unsigned char*)target);
194         }
195         else
196                 x86_patch (code, (unsigned char*)target);
197 }
198
199 void 
200 mono_amd64_patch (unsigned char* code, gpointer target)
201 {
202         amd64_patch (code, target);
203 }
204
205 typedef enum {
206         ArgInIReg,
207         ArgInFloatSSEReg,
208         ArgInDoubleSSEReg,
209         ArgOnStack,
210         ArgValuetypeInReg,
211         ArgNone /* only in pair_storage */
212 } ArgStorage;
213
214 typedef struct {
215         gint16 offset;
216         gint8  reg;
217         ArgStorage storage;
218
219         /* Only if storage == ArgValuetypeInReg */
220         ArgStorage pair_storage [2];
221         gint8 pair_regs [2];
222 } ArgInfo;
223
224 typedef struct {
225         int nargs;
226         guint32 stack_usage;
227         guint32 reg_usage;
228         guint32 freg_usage;
229         gboolean need_stack_align;
230         ArgInfo ret;
231         ArgInfo sig_cookie;
232         ArgInfo args [1];
233 } CallInfo;
234
235 #define DEBUG(a) if (cfg->verbose_level > 1) a
236
237 #define NEW_ICONST(cfg,dest,val) do {   \
238                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
239                 (dest)->opcode = OP_ICONST;     \
240                 (dest)->inst_c0 = (val);        \
241                 (dest)->type = STACK_I4;        \
242         } while (0)
243
244 #ifdef PLATFORM_WIN32
245 #define PARAM_REGS 4
246
247 static AMD64_Reg_No param_regs [] = { AMD64_RCX, AMD64_RDX, AMD64_R8, AMD64_R9 };
248
249 static AMD64_Reg_No return_regs [] = { AMD64_RAX, AMD64_RDX };
250 #else
251 #define PARAM_REGS 6
252  
253 static AMD64_Reg_No param_regs [] = { AMD64_RDI, AMD64_RSI, AMD64_RDX, AMD64_RCX, AMD64_R8, AMD64_R9 };
254
255  static AMD64_Reg_No return_regs [] = { AMD64_RAX, AMD64_RDX };
256 #endif
257
258 static void inline
259 add_general (guint32 *gr, guint32 *stack_size, ArgInfo *ainfo)
260 {
261     ainfo->offset = *stack_size;
262
263     if (*gr >= PARAM_REGS) {
264                 ainfo->storage = ArgOnStack;
265                 (*stack_size) += sizeof (gpointer);
266     }
267     else {
268                 ainfo->storage = ArgInIReg;
269                 ainfo->reg = param_regs [*gr];
270                 (*gr) ++;
271     }
272 }
273
274 #ifdef PLATFORM_WIN32
275 #define FLOAT_PARAM_REGS 4
276 #else
277 #define FLOAT_PARAM_REGS 8
278 #endif
279
280 static void inline
281 add_float (guint32 *gr, guint32 *stack_size, ArgInfo *ainfo, gboolean is_double)
282 {
283     ainfo->offset = *stack_size;
284
285     if (*gr >= FLOAT_PARAM_REGS) {
286                 ainfo->storage = ArgOnStack;
287                 (*stack_size) += sizeof (gpointer);
288     }
289     else {
290                 /* A double register */
291                 if (is_double)
292                         ainfo->storage = ArgInDoubleSSEReg;
293                 else
294                         ainfo->storage = ArgInFloatSSEReg;
295                 ainfo->reg = *gr;
296                 (*gr) += 1;
297     }
298 }
299
300 typedef enum ArgumentClass {
301         ARG_CLASS_NO_CLASS,
302         ARG_CLASS_MEMORY,
303         ARG_CLASS_INTEGER,
304         ARG_CLASS_SSE
305 } ArgumentClass;
306
307 static ArgumentClass
308 merge_argument_class_from_type (MonoType *type, ArgumentClass class1)
309 {
310         ArgumentClass class2 = ARG_CLASS_NO_CLASS;
311         MonoType *ptype;
312
313         ptype = mono_type_get_underlying_type (type);
314         switch (ptype->type) {
315         case MONO_TYPE_BOOLEAN:
316         case MONO_TYPE_CHAR:
317         case MONO_TYPE_I1:
318         case MONO_TYPE_U1:
319         case MONO_TYPE_I2:
320         case MONO_TYPE_U2:
321         case MONO_TYPE_I4:
322         case MONO_TYPE_U4:
323         case MONO_TYPE_I:
324         case MONO_TYPE_U:
325         case MONO_TYPE_STRING:
326         case MONO_TYPE_OBJECT:
327         case MONO_TYPE_CLASS:
328         case MONO_TYPE_SZARRAY:
329         case MONO_TYPE_PTR:
330         case MONO_TYPE_FNPTR:
331         case MONO_TYPE_ARRAY:
332         case MONO_TYPE_I8:
333         case MONO_TYPE_U8:
334                 class2 = ARG_CLASS_INTEGER;
335                 break;
336         case MONO_TYPE_R4:
337         case MONO_TYPE_R8:
338                 class2 = ARG_CLASS_SSE;
339                 break;
340
341         case MONO_TYPE_TYPEDBYREF:
342                 g_assert_not_reached ();
343
344         case MONO_TYPE_GENERICINST:
345                 if (!mono_type_generic_inst_is_valuetype (ptype)) {
346                         class2 = ARG_CLASS_INTEGER;
347                         break;
348                 }
349                 /* fall through */
350         case MONO_TYPE_VALUETYPE: {
351                 MonoMarshalType *info = mono_marshal_load_type_info (ptype->data.klass);
352                 int i;
353
354                 for (i = 0; i < info->num_fields; ++i) {
355                         class2 = class1;
356                         class2 = merge_argument_class_from_type (info->fields [i].field->type, class2);
357                 }
358                 break;
359         }
360         default:
361                 g_assert_not_reached ();
362         }
363
364         /* Merge */
365         if (class1 == class2)
366                 ;
367         else if (class1 == ARG_CLASS_NO_CLASS)
368                 class1 = class2;
369         else if ((class1 == ARG_CLASS_MEMORY) || (class2 == ARG_CLASS_MEMORY))
370                 class1 = ARG_CLASS_MEMORY;
371         else if ((class1 == ARG_CLASS_INTEGER) || (class2 == ARG_CLASS_INTEGER))
372                 class1 = ARG_CLASS_INTEGER;
373         else
374                 class1 = ARG_CLASS_SSE;
375
376         return class1;
377 }
378
379 static void
380 add_valuetype (MonoGenericSharingContext *gsctx, MonoMethodSignature *sig, ArgInfo *ainfo, MonoType *type,
381                gboolean is_return,
382                guint32 *gr, guint32 *fr, guint32 *stack_size)
383 {
384         guint32 size, quad, nquads, i;
385         ArgumentClass args [2];
386         MonoMarshalType *info;
387         MonoClass *klass;
388
389         klass = mono_class_from_mono_type (type);
390         if (sig->pinvoke) 
391                 size = mono_type_native_stack_size (&klass->byval_arg, NULL);
392         else 
393                 size = mini_type_stack_size (gsctx, &klass->byval_arg, NULL);
394
395         if (!sig->pinvoke || (size == 0) || (size > 16)) {
396                 /* Allways pass in memory */
397                 ainfo->offset = *stack_size;
398                 *stack_size += ALIGN_TO (size, 8);
399                 ainfo->storage = ArgOnStack;
400
401                 return;
402         }
403
404         /* FIXME: Handle structs smaller than 8 bytes */
405         //if ((size % 8) != 0)
406         //      NOT_IMPLEMENTED;
407
408         if (size > 8)
409                 nquads = 2;
410         else
411                 nquads = 1;
412
413         /*
414          * Implement the algorithm from section 3.2.3 of the X86_64 ABI.
415          * The X87 and SSEUP stuff is left out since there are no such types in
416          * the CLR.
417          */
418         info = mono_marshal_load_type_info (klass);
419         g_assert (info);
420         if (info->native_size > 16) {
421                 ainfo->offset = *stack_size;
422                 *stack_size += ALIGN_TO (info->native_size, 8);
423                 ainfo->storage = ArgOnStack;
424
425                 return;
426         }
427
428         args [0] = ARG_CLASS_NO_CLASS;
429         args [1] = ARG_CLASS_NO_CLASS;
430         for (quad = 0; quad < nquads; ++quad) {
431                 int size;
432                 guint32 align;
433                 ArgumentClass class1;
434                 
435                 class1 = ARG_CLASS_NO_CLASS;
436                 for (i = 0; i < info->num_fields; ++i) {
437                         size = mono_marshal_type_size (info->fields [i].field->type, 
438                                                                                    info->fields [i].mspec, 
439                                                                                    &align, TRUE, klass->unicode);
440                         if ((info->fields [i].offset < 8) && (info->fields [i].offset + size) > 8) {
441                                 /* Unaligned field */
442                                 NOT_IMPLEMENTED;
443                         }
444
445                         /* Skip fields in other quad */
446                         if ((quad == 0) && (info->fields [i].offset >= 8))
447                                 continue;
448                         if ((quad == 1) && (info->fields [i].offset < 8))
449                                 continue;
450
451                         class1 = merge_argument_class_from_type (info->fields [i].field->type, class1);
452                 }
453                 g_assert (class1 != ARG_CLASS_NO_CLASS);
454                 args [quad] = class1;
455         }
456
457         /* Post merger cleanup */
458         if ((args [0] == ARG_CLASS_MEMORY) || (args [1] == ARG_CLASS_MEMORY))
459                 args [0] = args [1] = ARG_CLASS_MEMORY;
460
461         /* Allocate registers */
462         {
463                 int orig_gr = *gr;
464                 int orig_fr = *fr;
465
466                 ainfo->storage = ArgValuetypeInReg;
467                 ainfo->pair_storage [0] = ainfo->pair_storage [1] = ArgNone;
468                 for (quad = 0; quad < nquads; ++quad) {
469                         switch (args [quad]) {
470                         case ARG_CLASS_INTEGER:
471                                 if (*gr >= PARAM_REGS)
472                                         args [quad] = ARG_CLASS_MEMORY;
473                                 else {
474                                         ainfo->pair_storage [quad] = ArgInIReg;
475                                         if (is_return)
476                                                 ainfo->pair_regs [quad] = return_regs [*gr];
477                                         else
478                                                 ainfo->pair_regs [quad] = param_regs [*gr];
479                                         (*gr) ++;
480                                 }
481                                 break;
482                         case ARG_CLASS_SSE:
483                                 if (*fr >= FLOAT_PARAM_REGS)
484                                         args [quad] = ARG_CLASS_MEMORY;
485                                 else {
486                                         ainfo->pair_storage [quad] = ArgInDoubleSSEReg;
487                                         ainfo->pair_regs [quad] = *fr;
488                                         (*fr) ++;
489                                 }
490                                 break;
491                         case ARG_CLASS_MEMORY:
492                                 break;
493                         default:
494                                 g_assert_not_reached ();
495                         }
496                 }
497
498                 if ((args [0] == ARG_CLASS_MEMORY) || (args [1] == ARG_CLASS_MEMORY)) {
499                         /* Revert possible register assignments */
500                         *gr = orig_gr;
501                         *fr = orig_fr;
502
503                         ainfo->offset = *stack_size;
504                         *stack_size += ALIGN_TO (info->native_size, 8);
505                         ainfo->storage = ArgOnStack;
506                 }
507         }
508 }
509
510 /*
511  * get_call_info:
512  *
513  *  Obtain information about a call according to the calling convention.
514  * For AMD64, see the "System V ABI, x86-64 Architecture Processor Supplement 
515  * Draft Version 0.23" document for more information.
516  */
517 static CallInfo*
518 get_call_info (MonoCompile *cfg, MonoMemPool *mp, MonoMethodSignature *sig, gboolean is_pinvoke)
519 {
520         guint32 i, gr, fr;
521         MonoType *ret_type;
522         int n = sig->hasthis + sig->param_count;
523         guint32 stack_size = 0;
524         CallInfo *cinfo;
525         MonoGenericSharingContext *gsctx = cfg ? cfg->generic_sharing_context : NULL;
526
527         if (mp)
528                 cinfo = mono_mempool_alloc0 (mp, sizeof (CallInfo) + (sizeof (ArgInfo) * n));
529         else
530                 cinfo = g_malloc0 (sizeof (CallInfo) + (sizeof (ArgInfo) * n));
531
532         gr = 0;
533         fr = 0;
534
535         /* return value */
536         {
537                 ret_type = mono_type_get_underlying_type (sig->ret);
538                 ret_type = mini_get_basic_type_from_generic (gsctx, ret_type);
539                 switch (ret_type->type) {
540                 case MONO_TYPE_BOOLEAN:
541                 case MONO_TYPE_I1:
542                 case MONO_TYPE_U1:
543                 case MONO_TYPE_I2:
544                 case MONO_TYPE_U2:
545                 case MONO_TYPE_CHAR:
546                 case MONO_TYPE_I4:
547                 case MONO_TYPE_U4:
548                 case MONO_TYPE_I:
549                 case MONO_TYPE_U:
550                 case MONO_TYPE_PTR:
551                 case MONO_TYPE_FNPTR:
552                 case MONO_TYPE_CLASS:
553                 case MONO_TYPE_OBJECT:
554                 case MONO_TYPE_SZARRAY:
555                 case MONO_TYPE_ARRAY:
556                 case MONO_TYPE_STRING:
557                         cinfo->ret.storage = ArgInIReg;
558                         cinfo->ret.reg = AMD64_RAX;
559                         break;
560                 case MONO_TYPE_U8:
561                 case MONO_TYPE_I8:
562                         cinfo->ret.storage = ArgInIReg;
563                         cinfo->ret.reg = AMD64_RAX;
564                         break;
565                 case MONO_TYPE_R4:
566                         cinfo->ret.storage = ArgInFloatSSEReg;
567                         cinfo->ret.reg = AMD64_XMM0;
568                         break;
569                 case MONO_TYPE_R8:
570                         cinfo->ret.storage = ArgInDoubleSSEReg;
571                         cinfo->ret.reg = AMD64_XMM0;
572                         break;
573                 case MONO_TYPE_GENERICINST:
574                         if (!mono_type_generic_inst_is_valuetype (sig->ret)) {
575                                 cinfo->ret.storage = ArgInIReg;
576                                 cinfo->ret.reg = AMD64_RAX;
577                                 break;
578                         }
579                         /* fall through */
580                 case MONO_TYPE_VALUETYPE: {
581                         guint32 tmp_gr = 0, tmp_fr = 0, tmp_stacksize = 0;
582
583                         add_valuetype (gsctx, sig, &cinfo->ret, sig->ret, TRUE, &tmp_gr, &tmp_fr, &tmp_stacksize);
584                         if (cinfo->ret.storage == ArgOnStack)
585                                 /* The caller passes the address where the value is stored */
586                                 add_general (&gr, &stack_size, &cinfo->ret);
587                         break;
588                 }
589                 case MONO_TYPE_TYPEDBYREF:
590                         /* Same as a valuetype with size 24 */
591                         add_general (&gr, &stack_size, &cinfo->ret);
592                         ;
593                         break;
594                 case MONO_TYPE_VOID:
595                         break;
596                 default:
597                         g_error ("Can't handle as return value 0x%x", sig->ret->type);
598                 }
599         }
600
601         /* this */
602         if (sig->hasthis)
603                 add_general (&gr, &stack_size, cinfo->args + 0);
604
605         if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG) && (n == 0)) {
606                 gr = PARAM_REGS;
607                 fr = FLOAT_PARAM_REGS;
608                 
609                 /* Emit the signature cookie just before the implicit arguments */
610                 add_general (&gr, &stack_size, &cinfo->sig_cookie);
611         }
612
613         for (i = 0; i < sig->param_count; ++i) {
614                 ArgInfo *ainfo = &cinfo->args [sig->hasthis + i];
615                 MonoType *ptype;
616
617                 if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG) && (i == sig->sentinelpos)) {
618                         /* We allways pass the sig cookie on the stack for simplicity */
619                         /* 
620                          * Prevent implicit arguments + the sig cookie from being passed 
621                          * in registers.
622                          */
623                         gr = PARAM_REGS;
624                         fr = FLOAT_PARAM_REGS;
625
626                         /* Emit the signature cookie just before the implicit arguments */
627                         add_general (&gr, &stack_size, &cinfo->sig_cookie);
628                 }
629
630                 if (sig->params [i]->byref) {
631                         add_general (&gr, &stack_size, ainfo);
632                         continue;
633                 }
634                 ptype = mono_type_get_underlying_type (sig->params [i]);
635                 ptype = mini_get_basic_type_from_generic (gsctx, ptype);
636                 switch (ptype->type) {
637                 case MONO_TYPE_BOOLEAN:
638                 case MONO_TYPE_I1:
639                 case MONO_TYPE_U1:
640                         add_general (&gr, &stack_size, ainfo);
641                         break;
642                 case MONO_TYPE_I2:
643                 case MONO_TYPE_U2:
644                 case MONO_TYPE_CHAR:
645                         add_general (&gr, &stack_size, ainfo);
646                         break;
647                 case MONO_TYPE_I4:
648                 case MONO_TYPE_U4:
649                         add_general (&gr, &stack_size, ainfo);
650                         break;
651                 case MONO_TYPE_I:
652                 case MONO_TYPE_U:
653                 case MONO_TYPE_PTR:
654                 case MONO_TYPE_FNPTR:
655                 case MONO_TYPE_CLASS:
656                 case MONO_TYPE_OBJECT:
657                 case MONO_TYPE_STRING:
658                 case MONO_TYPE_SZARRAY:
659                 case MONO_TYPE_ARRAY:
660                         add_general (&gr, &stack_size, ainfo);
661                         break;
662                 case MONO_TYPE_GENERICINST:
663                         if (!mono_type_generic_inst_is_valuetype (ptype)) {
664                                 add_general (&gr, &stack_size, ainfo);
665                                 break;
666                         }
667                         /* fall through */
668                 case MONO_TYPE_VALUETYPE:
669                         add_valuetype (gsctx, sig, ainfo, sig->params [i], FALSE, &gr, &fr, &stack_size);
670                         break;
671                 case MONO_TYPE_TYPEDBYREF:
672                         stack_size += sizeof (MonoTypedRef);
673                         ainfo->storage = ArgOnStack;
674                         break;
675                 case MONO_TYPE_U8:
676                 case MONO_TYPE_I8:
677                         add_general (&gr, &stack_size, ainfo);
678                         break;
679                 case MONO_TYPE_R4:
680                         add_float (&fr, &stack_size, ainfo, FALSE);
681                         break;
682                 case MONO_TYPE_R8:
683                         add_float (&fr, &stack_size, ainfo, TRUE);
684                         break;
685                 default:
686                         g_assert_not_reached ();
687                 }
688         }
689
690         if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG) && (n > 0) && (sig->sentinelpos == sig->param_count)) {
691                 gr = PARAM_REGS;
692                 fr = FLOAT_PARAM_REGS;
693                 
694                 /* Emit the signature cookie just before the implicit arguments */
695                 add_general (&gr, &stack_size, &cinfo->sig_cookie);
696         }
697
698 #ifdef PLATFORM_WIN32
699         if (stack_size < 32) {
700                 /* The Win64 ABI requires 32 bits  */
701                 stack_size = 32;
702         }
703 #endif
704
705         if (stack_size & 0x8) {
706                 /* The AMD64 ABI requires each stack frame to be 16 byte aligned */
707                 cinfo->need_stack_align = TRUE;
708                 stack_size += 8;
709         }
710
711         cinfo->stack_usage = stack_size;
712         cinfo->reg_usage = gr;
713         cinfo->freg_usage = fr;
714         return cinfo;
715 }
716
717 /*
718  * mono_arch_get_argument_info:
719  * @csig:  a method signature
720  * @param_count: the number of parameters to consider
721  * @arg_info: an array to store the result infos
722  *
723  * Gathers information on parameters such as size, alignment and
724  * padding. arg_info should be large enought to hold param_count + 1 entries. 
725  *
726  * Returns the size of the argument area on the stack.
727  */
728 int
729 mono_arch_get_argument_info (MonoMethodSignature *csig, int param_count, MonoJitArgumentInfo *arg_info)
730 {
731         int k;
732         CallInfo *cinfo = get_call_info (NULL, NULL, csig, FALSE);
733         guint32 args_size = cinfo->stack_usage;
734
735         /* The arguments are saved to a stack area in mono_arch_instrument_prolog */
736         if (csig->hasthis) {
737                 arg_info [0].offset = 0;
738         }
739
740         for (k = 0; k < param_count; k++) {
741                 arg_info [k + 1].offset = ((k + csig->hasthis) * 8);
742                 /* FIXME: */
743                 arg_info [k + 1].size = 0;
744         }
745
746         g_free (cinfo);
747
748         return args_size;
749 }
750
751 static int 
752 cpuid (int id, int* p_eax, int* p_ebx, int* p_ecx, int* p_edx)
753 {
754         __asm__ __volatile__ ("cpuid"
755                 : "=a" (*p_eax), "=b" (*p_ebx), "=c" (*p_ecx), "=d" (*p_edx)
756                 : "a" (id));
757         return 1;
758 }
759
760 /*
761  * Initialize the cpu to execute managed code.
762  */
763 void
764 mono_arch_cpu_init (void)
765 {
766 #ifndef _MSC_VER
767         guint16 fpcw;
768
769         /* spec compliance requires running with double precision */
770         __asm__  __volatile__ ("fnstcw %0\n": "=m" (fpcw));
771         fpcw &= ~X86_FPCW_PRECC_MASK;
772         fpcw |= X86_FPCW_PREC_DOUBLE;
773         __asm__  __volatile__ ("fldcw %0\n": : "m" (fpcw));
774         __asm__  __volatile__ ("fnstcw %0\n": "=m" (fpcw));
775 #else
776         _control87 (_PC_53, MCW_PC);
777 #endif
778 }
779
780 /*
781  * Initialize architecture specific code.
782  */
783 void
784 mono_arch_init (void)
785 {
786         InitializeCriticalSection (&mini_arch_mutex);
787 }
788
789 /*
790  * Cleanup architecture specific code.
791  */
792 void
793 mono_arch_cleanup (void)
794 {
795         DeleteCriticalSection (&mini_arch_mutex);
796 }
797
798 /*
799  * This function returns the optimizations supported on this cpu.
800  */
801 guint32
802 mono_arch_cpu_optimizazions (guint32 *exclude_mask)
803 {
804         int eax, ebx, ecx, edx;
805         guint32 opts = 0;
806
807         /* FIXME: AMD64 */
808
809         *exclude_mask = 0;
810         /* Feature Flags function, flags returned in EDX. */
811         if (cpuid (1, &eax, &ebx, &ecx, &edx)) {
812                 if (edx & (1 << 15)) {
813                         opts |= MONO_OPT_CMOV;
814                         if (edx & 1)
815                                 opts |= MONO_OPT_FCMOV;
816                         else
817                                 *exclude_mask |= MONO_OPT_FCMOV;
818                 } else
819                         *exclude_mask |= MONO_OPT_CMOV;
820         }
821         return opts;
822 }
823
824 gboolean
825 mono_amd64_is_sse2 (void)
826 {
827         return use_sse2;
828 }
829
830 GList *
831 mono_arch_get_allocatable_int_vars (MonoCompile *cfg)
832 {
833         GList *vars = NULL;
834         int i;
835
836         for (i = 0; i < cfg->num_varinfo; i++) {
837                 MonoInst *ins = cfg->varinfo [i];
838                 MonoMethodVar *vmv = MONO_VARINFO (cfg, i);
839
840                 /* unused vars */
841                 if (vmv->range.first_use.abs_pos >= vmv->range.last_use.abs_pos)
842                         continue;
843
844                 if ((ins->flags & (MONO_INST_IS_DEAD|MONO_INST_VOLATILE|MONO_INST_INDIRECT)) || 
845                     (ins->opcode != OP_LOCAL && ins->opcode != OP_ARG))
846                         continue;
847
848                 if (mono_is_regsize_var (ins->inst_vtype)) {
849                         g_assert (MONO_VARINFO (cfg, i)->reg == -1);
850                         g_assert (i == vmv->idx);
851                         vars = g_list_prepend (vars, vmv);
852                 }
853         }
854
855         vars = mono_varlist_sort (cfg, vars, 0);
856
857         return vars;
858 }
859
860 /**
861  * mono_arch_compute_omit_fp:
862  *
863  *   Determine whenever the frame pointer can be eliminated.
864  */
865 static void
866 mono_arch_compute_omit_fp (MonoCompile *cfg)
867 {
868         MonoMethodSignature *sig;
869         MonoMethodHeader *header;
870         int i, locals_size;
871         CallInfo *cinfo;
872
873         if (cfg->arch.omit_fp_computed)
874                 return;
875
876         header = mono_method_get_header (cfg->method);
877
878         sig = mono_method_signature (cfg->method);
879
880         if (!cfg->arch.cinfo)
881                 cfg->arch.cinfo = get_call_info (cfg, cfg->mempool, sig, FALSE);
882         cinfo = cfg->arch.cinfo;
883
884         /*
885          * FIXME: Remove some of the restrictions.
886          */
887         cfg->arch.omit_fp = TRUE;
888         cfg->arch.omit_fp_computed = TRUE;
889
890         /* Temporarily disable this when running in the debugger until we have support
891          * for this in the debugger. */
892         if (mono_debug_using_mono_debugger ())
893                 cfg->arch.omit_fp = FALSE;
894
895         if (!debug_omit_fp ())
896                 cfg->arch.omit_fp = FALSE;
897         /*
898         if (cfg->method->save_lmf)
899                 cfg->arch.omit_fp = FALSE;
900         */
901         if (cfg->flags & MONO_CFG_HAS_ALLOCA)
902                 cfg->arch.omit_fp = FALSE;
903         if (header->num_clauses)
904                 cfg->arch.omit_fp = FALSE;
905         if (cfg->param_area)
906                 cfg->arch.omit_fp = FALSE;
907         if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG))
908                 cfg->arch.omit_fp = FALSE;
909         if ((mono_jit_trace_calls != NULL && mono_trace_eval (cfg->method)) ||
910                 (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE))
911                 cfg->arch.omit_fp = FALSE;
912         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
913                 ArgInfo *ainfo = &cinfo->args [i];
914
915                 if (ainfo->storage == ArgOnStack) {
916                         /* 
917                          * The stack offset can only be determined when the frame
918                          * size is known.
919                          */
920                         cfg->arch.omit_fp = FALSE;
921                 }
922         }
923
924         locals_size = 0;
925         for (i = cfg->locals_start; i < cfg->num_varinfo; i++) {
926                 MonoInst *ins = cfg->varinfo [i];
927                 int ialign;
928
929                 locals_size += mono_type_size (ins->inst_vtype, &ialign);
930         }
931
932         if ((cfg->num_varinfo > 10000) || (locals_size >= (1 << 15))) {
933                 /* Avoid hitting the stack_alloc_size < (1 << 16) assertion in emit_epilog () */
934                 cfg->arch.omit_fp = FALSE;
935         }
936 }
937
938 GList *
939 mono_arch_get_global_int_regs (MonoCompile *cfg)
940 {
941         GList *regs = NULL;
942
943         mono_arch_compute_omit_fp (cfg);
944
945         if (cfg->arch.omit_fp)
946                 regs = g_list_prepend (regs, (gpointer)AMD64_RBP);
947
948         /* We use the callee saved registers for global allocation */
949         regs = g_list_prepend (regs, (gpointer)AMD64_RBX);
950         regs = g_list_prepend (regs, (gpointer)AMD64_R12);
951         regs = g_list_prepend (regs, (gpointer)AMD64_R13);
952         regs = g_list_prepend (regs, (gpointer)AMD64_R14);
953         regs = g_list_prepend (regs, (gpointer)AMD64_R15);
954
955         return regs;
956 }
957
958 /*
959  * mono_arch_regalloc_cost:
960  *
961  *  Return the cost, in number of memory references, of the action of 
962  * allocating the variable VMV into a register during global register
963  * allocation.
964  */
965 guint32
966 mono_arch_regalloc_cost (MonoCompile *cfg, MonoMethodVar *vmv)
967 {
968         MonoInst *ins = cfg->varinfo [vmv->idx];
969
970         if (cfg->method->save_lmf)
971                 /* The register is already saved */
972                 /* substract 1 for the invisible store in the prolog */
973                 return (ins->opcode == OP_ARG) ? 0 : 1;
974         else
975                 /* push+pop */
976                 return (ins->opcode == OP_ARG) ? 1 : 2;
977 }
978  
979 void
980 mono_arch_allocate_vars (MonoCompile *cfg)
981 {
982         MonoMethodSignature *sig;
983         MonoMethodHeader *header;
984         MonoInst *inst;
985         int i, offset;
986         guint32 locals_stack_size, locals_stack_align;
987         gint32 *offsets;
988         CallInfo *cinfo;
989
990         header = mono_method_get_header (cfg->method);
991
992         sig = mono_method_signature (cfg->method);
993
994         cinfo = cfg->arch.cinfo;
995
996         mono_arch_compute_omit_fp (cfg);
997
998         /*
999          * We use the ABI calling conventions for managed code as well.
1000          * Exception: valuetypes are never passed or returned in registers.
1001          */
1002
1003         if (cfg->arch.omit_fp) {
1004                 cfg->flags |= MONO_CFG_HAS_SPILLUP;
1005                 cfg->frame_reg = AMD64_RSP;
1006                 offset = 0;
1007         } else {
1008                 /* Locals are allocated backwards from %fp */
1009                 cfg->frame_reg = AMD64_RBP;
1010                 offset = 0;
1011         }
1012
1013         if (cfg->method->save_lmf) {
1014                 /* Reserve stack space for saving LMF */
1015                 /* mono_arch_find_jit_info () expects to find the LMF at a fixed offset */
1016                 g_assert (offset == 0);
1017                 if (cfg->arch.omit_fp) {
1018                         cfg->arch.lmf_offset = offset;
1019                         offset += sizeof (MonoLMF);
1020                 }
1021                 else {
1022                         offset += sizeof (MonoLMF);
1023                         cfg->arch.lmf_offset = -offset;
1024                 }
1025         } else {
1026                 /* Reserve space for caller saved registers */
1027                 for (i = 0; i < AMD64_NREG; ++i)
1028                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
1029                                 offset += sizeof (gpointer);
1030                         }
1031         }
1032
1033         if (sig->ret->type != MONO_TYPE_VOID) {
1034                 switch (cinfo->ret.storage) {
1035                 case ArgInIReg:
1036                 case ArgInFloatSSEReg:
1037                 case ArgInDoubleSSEReg:
1038                         if ((MONO_TYPE_ISSTRUCT (sig->ret) && !mono_class_from_mono_type (sig->ret)->enumtype) || (sig->ret->type == MONO_TYPE_TYPEDBYREF)) {
1039                                 /* The register is volatile */
1040                                 cfg->vret_addr->opcode = OP_REGOFFSET;
1041                                 cfg->vret_addr->inst_basereg = cfg->frame_reg;
1042                                 if (cfg->arch.omit_fp) {
1043                                         cfg->vret_addr->inst_offset = offset;
1044                                         offset += 8;
1045                                 } else {
1046                                         offset += 8;
1047                                         cfg->vret_addr->inst_offset = -offset;
1048                                 }
1049                                 if (G_UNLIKELY (cfg->verbose_level > 1)) {
1050                                         printf ("vret_addr =");
1051                                         mono_print_ins (cfg->vret_addr);
1052                                 }
1053                         }
1054                         else {
1055                                 cfg->ret->opcode = OP_REGVAR;
1056                                 cfg->ret->inst_c0 = cinfo->ret.reg;
1057                         }
1058                         break;
1059                 case ArgValuetypeInReg:
1060                         /* Allocate a local to hold the result, the epilog will copy it to the correct place */
1061                         cfg->ret->opcode = OP_REGOFFSET;
1062                         cfg->ret->inst_basereg = cfg->frame_reg;
1063                         if (cfg->arch.omit_fp) {
1064                                 cfg->ret->inst_offset = offset;
1065                                 offset += 16;
1066                         } else {
1067                                 offset += 16;
1068                                 cfg->ret->inst_offset = - offset;
1069                         }
1070                         break;
1071                 default:
1072                         g_assert_not_reached ();
1073                 }
1074                 cfg->ret->dreg = cfg->ret->inst_c0;
1075         }
1076
1077         /* Allocate locals */
1078         offsets = mono_allocate_stack_slots_full (cfg, cfg->arch.omit_fp ? FALSE: TRUE, &locals_stack_size, &locals_stack_align);
1079         if (locals_stack_align) {
1080                 offset += (locals_stack_align - 1);
1081                 offset &= ~(locals_stack_align - 1);
1082         }
1083         for (i = cfg->locals_start; i < cfg->num_varinfo; i++) {
1084                 if (offsets [i] != -1) {
1085                         MonoInst *inst = cfg->varinfo [i];
1086                         inst->opcode = OP_REGOFFSET;
1087                         inst->inst_basereg = cfg->frame_reg;
1088                         if (cfg->arch.omit_fp)
1089                                 inst->inst_offset = (offset + offsets [i]);
1090                         else
1091                                 inst->inst_offset = - (offset + offsets [i]);
1092                         //printf ("allocated local %d to ", i); mono_print_tree_nl (inst);
1093                 }
1094         }
1095         offset += locals_stack_size;
1096
1097         if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG)) {
1098                 g_assert (!cfg->arch.omit_fp);
1099                 g_assert (cinfo->sig_cookie.storage == ArgOnStack);
1100                 cfg->sig_cookie = cinfo->sig_cookie.offset + ARGS_OFFSET;
1101         }
1102
1103         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
1104                 inst = cfg->args [i];
1105                 if (inst->opcode != OP_REGVAR) {
1106                         ArgInfo *ainfo = &cinfo->args [i];
1107                         gboolean inreg = TRUE;
1108                         MonoType *arg_type;
1109
1110                         if (sig->hasthis && (i == 0))
1111                                 arg_type = &mono_defaults.object_class->byval_arg;
1112                         else
1113                                 arg_type = sig->params [i - sig->hasthis];
1114
1115                         /* FIXME: Allocate volatile arguments to registers */
1116                         if (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))
1117                                 inreg = FALSE;
1118
1119                         /* 
1120                          * Under AMD64, all registers used to pass arguments to functions
1121                          * are volatile across calls.
1122                          * FIXME: Optimize this.
1123                          */
1124                         if ((ainfo->storage == ArgInIReg) || (ainfo->storage == ArgInFloatSSEReg) || (ainfo->storage == ArgInDoubleSSEReg) || (ainfo->storage == ArgValuetypeInReg))
1125                                 inreg = FALSE;
1126
1127                         inst->opcode = OP_REGOFFSET;
1128
1129                         switch (ainfo->storage) {
1130                         case ArgInIReg:
1131                         case ArgInFloatSSEReg:
1132                         case ArgInDoubleSSEReg:
1133                                 inst->opcode = OP_REGVAR;
1134                                 inst->dreg = ainfo->reg;
1135                                 break;
1136                         case ArgOnStack:
1137                                 g_assert (!cfg->arch.omit_fp);
1138                                 inst->opcode = OP_REGOFFSET;
1139                                 inst->inst_basereg = cfg->frame_reg;
1140                                 inst->inst_offset = ainfo->offset + ARGS_OFFSET;
1141                                 break;
1142                         case ArgValuetypeInReg:
1143                                 break;
1144                         default:
1145                                 NOT_IMPLEMENTED;
1146                         }
1147
1148                         if (!inreg && (ainfo->storage != ArgOnStack)) {
1149                                 inst->opcode = OP_REGOFFSET;
1150                                 inst->inst_basereg = cfg->frame_reg;
1151                                 /* These arguments are saved to the stack in the prolog */
1152                                 offset = ALIGN_TO (offset, sizeof (gpointer));
1153                                 if (cfg->arch.omit_fp) {
1154                                         inst->inst_offset = offset;
1155                                         offset += (ainfo->storage == ArgValuetypeInReg) ? 2 * sizeof (gpointer) : sizeof (gpointer);
1156                                 } else {
1157                                         offset += (ainfo->storage == ArgValuetypeInReg) ? 2 * sizeof (gpointer) : sizeof (gpointer);
1158                                         inst->inst_offset = - offset;
1159                                 }
1160                         }
1161                 }
1162         }
1163
1164         cfg->stack_offset = offset;
1165 }
1166
1167 void
1168 mono_arch_create_vars (MonoCompile *cfg)
1169 {
1170         MonoMethodSignature *sig;
1171         CallInfo *cinfo;
1172
1173         sig = mono_method_signature (cfg->method);
1174
1175         if (!cfg->arch.cinfo)
1176                 cfg->arch.cinfo = get_call_info (cfg, cfg->mempool, sig, FALSE);
1177         cinfo = cfg->arch.cinfo;
1178
1179         if (cinfo->ret.storage == ArgValuetypeInReg)
1180                 cfg->ret_var_is_local = TRUE;
1181
1182         if ((cinfo->ret.storage != ArgValuetypeInReg) && MONO_TYPE_ISSTRUCT (sig->ret)) {
1183                 cfg->vret_addr = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_ARG);
1184                 if (G_UNLIKELY (cfg->verbose_level > 1)) {
1185                         printf ("vret_addr = ");
1186                         mono_print_ins (cfg->vret_addr);
1187                 }
1188         }
1189 }
1190
1191 static void
1192 add_outarg_reg (MonoCompile *cfg, MonoCallInst *call, MonoInst *arg, ArgStorage storage, int reg, MonoInst *tree)
1193 {
1194         switch (storage) {
1195         case ArgInIReg:
1196                 arg->opcode = OP_OUTARG_REG;
1197                 arg->inst_left = tree;
1198                 arg->inst_call = call;
1199                 arg->backend.reg3 = reg;
1200                 break;
1201         case ArgInFloatSSEReg:
1202                 arg->opcode = OP_AMD64_OUTARG_XMMREG_R4;
1203                 arg->inst_left = tree;
1204                 arg->inst_call = call;
1205                 arg->backend.reg3 = reg;
1206                 break;
1207         case ArgInDoubleSSEReg:
1208                 arg->opcode = OP_AMD64_OUTARG_XMMREG_R8;
1209                 arg->inst_left = tree;
1210                 arg->inst_call = call;
1211                 arg->backend.reg3 = reg;
1212                 break;
1213         default:
1214                 g_assert_not_reached ();
1215         }
1216 }
1217
1218 /* Fixme: we need an alignment solution for enter_method and mono_arch_call_opcode,
1219  * currently alignment in mono_arch_call_opcode is computed without arch_get_argument_info 
1220  */
1221
1222 static int
1223 arg_storage_to_ldind (ArgStorage storage)
1224 {
1225         switch (storage) {
1226         case ArgInIReg:
1227                 return CEE_LDIND_I;
1228         case ArgInDoubleSSEReg:
1229                 return CEE_LDIND_R8;
1230         case ArgInFloatSSEReg:
1231                 return CEE_LDIND_R4;
1232         default:
1233                 g_assert_not_reached ();
1234         }
1235
1236         return -1;
1237 }
1238
1239 static void
1240 emit_sig_cookie (MonoCompile *cfg, MonoCallInst *call, CallInfo *cinfo)
1241 {
1242         MonoInst *arg;
1243         MonoMethodSignature *tmp_sig;
1244         MonoInst *sig_arg;
1245                         
1246         /* FIXME: Add support for signature tokens to AOT */
1247         cfg->disable_aot = TRUE;
1248
1249         g_assert (cinfo->sig_cookie.storage == ArgOnStack);
1250
1251         /*
1252          * mono_ArgIterator_Setup assumes the signature cookie is 
1253          * passed first and all the arguments which were before it are
1254          * passed on the stack after the signature. So compensate by 
1255          * passing a different signature.
1256          */
1257         tmp_sig = mono_metadata_signature_dup (call->signature);
1258         tmp_sig->param_count -= call->signature->sentinelpos;
1259         tmp_sig->sentinelpos = 0;
1260         memcpy (tmp_sig->params, call->signature->params + call->signature->sentinelpos, tmp_sig->param_count * sizeof (MonoType*));
1261
1262         MONO_INST_NEW (cfg, sig_arg, OP_ICONST);
1263         sig_arg->inst_p0 = tmp_sig;
1264
1265         MONO_INST_NEW (cfg, arg, OP_OUTARG);
1266         arg->inst_left = sig_arg;
1267         arg->type = STACK_PTR;
1268         MONO_INST_LIST_ADD (&arg->node, &call->out_args);
1269 }
1270
1271 /* 
1272  * take the arguments and generate the arch-specific
1273  * instructions to properly call the function in call.
1274  * This includes pushing, moving arguments to the right register
1275  * etc.
1276  * Issue: who does the spilling if needed, and when?
1277  */
1278 MonoCallInst*
1279 mono_arch_call_opcode (MonoCompile *cfg, MonoBasicBlock* bb, MonoCallInst *call, int is_virtual) {
1280         MonoInst *arg, *in;
1281         MonoMethodSignature *sig;
1282         int i, n, stack_size;
1283         CallInfo *cinfo;
1284         ArgInfo *ainfo;
1285
1286         stack_size = 0;
1287
1288         sig = call->signature;
1289         n = sig->param_count + sig->hasthis;
1290
1291         cinfo = get_call_info (cfg, cfg->mempool, sig, sig->pinvoke);
1292
1293         for (i = 0; i < n; ++i) {
1294                 ainfo = cinfo->args + i;
1295
1296                 if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG) && (i == sig->sentinelpos)) {
1297                         /* Emit the signature cookie just before the implicit arguments */
1298                         emit_sig_cookie (cfg, call, cinfo);
1299                 }
1300
1301                 if (is_virtual && i == 0) {
1302                         /* the argument will be attached to the call instruction */
1303                         in = call->args [i];
1304                 } else {
1305                         MONO_INST_NEW (cfg, arg, OP_OUTARG);
1306                         in = call->args [i];
1307                         arg->cil_code = in->cil_code;
1308                         arg->inst_left = in;
1309                         arg->type = in->type;
1310                         if (!cinfo->stack_usage)
1311                                 /* Keep the assignments to the arg registers in order if possible */
1312                                 MONO_INST_LIST_ADD_TAIL (&arg->node, &call->out_args);
1313                         else
1314                                 MONO_INST_LIST_ADD (&arg->node, &call->out_args);
1315
1316                         if ((i >= sig->hasthis) && (MONO_TYPE_ISSTRUCT(sig->params [i - sig->hasthis]))) {
1317                                 guint32 align;
1318                                 guint32 size;
1319
1320                                 if (sig->params [i - sig->hasthis]->type == MONO_TYPE_TYPEDBYREF) {
1321                                         size = sizeof (MonoTypedRef);
1322                                         align = sizeof (gpointer);
1323                                 }
1324                                 else
1325                                 if (sig->pinvoke)
1326                                         size = mono_type_native_stack_size (&in->klass->byval_arg, &align);
1327                                 else {
1328                                         /* 
1329                                          * Other backends use mini_type_stack_size (), but that
1330                                          * aligns the size to 8, which is larger than the size of
1331                                          * the source, leading to reads of invalid memory if the
1332                                          * source is at the end of address space.
1333                                          */
1334                                         size = mono_class_value_size (in->klass, &align);
1335                                 }
1336                                 if (ainfo->storage == ArgValuetypeInReg) {
1337                                         if (ainfo->pair_storage [1] == ArgNone) {
1338                                                 MonoInst *load;
1339
1340                                                 /* Simpler case */
1341
1342                                                 MONO_INST_NEW (cfg, load, arg_storage_to_ldind (ainfo->pair_storage [0]));
1343                                                 load->inst_left = in;
1344
1345                                                 add_outarg_reg (cfg, call, arg, ainfo->pair_storage [0], ainfo->pair_regs [0], load);
1346                                         }
1347                                         else {
1348                                                 /* Trees can't be shared so make a copy */
1349                                                 MonoInst *vtaddr = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1350                                                 MonoInst *load, *load2, *offset_ins;
1351
1352                                                 /* Reg1 */
1353                                                 MONO_INST_NEW (cfg, load, CEE_LDIND_I);
1354                                                 load->ssa_op = MONO_SSA_LOAD;
1355                                                 load->inst_i0 = (cfg)->varinfo [vtaddr->inst_c0];
1356
1357                                                 NEW_ICONST (cfg, offset_ins, 0);
1358                                                 MONO_INST_NEW (cfg, load2, CEE_ADD);
1359                                                 load2->inst_left = load;
1360                                                 load2->inst_right = offset_ins;
1361
1362                                                 MONO_INST_NEW (cfg, load, arg_storage_to_ldind (ainfo->pair_storage [0]));
1363                                                 load->inst_left = load2;
1364
1365                                                 add_outarg_reg (cfg, call, arg, ainfo->pair_storage [0], ainfo->pair_regs [0], load);
1366
1367                                                 /* Reg2 */
1368                                                 MONO_INST_NEW (cfg, load, CEE_LDIND_I);
1369                                                 load->ssa_op = MONO_SSA_LOAD;
1370                                                 load->inst_i0 = (cfg)->varinfo [vtaddr->inst_c0];
1371
1372                                                 NEW_ICONST (cfg, offset_ins, 8);
1373                                                 MONO_INST_NEW (cfg, load2, CEE_ADD);
1374                                                 load2->inst_left = load;
1375                                                 load2->inst_right = offset_ins;
1376
1377                                                 MONO_INST_NEW (cfg, load, arg_storage_to_ldind (ainfo->pair_storage [1]));
1378                                                 load->inst_left = load2;
1379
1380                                                 MONO_INST_NEW (cfg, arg, OP_OUTARG);
1381                                                 arg->cil_code = in->cil_code;
1382                                                 arg->type = in->type;
1383                                                 MONO_INST_LIST_ADD (&arg->node, &call->out_args);
1384
1385                                                 add_outarg_reg (cfg, call, arg, ainfo->pair_storage [1], ainfo->pair_regs [1], load);
1386
1387                                                 /* Prepend a copy inst */
1388                                                 MONO_INST_NEW (cfg, arg, CEE_STIND_I);
1389                                                 arg->cil_code = in->cil_code;
1390                                                 arg->ssa_op = MONO_SSA_STORE;
1391                                                 arg->inst_left = vtaddr;
1392                                                 arg->inst_right = in;
1393                                                 arg->type = in->type;
1394
1395                                                 MONO_INST_LIST_ADD (&arg->node, &call->out_args);
1396                                         }
1397                                 }
1398                                 else {
1399                                         arg->opcode = OP_OUTARG_VT;
1400                                         arg->klass = in->klass;
1401                                         arg->backend.is_pinvoke = sig->pinvoke;
1402                                         arg->inst_imm = size;
1403                                 }
1404                         }
1405                         else {
1406                                 switch (ainfo->storage) {
1407                                 case ArgInIReg:
1408                                         add_outarg_reg (cfg, call, arg, ainfo->storage, ainfo->reg, in);
1409                                         break;
1410                                 case ArgInFloatSSEReg:
1411                                 case ArgInDoubleSSEReg:
1412                                         add_outarg_reg (cfg, call, arg, ainfo->storage, ainfo->reg, in);
1413                                         break;
1414                                 case ArgOnStack:
1415                                         arg->opcode = OP_OUTARG;
1416                                         if (!sig->params [i - sig->hasthis]->byref) {
1417                                                 if (sig->params [i - sig->hasthis]->type == MONO_TYPE_R4)
1418                                                         arg->opcode = OP_OUTARG_R4;
1419                                                 else
1420                                                         if (sig->params [i - sig->hasthis]->type == MONO_TYPE_R8)
1421                                                                 arg->opcode = OP_OUTARG_R8;
1422                                         }
1423                                         break;
1424                                 default:
1425                                         g_assert_not_reached ();
1426                                 }
1427                         }
1428                 }
1429         }
1430
1431         /* Handle the case where there are no implicit arguments */
1432         if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG) && (n == sig->sentinelpos)) {
1433                 emit_sig_cookie (cfg, call, cinfo);
1434         }
1435
1436         if (cinfo->need_stack_align) {
1437                 MONO_INST_NEW (cfg, arg, OP_AMD64_OUTARG_ALIGN_STACK);
1438                 MONO_INST_LIST_ADD (&arg->node, &call->out_args);
1439         }
1440
1441         if (cfg->method->save_lmf) {
1442                 MONO_INST_NEW (cfg, arg, OP_AMD64_SAVE_SP_TO_LMF);
1443                 MONO_INST_LIST_ADD_TAIL (&arg->node, &call->out_args);
1444         }
1445
1446         call->stack_usage = cinfo->stack_usage;
1447         cfg->param_area = MAX (cfg->param_area, call->stack_usage);
1448         cfg->flags |= MONO_CFG_HAS_CALLS;
1449
1450         return call;
1451 }
1452
1453 #define EMIT_COND_BRANCH(ins,cond,sign) \
1454 if (ins->flags & MONO_INST_BRLABEL) { \
1455         if (ins->inst_i0->inst_c0) { \
1456                 x86_branch (code, cond, cfg->native_code + ins->inst_i0->inst_c0, sign); \
1457         } else { \
1458                 mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_LABEL, ins->inst_i0); \
1459                 if ((cfg->opt & MONO_OPT_BRANCH) && \
1460                     x86_is_imm8 (ins->inst_i0->inst_c1 - cpos)) \
1461                         x86_branch8 (code, cond, 0, sign); \
1462                 else \
1463                         x86_branch32 (code, cond, 0, sign); \
1464         } \
1465 } else { \
1466         if (ins->inst_true_bb->native_offset) { \
1467                 x86_branch (code, cond, cfg->native_code + ins->inst_true_bb->native_offset, sign); \
1468         } else { \
1469                 mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_BB, ins->inst_true_bb); \
1470                 if ((cfg->opt & MONO_OPT_BRANCH) && \
1471                     x86_is_imm8 (ins->inst_true_bb->max_offset - cpos)) \
1472                         x86_branch8 (code, cond, 0, sign); \
1473                 else \
1474                         x86_branch32 (code, cond, 0, sign); \
1475         } \
1476 }
1477
1478 /* emit an exception if condition is fail */
1479 #define EMIT_COND_SYSTEM_EXCEPTION(cond,signed,exc_name)            \
1480         do {                                                        \
1481                 MonoInst *tins = mono_branch_optimize_exception_target (cfg, bb, exc_name); \
1482                 if (tins == NULL) {                                                                             \
1483                         mono_add_patch_info (cfg, code - cfg->native_code,   \
1484                                         MONO_PATCH_INFO_EXC, exc_name);  \
1485                         x86_branch32 (code, cond, 0, signed);               \
1486                 } else {        \
1487                         EMIT_COND_BRANCH (tins, cond, signed);  \
1488                 }                       \
1489         } while (0); 
1490
1491 #define EMIT_FPCOMPARE(code) do { \
1492         amd64_fcompp (code); \
1493         amd64_fnstsw (code); \
1494 } while (0); 
1495
1496 #define EMIT_SSE2_FPFUNC(code, op, dreg, sreg1) do { \
1497     amd64_movsd_membase_reg (code, AMD64_RSP, -8, (sreg1)); \
1498         amd64_fld_membase (code, AMD64_RSP, -8, TRUE); \
1499         amd64_ ##op (code); \
1500         amd64_fst_membase (code, AMD64_RSP, -8, TRUE, TRUE); \
1501         amd64_movsd_reg_membase (code, (dreg), AMD64_RSP, -8); \
1502 } while (0);
1503
1504 static guint8*
1505 emit_call_body (MonoCompile *cfg, guint8 *code, guint32 patch_type, gconstpointer data)
1506 {
1507         mono_add_patch_info (cfg, code - cfg->native_code, patch_type, data);
1508
1509         /* 
1510          * FIXME: Add support for thunks
1511          */
1512         {
1513                 gboolean near_call = FALSE;
1514
1515                 /*
1516                  * Indirect calls are expensive so try to make a near call if possible.
1517                  * The caller memory is allocated by the code manager so it is 
1518                  * guaranteed to be at a 32 bit offset.
1519                  */
1520
1521                 if (patch_type != MONO_PATCH_INFO_ABS) {
1522                         /* The target is in memory allocated using the code manager */
1523                         near_call = TRUE;
1524
1525                         if ((patch_type == MONO_PATCH_INFO_METHOD) || (patch_type == MONO_PATCH_INFO_METHOD_JUMP)) {
1526                                 if (((MonoMethod*)data)->klass->image->assembly->aot_module)
1527                                         /* The callee might be an AOT method */
1528                                         near_call = FALSE;
1529                                 if (((MonoMethod*)data)->dynamic)
1530                                         /* The target is in malloc-ed memory */
1531                                         near_call = FALSE;
1532                         }
1533
1534                         if (patch_type == MONO_PATCH_INFO_INTERNAL_METHOD) {
1535                                 /* 
1536                                  * The call might go directly to a native function without
1537                                  * the wrapper.
1538                                  */
1539                                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (data);
1540                                 if (mi) {
1541                                         gconstpointer target = mono_icall_get_wrapper (mi);
1542                                         if ((((guint64)target) >> 32) != 0)
1543                                                 near_call = FALSE;
1544                                 }
1545                         }
1546                 }
1547                 else {
1548                         if (mono_find_class_init_trampoline_by_addr (data))
1549                                 near_call = TRUE;
1550                         else {
1551                                 MonoJitICallInfo *info = mono_find_jit_icall_by_addr (data);
1552                                 if (info) {
1553                                         if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && 
1554                                                 strstr (cfg->method->name, info->name)) {
1555                                                 /* A call to the wrapped function */
1556                                                 if ((((guint64)data) >> 32) == 0)
1557                                                         near_call = TRUE;
1558                                         }
1559                                         else if (info->func == info->wrapper) {
1560                                                 /* No wrapper */
1561                                                 if ((((guint64)info->func) >> 32) == 0)
1562                                                         near_call = TRUE;
1563                                         }
1564                                         else {
1565                                                 /* See the comment in mono_codegen () */
1566                                                 if ((info->name [0] != 'v') || (strstr (info->name, "ves_array_new_va_") == NULL && strstr (info->name, "ves_array_element_address_") == NULL))
1567                                                         near_call = TRUE;
1568                                         }
1569                                 }
1570                                 else if ((((guint64)data) >> 32) == 0)
1571                                         near_call = TRUE;
1572                         }
1573                 }
1574
1575                 if (cfg->method->dynamic)
1576                         /* These methods are allocated using malloc */
1577                         near_call = FALSE;
1578
1579                 if (cfg->compile_aot)
1580                         near_call = TRUE;
1581
1582 #ifdef MONO_ARCH_NOMAP32BIT
1583                 near_call = FALSE;
1584 #endif
1585
1586                 if (near_call) {
1587                         amd64_call_code (code, 0);
1588                 }
1589                 else {
1590                         amd64_set_reg_template (code, GP_SCRATCH_REG);
1591                         amd64_call_reg (code, GP_SCRATCH_REG);
1592                 }
1593         }
1594
1595         return code;
1596 }
1597
1598 static inline guint8*
1599 emit_call (MonoCompile *cfg, guint8 *code, guint32 patch_type, gconstpointer data)
1600 {
1601         mono_add_patch_info (cfg, code - cfg->native_code, patch_type, data);
1602
1603         return emit_call_body (cfg, code, patch_type, data);
1604 }
1605
1606 static inline int
1607 store_membase_imm_to_store_membase_reg (int opcode)
1608 {
1609         switch (opcode) {
1610         case OP_STORE_MEMBASE_IMM:
1611                 return OP_STORE_MEMBASE_REG;
1612         case OP_STOREI4_MEMBASE_IMM:
1613                 return OP_STOREI4_MEMBASE_REG;
1614         case OP_STOREI8_MEMBASE_IMM:
1615                 return OP_STOREI8_MEMBASE_REG;
1616         }
1617
1618         return -1;
1619 }
1620
1621 #define INST_IGNORES_CFLAGS(opcode) (!(((opcode) == OP_ADC) || ((opcode) == OP_ADC_IMM) || ((opcode) == OP_IADC) || ((opcode) == OP_IADC_IMM) || ((opcode) == OP_SBB) || ((opcode) == OP_SBB_IMM) || ((opcode) == OP_ISBB) || ((opcode) == OP_ISBB_IMM)))
1622
1623 /*
1624  * mono_arch_peephole_pass_1:
1625  *
1626  *   Perform peephole opts which should/can be performed before local regalloc
1627  */
1628 void
1629 mono_arch_peephole_pass_1 (MonoCompile *cfg, MonoBasicBlock *bb)
1630 {
1631         MonoInst *ins, *n;
1632
1633         MONO_INST_LIST_FOR_EACH_ENTRY_SAFE (ins, n, &bb->ins_list, node) {
1634                 MonoInst *last_ins = mono_inst_list_prev (&ins->node, &bb->ins_list);
1635
1636                 switch (ins->opcode) {
1637                 case OP_ADD_IMM:
1638                 case OP_IADD_IMM:
1639                 case OP_LADD_IMM:
1640                         if ((ins->sreg1 < MONO_MAX_IREGS) && (ins->dreg >= MONO_MAX_IREGS) && (ins->inst_imm > 0)) {
1641                                 /* 
1642                                  * X86_LEA is like ADD, but doesn't have the
1643                                  * sreg1==dreg restriction. inst_imm > 0 is needed since LEA sign-extends 
1644                                  * its operand to 64 bit.
1645                                  */
1646                                 ins->opcode = OP_X86_LEA_MEMBASE;
1647                                 ins->inst_basereg = ins->sreg1;
1648                                 /* Fall through */
1649                         }
1650                         else
1651                                 break;
1652                 case OP_LXOR:
1653                 case OP_IXOR:
1654                         if ((ins->sreg1 == ins->sreg2) && (ins->sreg1 == ins->dreg)) {
1655                                 MonoInst *ins2;
1656
1657                                 /* 
1658                                  * Replace STORE_MEMBASE_IMM 0 with STORE_MEMBASE_REG since 
1659                                  * the latter has length 2-3 instead of 6 (reverse constant
1660                                  * propagation). These instruction sequences are very common
1661                                  * in the initlocals bblock.
1662                                  */
1663                                 for (ins2 = mono_inst_list_next (&ins->node, &bb->ins_list); ins2;
1664                                                 ins2 = mono_inst_list_next (&ins2->node, &bb->ins_list)) {
1665                                         if (((ins2->opcode == OP_STORE_MEMBASE_IMM) || (ins2->opcode == OP_STOREI4_MEMBASE_IMM) || (ins2->opcode == OP_STOREI8_MEMBASE_IMM) || (ins2->opcode == OP_STORE_MEMBASE_IMM)) && (ins2->inst_imm == 0)) {
1666                                                 ins2->opcode = store_membase_imm_to_store_membase_reg (ins2->opcode);
1667                                                 ins2->sreg1 = ins->dreg;
1668                                         } else if ((ins2->opcode == OP_STOREI1_MEMBASE_IMM) || (ins2->opcode == OP_STOREI2_MEMBASE_IMM) || (ins2->opcode == OP_STOREI8_MEMBASE_REG) || (ins2->opcode == OP_STORE_MEMBASE_REG)) {
1669                                                 /* Continue */
1670                                         } else if (((ins2->opcode == OP_ICONST) || (ins2->opcode == OP_I8CONST)) && (ins2->dreg == ins->dreg) && (ins2->inst_c0 == 0)) {
1671                                                 NULLIFY_INS (ins2);
1672                                                 /* Continue */
1673                                         } else {
1674                                                 break;
1675                                         }
1676                                 }
1677                         }
1678                         break;
1679                 case OP_COMPARE_IMM:
1680                 case OP_LCOMPARE_IMM:
1681                         /* OP_COMPARE_IMM (reg, 0) 
1682                          * --> 
1683                          * OP_AMD64_TEST_NULL (reg) 
1684                          */
1685                         if (!ins->inst_imm)
1686                                 ins->opcode = OP_AMD64_TEST_NULL;
1687                         break;
1688                 case OP_ICOMPARE_IMM:
1689                         if (!ins->inst_imm)
1690                                 ins->opcode = OP_X86_TEST_NULL;
1691                         break;
1692                 case OP_AMD64_ICOMPARE_MEMBASE_IMM:
1693                         /* 
1694                          * OP_STORE_MEMBASE_REG reg, offset(basereg)
1695                          * OP_X86_COMPARE_MEMBASE_IMM offset(basereg), imm
1696                          * -->
1697                          * OP_STORE_MEMBASE_REG reg, offset(basereg)
1698                          * OP_COMPARE_IMM reg, imm
1699                          *
1700                          * Note: if imm = 0 then OP_COMPARE_IMM replaced with OP_X86_TEST_NULL
1701                          */
1702                         if (last_ins && (last_ins->opcode == OP_STOREI4_MEMBASE_REG) &&
1703                             ins->inst_basereg == last_ins->inst_destbasereg &&
1704                             ins->inst_offset == last_ins->inst_offset) {
1705                                         ins->opcode = OP_ICOMPARE_IMM;
1706                                         ins->sreg1 = last_ins->sreg1;
1707
1708                                         /* check if we can remove cmp reg,0 with test null */
1709                                         if (!ins->inst_imm)
1710                                                 ins->opcode = OP_X86_TEST_NULL;
1711                                 }
1712
1713                         break;
1714                 case OP_LOAD_MEMBASE:
1715                 case OP_LOADI4_MEMBASE:
1716                         /* 
1717                          * Note: if reg1 = reg2 the load op is removed
1718                          *
1719                          * OP_STORE_MEMBASE_REG reg1, offset(basereg) 
1720                          * OP_LOAD_MEMBASE offset(basereg), reg2
1721                          * -->
1722                          * OP_STORE_MEMBASE_REG reg1, offset(basereg)
1723                          * OP_MOVE reg1, reg2
1724                          */
1725                         if (last_ins && (last_ins->opcode == OP_STOREI4_MEMBASE_REG 
1726                                          || last_ins->opcode == OP_STORE_MEMBASE_REG) &&
1727                             ins->inst_basereg == last_ins->inst_destbasereg &&
1728                             ins->inst_offset == last_ins->inst_offset) {
1729                                 if (ins->dreg == last_ins->sreg1) {
1730                                         MONO_DEL_INS (ins);
1731                                         continue;
1732                                 } else {
1733                                         //static int c = 0; printf ("MATCHX %s %d\n", cfg->method->name,c++);
1734                                         ins->opcode = OP_MOVE;
1735                                         ins->sreg1 = last_ins->sreg1;
1736                                 }
1737
1738                         /* 
1739                          * Note: reg1 must be different from the basereg in the second load
1740                          * Note: if reg1 = reg2 is equal then second load is removed
1741                          *
1742                          * OP_LOAD_MEMBASE offset(basereg), reg1
1743                          * OP_LOAD_MEMBASE offset(basereg), reg2
1744                          * -->
1745                          * OP_LOAD_MEMBASE offset(basereg), reg1
1746                          * OP_MOVE reg1, reg2
1747                          */
1748                         } if (last_ins && (last_ins->opcode == OP_LOADI4_MEMBASE
1749                                            || last_ins->opcode == OP_LOAD_MEMBASE) &&
1750                               ins->inst_basereg != last_ins->dreg &&
1751                               ins->inst_basereg == last_ins->inst_basereg &&
1752                               ins->inst_offset == last_ins->inst_offset) {
1753
1754                                 if (ins->dreg == last_ins->dreg) {
1755                                         MONO_DEL_INS (ins);
1756                                         continue;
1757                                 } else {
1758                                         ins->opcode = OP_MOVE;
1759                                         ins->sreg1 = last_ins->dreg;
1760                                 }
1761
1762                                 //g_assert_not_reached ();
1763
1764 #if 0
1765                         /* 
1766                          * OP_STORE_MEMBASE_IMM imm, offset(basereg) 
1767                          * OP_LOAD_MEMBASE offset(basereg), reg
1768                          * -->
1769                          * OP_STORE_MEMBASE_IMM imm, offset(basereg) 
1770                          * OP_ICONST reg, imm
1771                          */
1772                         } else if (last_ins && (last_ins->opcode == OP_STOREI4_MEMBASE_IMM
1773                                                 || last_ins->opcode == OP_STORE_MEMBASE_IMM) &&
1774                                    ins->inst_basereg == last_ins->inst_destbasereg &&
1775                                    ins->inst_offset == last_ins->inst_offset) {
1776                                 //static int c = 0; printf ("MATCHX %s %d\n", cfg->method->name,c++);
1777                                 ins->opcode = OP_ICONST;
1778                                 ins->inst_c0 = last_ins->inst_imm;
1779                                 g_assert_not_reached (); // check this rule
1780 #endif
1781                         }
1782                         break;
1783                 case OP_LOADI1_MEMBASE:
1784                         /* 
1785                          * Note: if reg1 = reg2 the load op is removed
1786                          *
1787                          * OP_STORE_MEMBASE_REG reg1, offset(basereg) 
1788                          * OP_LOAD_MEMBASE offset(basereg), reg2
1789                          * -->
1790                          * OP_STORE_MEMBASE_REG reg1, offset(basereg)
1791                          * OP_MOVE reg1, reg2
1792                          */
1793                         if (last_ins && (last_ins->opcode == OP_STOREI1_MEMBASE_REG) &&
1794                                         ins->inst_basereg == last_ins->inst_destbasereg &&
1795                                         ins->inst_offset == last_ins->inst_offset) {
1796                                 if (ins->dreg == last_ins->sreg1) {
1797                                         MONO_DEL_INS (ins);
1798                                         continue;
1799                                 } else {
1800                                         //static int c = 0; printf ("MATCHX %s %d\n", cfg->method->name,c++);
1801                                         ins->opcode = OP_MOVE;
1802                                         ins->sreg1 = last_ins->sreg1;
1803                                 }
1804                         }
1805                         break;
1806                 case OP_LOADI2_MEMBASE:
1807                         /* 
1808                          * Note: if reg1 = reg2 the load op is removed
1809                          *
1810                          * OP_STORE_MEMBASE_REG reg1, offset(basereg) 
1811                          * OP_LOAD_MEMBASE offset(basereg), reg2
1812                          * -->
1813                          * OP_STORE_MEMBASE_REG reg1, offset(basereg)
1814                          * OP_MOVE reg1, reg2
1815                          */
1816                         if (last_ins && (last_ins->opcode == OP_STOREI2_MEMBASE_REG) &&
1817                                         ins->inst_basereg == last_ins->inst_destbasereg &&
1818                                         ins->inst_offset == last_ins->inst_offset) {
1819                                 if (ins->dreg == last_ins->sreg1) {
1820                                         MONO_DEL_INS (ins);
1821                                         continue;
1822                                 } else {
1823                                         //static int c = 0; printf ("MATCHX %s %d\n", cfg->method->name,c++);
1824                                         ins->opcode = OP_MOVE;
1825                                         ins->sreg1 = last_ins->sreg1;
1826                                 }
1827                         }
1828                         break;
1829                 case OP_MOVE:
1830                 case OP_FMOVE:
1831                         /*
1832                          * Removes:
1833                          *
1834                          * OP_MOVE reg, reg 
1835                          */
1836                         if (ins->dreg == ins->sreg1) {
1837                                 MONO_DEL_INS (ins);
1838                                 continue;
1839                         }
1840                         /* 
1841                          * Removes:
1842                          *
1843                          * OP_MOVE sreg, dreg 
1844                          * OP_MOVE dreg, sreg
1845                          */
1846                         if (last_ins && last_ins->opcode == OP_MOVE &&
1847                             ins->sreg1 == last_ins->dreg &&
1848                             ins->dreg == last_ins->sreg1) {
1849                                 MONO_DEL_INS (ins);
1850                                 continue;
1851                         }
1852                         break;
1853                 }
1854         }
1855 }
1856
1857 void
1858 mono_arch_peephole_pass_2 (MonoCompile *cfg, MonoBasicBlock *bb)
1859 {
1860         MonoInst *ins, *n;
1861
1862         MONO_INST_LIST_FOR_EACH_ENTRY_SAFE (ins, n, &bb->ins_list, node) {
1863                 MonoInst *last_ins = mono_inst_list_prev (&ins->node, &bb->ins_list);
1864
1865                 switch (ins->opcode) {
1866                 case OP_ICONST:
1867                 case OP_I8CONST: {
1868                         MonoInst *next;
1869
1870                         /* reg = 0 -> XOR (reg, reg) */
1871                         /* XOR sets cflags on x86, so we cant do it always */
1872                         next = mono_inst_list_next (&ins->node, &bb->ins_list);
1873                         if (ins->inst_c0 == 0 && (!next ||
1874                                         (next && INST_IGNORES_CFLAGS (next->opcode)))) {
1875                                 ins->opcode = OP_LXOR;
1876                                 ins->sreg1 = ins->dreg;
1877                                 ins->sreg2 = ins->dreg;
1878                                 /* Fall through */
1879                         } else {
1880                                 break;
1881                         }
1882                 }
1883                 case OP_LXOR:
1884                         /*
1885                          * Use IXOR to avoid a rex prefix if possible. The cpu will sign extend the 
1886                          * 0 result into 64 bits.
1887                          */
1888                         if ((ins->sreg1 == ins->sreg2) && (ins->sreg1 == ins->dreg)) {
1889                                 ins->opcode = OP_IXOR;
1890                         }
1891                         /* Fall through */
1892                 case OP_IXOR:
1893                         if ((ins->sreg1 == ins->sreg2) && (ins->sreg1 == ins->dreg)) {
1894                                 MonoInst *ins2;
1895
1896                                 /* 
1897                                  * Replace STORE_MEMBASE_IMM 0 with STORE_MEMBASE_REG since 
1898                                  * the latter has length 2-3 instead of 6 (reverse constant
1899                                  * propagation). These instruction sequences are very common
1900                                  * in the initlocals bblock.
1901                                  */
1902                                 for (ins2 = mono_inst_list_next (&ins->node, &bb->ins_list); ins2;
1903                                                 ins2 = mono_inst_list_next (&ins2->node, &bb->ins_list)) {
1904                                         if (((ins2->opcode == OP_STORE_MEMBASE_IMM) || (ins2->opcode == OP_STOREI4_MEMBASE_IMM) || (ins2->opcode == OP_STOREI8_MEMBASE_IMM) || (ins2->opcode == OP_STORE_MEMBASE_IMM)) && (ins2->inst_imm == 0)) {
1905                                                 ins2->opcode = store_membase_imm_to_store_membase_reg (ins2->opcode);
1906                                                 ins2->sreg1 = ins->dreg;
1907                                         } else if ((ins2->opcode == OP_STOREI1_MEMBASE_IMM) || (ins2->opcode == OP_STOREI2_MEMBASE_IMM) || (ins2->opcode == OP_STOREI4_MEMBASE_REG) || (ins2->opcode == OP_STOREI8_MEMBASE_REG) || (ins2->opcode == OP_STORE_MEMBASE_REG)) {
1908                                                 /* Continue */
1909                                         } else if (((ins2->opcode == OP_ICONST) || (ins2->opcode == OP_I8CONST)) && (ins2->dreg == ins->dreg) && (ins2->inst_c0 == 0)) {
1910                                                 NULLIFY_INS (ins2);
1911                                                 /* Continue */
1912                                         } else {
1913                                                 break;
1914                                         }
1915                                 }
1916                         }
1917                         break;
1918                 case OP_IADD_IMM:
1919                         if ((ins->inst_imm == 1) && (ins->dreg == ins->sreg1))
1920                                 ins->opcode = OP_X86_INC_REG;
1921                         break;
1922                 case OP_ISUB_IMM:
1923                         if ((ins->inst_imm == 1) && (ins->dreg == ins->sreg1))
1924                                 ins->opcode = OP_X86_DEC_REG;
1925                         break;
1926                 case OP_MUL_IMM: 
1927                         /* remove unnecessary multiplication with 1 */
1928                         if (ins->inst_imm == 1) {
1929                                 if (ins->dreg != ins->sreg1) {
1930                                         ins->opcode = OP_MOVE;
1931                                 } else {
1932                                         MONO_DEL_INS (ins);
1933                                         continue;
1934                                 }
1935                         }
1936                         break;
1937                 case OP_COMPARE_IMM:
1938                         /* OP_COMPARE_IMM (reg, 0) 
1939                          * --> 
1940                          * OP_AMD64_TEST_NULL (reg) 
1941                          */
1942                         if (!ins->inst_imm)
1943                                 ins->opcode = OP_AMD64_TEST_NULL;
1944                         break;
1945                 case OP_ICOMPARE_IMM:
1946                         if (!ins->inst_imm)
1947                                 ins->opcode = OP_X86_TEST_NULL;
1948                         break;
1949                 case OP_AMD64_ICOMPARE_MEMBASE_IMM:
1950                         /* 
1951                          * OP_STORE_MEMBASE_REG reg, offset(basereg)
1952                          * OP_X86_COMPARE_MEMBASE_IMM offset(basereg), imm
1953                          * -->
1954                          * OP_STORE_MEMBASE_REG reg, offset(basereg)
1955                          * OP_COMPARE_IMM reg, imm
1956                          *
1957                          * Note: if imm = 0 then OP_COMPARE_IMM replaced with OP_X86_TEST_NULL
1958                          */
1959                         if (last_ins && (last_ins->opcode == OP_STOREI4_MEMBASE_REG) &&
1960                             ins->inst_basereg == last_ins->inst_destbasereg &&
1961                             ins->inst_offset == last_ins->inst_offset) {
1962                                         ins->opcode = OP_ICOMPARE_IMM;
1963                                         ins->sreg1 = last_ins->sreg1;
1964
1965                                         /* check if we can remove cmp reg,0 with test null */
1966                                         if (!ins->inst_imm)
1967                                                 ins->opcode = OP_X86_TEST_NULL;
1968                                 }
1969
1970                         break;
1971                 case OP_LOAD_MEMBASE:
1972                 case OP_LOADI4_MEMBASE:
1973                         /* 
1974                          * Note: if reg1 = reg2 the load op is removed
1975                          *
1976                          * OP_STORE_MEMBASE_REG reg1, offset(basereg) 
1977                          * OP_LOAD_MEMBASE offset(basereg), reg2
1978                          * -->
1979                          * OP_STORE_MEMBASE_REG reg1, offset(basereg)
1980                          * OP_MOVE reg1, reg2
1981                          */
1982                         if (last_ins && (last_ins->opcode == OP_STOREI4_MEMBASE_REG 
1983                                          || last_ins->opcode == OP_STORE_MEMBASE_REG) &&
1984                             ins->inst_basereg == last_ins->inst_destbasereg &&
1985                             ins->inst_offset == last_ins->inst_offset) {
1986                                 if (ins->dreg == last_ins->sreg1) {
1987                                         MONO_DEL_INS (ins);
1988                                         continue;
1989                                 } else {
1990                                         //static int c = 0; printf ("MATCHX %s %d\n", cfg->method->name,c++);
1991                                         ins->opcode = OP_MOVE;
1992                                         ins->sreg1 = last_ins->sreg1;
1993                                 }
1994
1995                         /* 
1996                          * Note: reg1 must be different from the basereg in the second load
1997                          * Note: if reg1 = reg2 is equal then second load is removed
1998                          *
1999                          * OP_LOAD_MEMBASE offset(basereg), reg1
2000                          * OP_LOAD_MEMBASE offset(basereg), reg2
2001                          * -->
2002                          * OP_LOAD_MEMBASE offset(basereg), reg1
2003                          * OP_MOVE reg1, reg2
2004                          */
2005                         } if (last_ins && (last_ins->opcode == OP_LOADI4_MEMBASE
2006                                            || last_ins->opcode == OP_LOAD_MEMBASE) &&
2007                               ins->inst_basereg != last_ins->dreg &&
2008                               ins->inst_basereg == last_ins->inst_basereg &&
2009                               ins->inst_offset == last_ins->inst_offset) {
2010
2011                                 if (ins->dreg == last_ins->dreg) {
2012                                         MONO_DEL_INS (ins);
2013                                         continue;
2014                                 } else {
2015                                         ins->opcode = OP_MOVE;
2016                                         ins->sreg1 = last_ins->dreg;
2017                                 }
2018
2019                                 //g_assert_not_reached ();
2020
2021 #if 0
2022                         /* 
2023                          * OP_STORE_MEMBASE_IMM imm, offset(basereg) 
2024                          * OP_LOAD_MEMBASE offset(basereg), reg
2025                          * -->
2026                          * OP_STORE_MEMBASE_IMM imm, offset(basereg) 
2027                          * OP_ICONST reg, imm
2028                          */
2029                         } else if (last_ins && (last_ins->opcode == OP_STOREI4_MEMBASE_IMM
2030                                                 || last_ins->opcode == OP_STORE_MEMBASE_IMM) &&
2031                                    ins->inst_basereg == last_ins->inst_destbasereg &&
2032                                    ins->inst_offset == last_ins->inst_offset) {
2033                                 //static int c = 0; printf ("MATCHX %s %d\n", cfg->method->name,c++);
2034                                 ins->opcode = OP_ICONST;
2035                                 ins->inst_c0 = last_ins->inst_imm;
2036                                 g_assert_not_reached (); // check this rule
2037 #endif
2038                         }
2039                         break;
2040                 case OP_LOADI1_MEMBASE:
2041                 case OP_LOADU1_MEMBASE:
2042                         /* 
2043                          * OP_STORE_MEMBASE_REG reg1, offset(basereg) 
2044                          * OP_LOAD_MEMBASE offset(basereg), reg2
2045                          * -->
2046                          * OP_STORE_MEMBASE_REG reg1, offset(basereg)
2047                          * CONV_I1/U1 reg1, reg2
2048                          */
2049                         if (last_ins && (last_ins->opcode == OP_STOREI1_MEMBASE_REG) &&
2050                                         ins->inst_basereg == last_ins->inst_destbasereg &&
2051                                         ins->inst_offset == last_ins->inst_offset) {
2052                                 ins->opcode = (ins->opcode == OP_LOADI1_MEMBASE) ? OP_PCONV_TO_I1 : OP_PCONV_TO_U1;
2053                                 ins->sreg1 = last_ins->sreg1;
2054                         }
2055                         break;
2056                 case OP_LOADI2_MEMBASE:
2057                 case OP_LOADU2_MEMBASE:
2058                         /* 
2059                          * OP_STORE_MEMBASE_REG reg1, offset(basereg) 
2060                          * OP_LOAD_MEMBASE offset(basereg), reg2
2061                          * -->
2062                          * OP_STORE_MEMBASE_REG reg1, offset(basereg)
2063                          * CONV_I2/U2 reg1, reg2
2064                          */
2065                         if (last_ins && (last_ins->opcode == OP_STOREI2_MEMBASE_REG) &&
2066                                         ins->inst_basereg == last_ins->inst_destbasereg &&
2067                                         ins->inst_offset == last_ins->inst_offset) {
2068                                 ins->opcode = (ins->opcode == OP_LOADI2_MEMBASE) ? OP_PCONV_TO_I2 : OP_PCONV_TO_U2;
2069                                 ins->sreg1 = last_ins->sreg1;
2070                         }
2071                         break;
2072                 case OP_MOVE:
2073                 case OP_FMOVE:
2074                         /*
2075                          * Removes:
2076                          *
2077                          * OP_MOVE reg, reg 
2078                          */
2079                         if (ins->dreg == ins->sreg1) {
2080                                 MONO_DEL_INS (ins);
2081                                 continue;
2082                         }
2083                         /* 
2084                          * Removes:
2085                          *
2086                          * OP_MOVE sreg, dreg 
2087                          * OP_MOVE dreg, sreg
2088                          */
2089                         if (last_ins && last_ins->opcode == OP_MOVE &&
2090                                         ins->sreg1 == last_ins->dreg &&
2091                                         ins->dreg == last_ins->sreg1) {
2092                                 MONO_DEL_INS (ins);
2093                                 continue;
2094                         }
2095                         break;
2096                 }
2097         }
2098 }
2099
2100 #define NEW_INS(cfg,ins,dest,op) do {                                   \
2101                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
2102                 (dest)->opcode = (op);  \
2103                 MONO_INST_LIST_ADD_TAIL (&(dest)->node, &(ins)->node); \
2104         } while (0)
2105
2106 /*
2107  * mono_arch_lowering_pass:
2108  *
2109  *  Converts complex opcodes into simpler ones so that each IR instruction
2110  * corresponds to one machine instruction.
2111  */
2112 void
2113 mono_arch_lowering_pass (MonoCompile *cfg, MonoBasicBlock *bb)
2114 {
2115         MonoInst *ins, *n, *temp;
2116
2117         if (bb->max_vreg > cfg->rs->next_vreg)
2118                 cfg->rs->next_vreg = bb->max_vreg;
2119
2120         /*
2121          * FIXME: Need to add more instructions, but the current machine 
2122          * description can't model some parts of the composite instructions like
2123          * cdq.
2124          */
2125         MONO_INST_LIST_FOR_EACH_ENTRY_SAFE (ins, n, &bb->ins_list, node) {
2126                 switch (ins->opcode) {
2127                 case OP_DIV_IMM:
2128                 case OP_REM_IMM:
2129                 case OP_IDIV_IMM:
2130                 case OP_IREM_IMM:
2131                 case OP_IDIV_UN_IMM:
2132                 case OP_IREM_UN_IMM:
2133                         NEW_INS (cfg, ins, temp, OP_ICONST);
2134                         temp->inst_c0 = ins->inst_imm;
2135                         temp->dreg = mono_regstate_next_int (cfg->rs);
2136                         ins->opcode = mono_op_imm_to_op (ins->opcode);
2137                         ins->sreg2 = temp->dreg;
2138                         break;
2139                 case OP_COMPARE_IMM:
2140                 case OP_LCOMPARE_IMM:
2141                         if (!amd64_is_imm32 (ins->inst_imm)) {
2142                                 NEW_INS (cfg, ins, temp, OP_I8CONST);
2143                                 temp->inst_c0 = ins->inst_imm;
2144                                 temp->dreg = mono_regstate_next_int (cfg->rs);
2145                                 ins->opcode = OP_COMPARE;
2146                                 ins->sreg2 = temp->dreg;
2147                         }
2148                         break;
2149                 case OP_LOAD_MEMBASE:
2150                 case OP_LOADI8_MEMBASE:
2151                         if (!amd64_is_imm32 (ins->inst_offset)) {
2152                                 NEW_INS (cfg, ins, temp, OP_I8CONST);
2153                                 temp->inst_c0 = ins->inst_offset;
2154                                 temp->dreg = mono_regstate_next_int (cfg->rs);
2155                                 ins->opcode = OP_AMD64_LOADI8_MEMINDEX;
2156                                 ins->inst_indexreg = temp->dreg;
2157                         }
2158                         break;
2159                 case OP_STORE_MEMBASE_IMM:
2160                 case OP_STOREI8_MEMBASE_IMM:
2161                         if (!amd64_is_imm32 (ins->inst_imm)) {
2162                                 NEW_INS (cfg, ins, temp, OP_I8CONST);
2163                                 temp->inst_c0 = ins->inst_imm;
2164                                 temp->dreg = mono_regstate_next_int (cfg->rs);
2165                                 ins->opcode = OP_STOREI8_MEMBASE_REG;
2166                                 ins->sreg1 = temp->dreg;
2167                         }
2168                         break;
2169                 default:
2170                         break;
2171                 }
2172         }
2173
2174         bb->max_vreg = cfg->rs->next_vreg;
2175 }
2176
2177 static const int 
2178 branch_cc_table [] = {
2179         X86_CC_EQ, X86_CC_GE, X86_CC_GT, X86_CC_LE, X86_CC_LT,
2180         X86_CC_NE, X86_CC_GE, X86_CC_GT, X86_CC_LE, X86_CC_LT,
2181         X86_CC_O, X86_CC_NO, X86_CC_C, X86_CC_NC
2182 };
2183
2184 /* Maps CMP_... constants to X86_CC_... constants */
2185 static const int
2186 cc_table [] = {
2187         X86_CC_EQ, X86_CC_NE, X86_CC_LE, X86_CC_GE, X86_CC_LT, X86_CC_GT,
2188         X86_CC_LE, X86_CC_GE, X86_CC_LT, X86_CC_GT
2189 };
2190
2191 static const int
2192 cc_signed_table [] = {
2193         TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
2194         FALSE, FALSE, FALSE, FALSE
2195 };
2196
2197 /*#include "cprop.c"*/
2198
2199 static unsigned char*
2200 emit_float_to_int (MonoCompile *cfg, guchar *code, int dreg, int sreg, int size, gboolean is_signed)
2201 {
2202         if (use_sse2) {
2203                 amd64_sse_cvttsd2si_reg_reg (code, dreg, sreg);
2204         }
2205         else {
2206                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 16);
2207                 x86_fnstcw_membase(code, AMD64_RSP, 0);
2208                 amd64_mov_reg_membase (code, dreg, AMD64_RSP, 0, 2);
2209                 amd64_alu_reg_imm (code, X86_OR, dreg, 0xc00);
2210                 amd64_mov_membase_reg (code, AMD64_RSP, 2, dreg, 2);
2211                 amd64_fldcw_membase (code, AMD64_RSP, 2);
2212                 amd64_push_reg (code, AMD64_RAX); // SP = SP - 8
2213                 amd64_fist_pop_membase (code, AMD64_RSP, 0, size == 8);
2214                 amd64_pop_reg (code, dreg);
2215                 amd64_fldcw_membase (code, AMD64_RSP, 0);
2216                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 16);
2217         }
2218
2219         if (size == 1)
2220                 amd64_widen_reg (code, dreg, dreg, is_signed, FALSE);
2221         else if (size == 2)
2222                 amd64_widen_reg (code, dreg, dreg, is_signed, TRUE);
2223         return code;
2224 }
2225
2226 static unsigned char*
2227 mono_emit_stack_alloc (guchar *code, MonoInst* tree)
2228 {
2229         int sreg = tree->sreg1;
2230         int need_touch = FALSE;
2231
2232 #if defined(PLATFORM_WIN32) || defined(MONO_ARCH_SIGSEGV_ON_ALTSTACK)
2233         if (!tree->flags & MONO_INST_INIT)
2234                 need_touch = TRUE;
2235 #endif
2236
2237         if (need_touch) {
2238                 guint8* br[5];
2239
2240                 /*
2241                  * Under Windows:
2242                  * If requested stack size is larger than one page,
2243                  * perform stack-touch operation
2244                  */
2245                 /*
2246                  * Generate stack probe code.
2247                  * Under Windows, it is necessary to allocate one page at a time,
2248                  * "touching" stack after each successful sub-allocation. This is
2249                  * because of the way stack growth is implemented - there is a
2250                  * guard page before the lowest stack page that is currently commited.
2251                  * Stack normally grows sequentially so OS traps access to the
2252                  * guard page and commits more pages when needed.
2253                  */
2254                 amd64_test_reg_imm (code, sreg, ~0xFFF);
2255                 br[0] = code; x86_branch8 (code, X86_CC_Z, 0, FALSE);
2256
2257                 br[2] = code; /* loop */
2258                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 0x1000);
2259                 amd64_test_membase_reg (code, AMD64_RSP, 0, AMD64_RSP);
2260                 amd64_alu_reg_imm (code, X86_SUB, sreg, 0x1000);
2261                 amd64_alu_reg_imm (code, X86_CMP, sreg, 0x1000);
2262                 br[3] = code; x86_branch8 (code, X86_CC_AE, 0, FALSE);
2263                 amd64_patch (br[3], br[2]);
2264                 amd64_test_reg_reg (code, sreg, sreg);
2265                 br[4] = code; x86_branch8 (code, X86_CC_Z, 0, FALSE);
2266                 amd64_alu_reg_reg (code, X86_SUB, AMD64_RSP, sreg);
2267
2268                 br[1] = code; x86_jump8 (code, 0);
2269
2270                 amd64_patch (br[0], code);
2271                 amd64_alu_reg_reg (code, X86_SUB, AMD64_RSP, sreg);
2272                 amd64_patch (br[1], code);
2273                 amd64_patch (br[4], code);
2274         }
2275         else
2276                 amd64_alu_reg_reg (code, X86_SUB, AMD64_RSP, tree->sreg1);
2277
2278         if (tree->flags & MONO_INST_INIT) {
2279                 int offset = 0;
2280                 if (tree->dreg != AMD64_RAX && sreg != AMD64_RAX) {
2281                         amd64_push_reg (code, AMD64_RAX);
2282                         offset += 8;
2283                 }
2284                 if (tree->dreg != AMD64_RCX && sreg != AMD64_RCX) {
2285                         amd64_push_reg (code, AMD64_RCX);
2286                         offset += 8;
2287                 }
2288                 if (tree->dreg != AMD64_RDI && sreg != AMD64_RDI) {
2289                         amd64_push_reg (code, AMD64_RDI);
2290                         offset += 8;
2291                 }
2292                 
2293                 amd64_shift_reg_imm (code, X86_SHR, sreg, 3);
2294                 if (sreg != AMD64_RCX)
2295                         amd64_mov_reg_reg (code, AMD64_RCX, sreg, 8);
2296                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
2297                                 
2298                 amd64_lea_membase (code, AMD64_RDI, AMD64_RSP, offset);
2299                 amd64_cld (code);
2300                 amd64_prefix (code, X86_REP_PREFIX);
2301                 amd64_stosl (code);
2302                 
2303                 if (tree->dreg != AMD64_RDI && sreg != AMD64_RDI)
2304                         amd64_pop_reg (code, AMD64_RDI);
2305                 if (tree->dreg != AMD64_RCX && sreg != AMD64_RCX)
2306                         amd64_pop_reg (code, AMD64_RCX);
2307                 if (tree->dreg != AMD64_RAX && sreg != AMD64_RAX)
2308                         amd64_pop_reg (code, AMD64_RAX);
2309         }
2310         return code;
2311 }
2312
2313 static guint8*
2314 emit_move_return_value (MonoCompile *cfg, MonoInst *ins, guint8 *code)
2315 {
2316         CallInfo *cinfo;
2317         guint32 quad;
2318
2319         /* Move return value to the target register */
2320         /* FIXME: do this in the local reg allocator */
2321         switch (ins->opcode) {
2322         case OP_CALL:
2323         case OP_CALL_REG:
2324         case OP_CALL_MEMBASE:
2325         case OP_LCALL:
2326         case OP_LCALL_REG:
2327         case OP_LCALL_MEMBASE:
2328                 g_assert (ins->dreg == AMD64_RAX);
2329                 break;
2330         case OP_FCALL:
2331         case OP_FCALL_REG:
2332         case OP_FCALL_MEMBASE:
2333                 if (((MonoCallInst*)ins)->signature->ret->type == MONO_TYPE_R4) {
2334                         if (use_sse2)
2335                                 amd64_sse_cvtss2sd_reg_reg (code, ins->dreg, AMD64_XMM0);
2336                         else {
2337                                 /* FIXME: optimize this */
2338                                 amd64_movss_membase_reg (code, AMD64_RSP, -8, AMD64_XMM0);
2339                                 amd64_fld_membase (code, AMD64_RSP, -8, FALSE);
2340                         }
2341                 }
2342                 else {
2343                         if (use_sse2) {
2344                                 if (ins->dreg != AMD64_XMM0)
2345                                         amd64_sse_movsd_reg_reg (code, ins->dreg, AMD64_XMM0);
2346                         }
2347                         else {
2348                                 /* FIXME: optimize this */
2349                                 amd64_movsd_membase_reg (code, AMD64_RSP, -8, AMD64_XMM0);
2350                                 amd64_fld_membase (code, AMD64_RSP, -8, TRUE);
2351                         }
2352                 }
2353                 break;
2354         case OP_VCALL:
2355         case OP_VCALL_REG:
2356         case OP_VCALL_MEMBASE:
2357                 cinfo = get_call_info (cfg, cfg->mempool, ((MonoCallInst*)ins)->signature, FALSE);
2358                 if (cinfo->ret.storage == ArgValuetypeInReg) {
2359                         /* Pop the destination address from the stack */
2360                         amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
2361                         amd64_pop_reg (code, AMD64_RCX);
2362                         
2363                         for (quad = 0; quad < 2; quad ++) {
2364                                 switch (cinfo->ret.pair_storage [quad]) {
2365                                 case ArgInIReg:
2366                                         amd64_mov_membase_reg (code, AMD64_RCX, (quad * 8), cinfo->ret.pair_regs [quad], 8);
2367                                         break;
2368                                 case ArgInFloatSSEReg:
2369                                         amd64_movss_membase_reg (code, AMD64_RCX, (quad * 8), cinfo->ret.pair_regs [quad]);
2370                                         break;
2371                                 case ArgInDoubleSSEReg:
2372                                         amd64_movsd_membase_reg (code, AMD64_RCX, (quad * 8), cinfo->ret.pair_regs [quad]);
2373                                         break;
2374                                 case ArgNone:
2375                                         break;
2376                                 default:
2377                                         NOT_IMPLEMENTED;
2378                                 }
2379                         }
2380                 }
2381                 break;
2382         }
2383
2384         return code;
2385 }
2386
2387 /*
2388  * emit_tls_get:
2389  * @code: buffer to store code to
2390  * @dreg: hard register where to place the result
2391  * @tls_offset: offset info
2392  *
2393  * emit_tls_get emits in @code the native code that puts in the dreg register
2394  * the item in the thread local storage identified by tls_offset.
2395  *
2396  * Returns: a pointer to the end of the stored code
2397  */
2398 static guint8*
2399 emit_tls_get (guint8* code, int dreg, int tls_offset)
2400 {
2401         if (optimize_for_xen) {
2402                 x86_prefix (code, X86_FS_PREFIX);
2403                 amd64_mov_reg_mem (code, dreg, 0, 8);
2404                 amd64_mov_reg_membase (code, dreg, dreg, tls_offset, 8);
2405         } else {
2406                 x86_prefix (code, X86_FS_PREFIX);
2407                 amd64_mov_reg_mem (code, dreg, tls_offset, 8);
2408         }
2409         return code;
2410 }
2411
2412 /*
2413  * emit_load_volatile_arguments:
2414  *
2415  *  Load volatile arguments from the stack to the original input registers.
2416  * Required before a tail call.
2417  */
2418 static guint8*
2419 emit_load_volatile_arguments (MonoCompile *cfg, guint8 *code)
2420 {
2421         MonoMethod *method = cfg->method;
2422         MonoMethodSignature *sig;
2423         MonoInst *ins;
2424         CallInfo *cinfo;
2425         guint32 i, quad;
2426
2427         /* FIXME: Generate intermediate code instead */
2428
2429         sig = mono_method_signature (method);
2430
2431         cinfo = cfg->arch.cinfo;
2432         
2433         /* This is the opposite of the code in emit_prolog */
2434         if (sig->ret->type != MONO_TYPE_VOID) {
2435                 if (cfg->vret_addr && (cfg->vret_addr->opcode != OP_REGVAR))
2436                         amd64_mov_reg_membase (code, cinfo->ret.reg, cfg->vret_addr->inst_basereg, cfg->vret_addr->inst_offset, 8);
2437         }
2438
2439         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
2440                 ArgInfo *ainfo = cinfo->args + i;
2441                 MonoType *arg_type;
2442                 ins = cfg->args [i];
2443
2444                 if (sig->hasthis && (i == 0))
2445                         arg_type = &mono_defaults.object_class->byval_arg;
2446                 else
2447                         arg_type = sig->params [i - sig->hasthis];
2448
2449                 if (ins->opcode != OP_REGVAR) {
2450                         switch (ainfo->storage) {
2451                         case ArgInIReg: {
2452                                 guint32 size = 8;
2453
2454                                 /* FIXME: I1 etc */
2455                                 amd64_mov_reg_membase (code, ainfo->reg, ins->inst_basereg, ins->inst_offset, size);
2456                                 break;
2457                         }
2458                         case ArgInFloatSSEReg:
2459                                 amd64_movss_reg_membase (code, ainfo->reg, ins->inst_basereg, ins->inst_offset);
2460                                 break;
2461                         case ArgInDoubleSSEReg:
2462                                 amd64_movsd_reg_membase (code, ainfo->reg, ins->inst_basereg, ins->inst_offset);
2463                                 break;
2464                         case ArgValuetypeInReg:
2465                                 for (quad = 0; quad < 2; quad ++) {
2466                                         switch (ainfo->pair_storage [quad]) {
2467                                         case ArgInIReg:
2468                                                 amd64_mov_reg_membase (code, ainfo->pair_regs [quad], ins->inst_basereg, ins->inst_offset + (quad * sizeof (gpointer)), sizeof (gpointer));
2469                                                 break;
2470                                         case ArgInFloatSSEReg:
2471                                         case ArgInDoubleSSEReg:
2472                                                 g_assert_not_reached ();
2473                                                 break;
2474                                         case ArgNone:
2475                                                 break;
2476                                         default:
2477                                                 g_assert_not_reached ();
2478                                         }
2479                                 }
2480                                 break;
2481                         default:
2482                                 break;
2483                         }
2484                 }
2485                 else {
2486                         g_assert (ainfo->storage == ArgInIReg);
2487
2488                         amd64_mov_reg_reg (code, ainfo->reg, ins->dreg, 8);
2489                 }
2490         }
2491
2492         return code;
2493 }
2494
2495 #define REAL_PRINT_REG(text,reg) \
2496 mono_assert (reg >= 0); \
2497 amd64_push_reg (code, AMD64_RAX); \
2498 amd64_push_reg (code, AMD64_RDX); \
2499 amd64_push_reg (code, AMD64_RCX); \
2500 amd64_push_reg (code, reg); \
2501 amd64_push_imm (code, reg); \
2502 amd64_push_imm (code, text " %d %p\n"); \
2503 amd64_mov_reg_imm (code, AMD64_RAX, printf); \
2504 amd64_call_reg (code, AMD64_RAX); \
2505 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 3*4); \
2506 amd64_pop_reg (code, AMD64_RCX); \
2507 amd64_pop_reg (code, AMD64_RDX); \
2508 amd64_pop_reg (code, AMD64_RAX);
2509
2510 /* benchmark and set based on cpu */
2511 #define LOOP_ALIGNMENT 8
2512 #define bb_is_loop_start(bb) ((bb)->loop_body_start && (bb)->nesting)
2513
2514 void
2515 mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb)
2516 {
2517         MonoInst *ins;
2518         MonoCallInst *call;
2519         guint offset;
2520         guint8 *code = cfg->native_code + cfg->code_len;
2521         guint last_offset = 0;
2522         int max_len, cpos;
2523
2524         if (cfg->opt & MONO_OPT_LOOP) {
2525                 int pad, align = LOOP_ALIGNMENT;
2526                 /* set alignment depending on cpu */
2527                 if (bb_is_loop_start (bb) && (pad = (cfg->code_len & (align - 1)))) {
2528                         pad = align - pad;
2529                         /*g_print ("adding %d pad at %x to loop in %s\n", pad, cfg->code_len, cfg->method->name);*/
2530                         amd64_padding (code, pad);
2531                         cfg->code_len += pad;
2532                         bb->native_offset = cfg->code_len;
2533                 }
2534         }
2535
2536         if (cfg->verbose_level > 2)
2537                 g_print ("Basic block %d starting at offset 0x%x\n", bb->block_num, bb->native_offset);
2538
2539         cpos = bb->max_offset;
2540
2541         if (cfg->prof_options & MONO_PROFILE_COVERAGE) {
2542                 MonoProfileCoverageInfo *cov = cfg->coverage_info;
2543                 g_assert (!cfg->compile_aot);
2544                 cpos += 6;
2545
2546                 cov->data [bb->dfn].cil_code = bb->cil_code;
2547                 amd64_mov_reg_imm (code, AMD64_R11, (guint64)&cov->data [bb->dfn].count);
2548                 /* this is not thread save, but good enough */
2549                 amd64_inc_membase (code, AMD64_R11, 0);
2550         }
2551
2552         offset = code - cfg->native_code;
2553
2554         mono_debug_open_block (cfg, bb, offset);
2555
2556         MONO_BB_FOR_EACH_INS (bb, ins) {
2557                 offset = code - cfg->native_code;
2558
2559                 max_len = ((guint8 *)ins_get_spec (ins->opcode))[MONO_INST_LEN];
2560
2561                 if (G_UNLIKELY (offset > (cfg->code_size - max_len - 16))) {
2562                         cfg->code_size *= 2;
2563                         cfg->native_code = g_realloc (cfg->native_code, cfg->code_size);
2564                         code = cfg->native_code + offset;
2565                         mono_jit_stats.code_reallocs++;
2566                 }
2567
2568                 if (cfg->debug_info)
2569                         mono_debug_record_line_number (cfg, ins, offset);
2570
2571                 switch (ins->opcode) {
2572                 case OP_BIGMUL:
2573                         amd64_mul_reg (code, ins->sreg2, TRUE);
2574                         break;
2575                 case OP_BIGMUL_UN:
2576                         amd64_mul_reg (code, ins->sreg2, FALSE);
2577                         break;
2578                 case OP_X86_SETEQ_MEMBASE:
2579                         amd64_set_membase (code, X86_CC_EQ, ins->inst_basereg, ins->inst_offset, TRUE);
2580                         break;
2581                 case OP_STOREI1_MEMBASE_IMM:
2582                         amd64_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 1);
2583                         break;
2584                 case OP_STOREI2_MEMBASE_IMM:
2585                         amd64_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 2);
2586                         break;
2587                 case OP_STOREI4_MEMBASE_IMM:
2588                         amd64_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 4);
2589                         break;
2590                 case OP_STOREI1_MEMBASE_REG:
2591                         amd64_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 1);
2592                         break;
2593                 case OP_STOREI2_MEMBASE_REG:
2594                         amd64_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 2);
2595                         break;
2596                 case OP_STORE_MEMBASE_REG:
2597                 case OP_STOREI8_MEMBASE_REG:
2598                         amd64_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 8);
2599                         break;
2600                 case OP_STOREI4_MEMBASE_REG:
2601                         amd64_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 4);
2602                         break;
2603                 case OP_STORE_MEMBASE_IMM:
2604                 case OP_STOREI8_MEMBASE_IMM:
2605                         g_assert (amd64_is_imm32 (ins->inst_imm));
2606                         amd64_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 8);
2607                         break;
2608                 case OP_LOAD_MEM:
2609                 case OP_LOADI8_MEM:
2610                         // FIXME: Decompose this earlier
2611                         if (amd64_is_imm32 (ins->inst_imm))
2612                                 amd64_mov_reg_mem (code, ins->dreg, ins->inst_imm, sizeof (gpointer));
2613                         else {
2614                                 amd64_mov_reg_imm (code, ins->dreg, ins->inst_imm);
2615                                 amd64_mov_reg_membase (code, ins->dreg, ins->dreg, 0, 8);
2616                         }
2617                         break;
2618                 case OP_LOADI4_MEM:
2619                         amd64_mov_reg_imm (code, ins->dreg, ins->inst_imm);
2620                         amd64_movsxd_reg_membase (code, ins->dreg, ins->dreg, 0);
2621                         break;
2622                 case OP_LOADU4_MEM:
2623                         amd64_mov_reg_imm (code, ins->dreg, ins->inst_p0);
2624                         amd64_mov_reg_membase (code, ins->dreg, ins->dreg, 0, 4);
2625                         break;
2626                 case OP_LOADU1_MEM:
2627                         amd64_mov_reg_imm (code, ins->dreg, ins->inst_imm);
2628                         amd64_widen_membase (code, ins->dreg, ins->dreg, 0, FALSE, FALSE);
2629                         break;
2630                 case OP_LOADU2_MEM:
2631                         amd64_mov_reg_imm (code, ins->dreg, ins->inst_imm);
2632                         amd64_widen_membase (code, ins->dreg, ins->dreg, 0, FALSE, TRUE);
2633                         break;
2634                 case OP_LOAD_MEMBASE:
2635                 case OP_LOADI8_MEMBASE:
2636                         g_assert (amd64_is_imm32 (ins->inst_offset));
2637                         amd64_mov_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, sizeof (gpointer));
2638                         break;
2639                 case OP_LOADI4_MEMBASE:
2640                         amd64_movsxd_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset);
2641                         break;
2642                 case OP_LOADU4_MEMBASE:
2643                         amd64_mov_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, 4);
2644                         break;
2645                 case OP_LOADU1_MEMBASE:
2646                         amd64_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, FALSE, FALSE);
2647                         break;
2648                 case OP_LOADI1_MEMBASE:
2649                         amd64_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, TRUE, FALSE);
2650                         break;
2651                 case OP_LOADU2_MEMBASE:
2652                         amd64_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, FALSE, TRUE);
2653                         break;
2654                 case OP_LOADI2_MEMBASE:
2655                         amd64_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, TRUE, TRUE);
2656                         break;
2657                 case OP_AMD64_LOADI8_MEMINDEX:
2658                         amd64_mov_reg_memindex_size (code, ins->dreg, ins->inst_basereg, 0, ins->inst_indexreg, 0, 8);
2659                         break;
2660                 case OP_LCONV_TO_I1:
2661                 case OP_ICONV_TO_I1:
2662                 case OP_SEXT_I1:
2663                         amd64_widen_reg (code, ins->dreg, ins->sreg1, TRUE, FALSE);
2664                         break;
2665                 case OP_LCONV_TO_I2:
2666                 case OP_ICONV_TO_I2:
2667                 case OP_SEXT_I2:
2668                         amd64_widen_reg (code, ins->dreg, ins->sreg1, TRUE, TRUE);
2669                         break;
2670                 case OP_LCONV_TO_U1:
2671                 case OP_ICONV_TO_U1:
2672                         amd64_widen_reg (code, ins->dreg, ins->sreg1, FALSE, FALSE);
2673                         break;
2674                 case OP_LCONV_TO_U2:
2675                 case OP_ICONV_TO_U2:
2676                         amd64_widen_reg (code, ins->dreg, ins->sreg1, FALSE, TRUE);
2677                         break;
2678                 case OP_ZEXT_I4:
2679                         /* Clean out the upper word */
2680                         amd64_mov_reg_reg_size (code, ins->dreg, ins->sreg1, 4);
2681                         break;
2682                 case OP_SEXT_I4:
2683                         amd64_movsxd_reg_reg (code, ins->dreg, ins->sreg1);
2684                         break;
2685                 case OP_COMPARE:
2686                 case OP_LCOMPARE:
2687                         amd64_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2);
2688                         break;
2689                 case OP_COMPARE_IMM:
2690                 case OP_LCOMPARE_IMM:
2691                         g_assert (amd64_is_imm32 (ins->inst_imm));
2692                         amd64_alu_reg_imm (code, X86_CMP, ins->sreg1, ins->inst_imm);
2693                         break;
2694                 case OP_X86_COMPARE_REG_MEMBASE:
2695                         amd64_alu_reg_membase (code, X86_CMP, ins->sreg1, ins->sreg2, ins->inst_offset);
2696                         break;
2697                 case OP_X86_TEST_NULL:
2698                         amd64_test_reg_reg_size (code, ins->sreg1, ins->sreg1, 4);
2699                         break;
2700                 case OP_AMD64_TEST_NULL:
2701                         amd64_test_reg_reg (code, ins->sreg1, ins->sreg1);
2702                         break;
2703
2704                 case OP_X86_ADD_REG_MEMBASE:
2705                         amd64_alu_reg_membase_size (code, X86_ADD, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
2706                         break;
2707                 case OP_X86_SUB_REG_MEMBASE:
2708                         amd64_alu_reg_membase_size (code, X86_SUB, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
2709                         break;
2710                 case OP_X86_AND_REG_MEMBASE:
2711                         amd64_alu_reg_membase_size (code, X86_AND, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
2712                         break;
2713                 case OP_X86_OR_REG_MEMBASE:
2714                         amd64_alu_reg_membase_size (code, X86_OR, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
2715                         break;
2716                 case OP_X86_XOR_REG_MEMBASE:
2717                         amd64_alu_reg_membase_size (code, X86_XOR, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
2718                         break;
2719
2720                 case OP_X86_ADD_MEMBASE_IMM:
2721                         /* FIXME: Make a 64 version too */
2722                         amd64_alu_membase_imm_size (code, X86_ADD, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
2723                         break;
2724                 case OP_X86_SUB_MEMBASE_IMM:
2725                         g_assert (amd64_is_imm32 (ins->inst_imm));
2726                         amd64_alu_membase_imm_size (code, X86_SUB, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
2727                         break;
2728                 case OP_X86_AND_MEMBASE_IMM:
2729                         g_assert (amd64_is_imm32 (ins->inst_imm));
2730                         amd64_alu_membase_imm_size (code, X86_AND, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
2731                         break;
2732                 case OP_X86_OR_MEMBASE_IMM:
2733                         g_assert (amd64_is_imm32 (ins->inst_imm));
2734                         amd64_alu_membase_imm_size (code, X86_OR, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
2735                         break;
2736                 case OP_X86_XOR_MEMBASE_IMM:
2737                         g_assert (amd64_is_imm32 (ins->inst_imm));
2738                         amd64_alu_membase_imm_size (code, X86_XOR, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
2739                         break;
2740                 case OP_X86_ADD_MEMBASE_REG:
2741                         amd64_alu_membase_reg_size (code, X86_ADD, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
2742                         break;
2743                 case OP_X86_SUB_MEMBASE_REG:
2744                         amd64_alu_membase_reg_size (code, X86_SUB, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
2745                         break;
2746                 case OP_X86_AND_MEMBASE_REG:
2747                         amd64_alu_membase_reg_size (code, X86_AND, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
2748                         break;
2749                 case OP_X86_OR_MEMBASE_REG:
2750                         amd64_alu_membase_reg_size (code, X86_OR, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
2751                         break;
2752                 case OP_X86_XOR_MEMBASE_REG:
2753                         amd64_alu_membase_reg_size (code, X86_XOR, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
2754                         break;
2755                 case OP_X86_INC_MEMBASE:
2756                         amd64_inc_membase_size (code, ins->inst_basereg, ins->inst_offset, 4);
2757                         break;
2758                 case OP_X86_INC_REG:
2759                         amd64_inc_reg_size (code, ins->dreg, 4);
2760                         break;
2761                 case OP_X86_DEC_MEMBASE:
2762                         amd64_dec_membase_size (code, ins->inst_basereg, ins->inst_offset, 4);
2763                         break;
2764                 case OP_X86_DEC_REG:
2765                         amd64_dec_reg_size (code, ins->dreg, 4);
2766                         break;
2767                 case OP_X86_MUL_REG_MEMBASE:
2768                         amd64_imul_reg_membase_size (code, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
2769                         break;
2770                 case OP_AMD64_ICOMPARE_MEMBASE_REG:
2771                         amd64_alu_membase_reg_size (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
2772                         break;
2773                 case OP_AMD64_ICOMPARE_MEMBASE_IMM:
2774                         amd64_alu_membase_imm_size (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
2775                         break;
2776                 case OP_AMD64_COMPARE_MEMBASE_REG:
2777                         amd64_alu_membase_reg_size (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
2778                         break;
2779                 case OP_AMD64_COMPARE_MEMBASE_IMM:
2780                         g_assert (amd64_is_imm32 (ins->inst_imm));
2781                         amd64_alu_membase_imm_size (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
2782                         break;
2783                 case OP_X86_COMPARE_MEMBASE8_IMM:
2784                         amd64_alu_membase8_imm_size (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
2785                         break;
2786                 case OP_AMD64_ICOMPARE_REG_MEMBASE:
2787                         amd64_alu_reg_membase_size (code, X86_CMP, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
2788                         break;
2789                 case OP_AMD64_COMPARE_REG_MEMBASE:
2790                         amd64_alu_reg_membase_size (code, X86_CMP, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
2791                         break;
2792
2793                 case OP_AMD64_ADD_REG_MEMBASE:
2794                         amd64_alu_reg_membase_size (code, X86_ADD, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
2795                         break;
2796                 case OP_AMD64_SUB_REG_MEMBASE:
2797                         amd64_alu_reg_membase_size (code, X86_SUB, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
2798                         break;
2799                 case OP_AMD64_AND_REG_MEMBASE:
2800                         amd64_alu_reg_membase_size (code, X86_AND, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
2801                         break;
2802                 case OP_AMD64_OR_REG_MEMBASE:
2803                         amd64_alu_reg_membase_size (code, X86_OR, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
2804                         break;
2805                 case OP_AMD64_XOR_REG_MEMBASE:
2806                         amd64_alu_reg_membase_size (code, X86_XOR, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
2807                         break;
2808
2809                 case OP_AMD64_ADD_MEMBASE_REG:
2810                         amd64_alu_membase_reg_size (code, X86_ADD, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
2811                         break;
2812                 case OP_AMD64_SUB_MEMBASE_REG:
2813                         amd64_alu_membase_reg_size (code, X86_SUB, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
2814                         break;
2815                 case OP_AMD64_AND_MEMBASE_REG:
2816                         amd64_alu_membase_reg_size (code, X86_AND, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
2817                         break;
2818                 case OP_AMD64_OR_MEMBASE_REG:
2819                         amd64_alu_membase_reg_size (code, X86_OR, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
2820                         break;
2821                 case OP_AMD64_XOR_MEMBASE_REG:
2822                         amd64_alu_membase_reg_size (code, X86_XOR, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
2823                         break;
2824
2825                 case OP_AMD64_ADD_MEMBASE_IMM:
2826                         g_assert (amd64_is_imm32 (ins->inst_imm));
2827                         amd64_alu_membase_imm_size (code, X86_ADD, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
2828                         break;
2829                 case OP_AMD64_SUB_MEMBASE_IMM:
2830                         g_assert (amd64_is_imm32 (ins->inst_imm));
2831                         amd64_alu_membase_imm_size (code, X86_SUB, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
2832                         break;
2833                 case OP_AMD64_AND_MEMBASE_IMM:
2834                         g_assert (amd64_is_imm32 (ins->inst_imm));
2835                         amd64_alu_membase_imm_size (code, X86_AND, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
2836                         break;
2837                 case OP_AMD64_OR_MEMBASE_IMM:
2838                         g_assert (amd64_is_imm32 (ins->inst_imm));
2839                         amd64_alu_membase_imm_size (code, X86_OR, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
2840                         break;
2841                 case OP_AMD64_XOR_MEMBASE_IMM:
2842                         g_assert (amd64_is_imm32 (ins->inst_imm));
2843                         amd64_alu_membase_imm_size (code, X86_XOR, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
2844                         break;
2845
2846                 case OP_BREAK:
2847                         amd64_breakpoint (code);
2848                         break;
2849                 case OP_NOP:
2850                 case OP_DUMMY_USE:
2851                 case OP_DUMMY_STORE:
2852                 case OP_NOT_REACHED:
2853                 case OP_NOT_NULL:
2854                         break;
2855                 case OP_ADDCC:
2856                 case OP_LADD:
2857                         amd64_alu_reg_reg (code, X86_ADD, ins->sreg1, ins->sreg2);
2858                         break;
2859                 case OP_ADC:
2860                         amd64_alu_reg_reg (code, X86_ADC, ins->sreg1, ins->sreg2);
2861                         break;
2862                 case OP_ADD_IMM:
2863                 case OP_LADD_IMM:
2864                         g_assert (amd64_is_imm32 (ins->inst_imm));
2865                         amd64_alu_reg_imm (code, X86_ADD, ins->dreg, ins->inst_imm);
2866                         break;
2867                 case OP_ADC_IMM:
2868                         g_assert (amd64_is_imm32 (ins->inst_imm));
2869                         amd64_alu_reg_imm (code, X86_ADC, ins->dreg, ins->inst_imm);
2870                         break;
2871                 case OP_SUBCC:
2872                 case OP_LSUB:
2873                         amd64_alu_reg_reg (code, X86_SUB, ins->sreg1, ins->sreg2);
2874                         break;
2875                 case OP_SBB:
2876                         amd64_alu_reg_reg (code, X86_SBB, ins->sreg1, ins->sreg2);
2877                         break;
2878                 case OP_SUB_IMM:
2879                 case OP_LSUB_IMM:
2880                         g_assert (amd64_is_imm32 (ins->inst_imm));
2881                         amd64_alu_reg_imm (code, X86_SUB, ins->dreg, ins->inst_imm);
2882                         break;
2883                 case OP_SBB_IMM:
2884                         g_assert (amd64_is_imm32 (ins->inst_imm));
2885                         amd64_alu_reg_imm (code, X86_SBB, ins->dreg, ins->inst_imm);
2886                         break;
2887                 case OP_LAND:
2888                         amd64_alu_reg_reg (code, X86_AND, ins->sreg1, ins->sreg2);
2889                         break;
2890                 case OP_AND_IMM:
2891                 case OP_LAND_IMM:
2892                         g_assert (amd64_is_imm32 (ins->inst_imm));
2893                         amd64_alu_reg_imm (code, X86_AND, ins->sreg1, ins->inst_imm);
2894                         break;
2895                 case OP_LMUL:
2896                         amd64_imul_reg_reg (code, ins->sreg1, ins->sreg2);
2897                         break;
2898                 case OP_MUL_IMM:
2899                 case OP_LMUL_IMM:
2900                 case OP_IMUL_IMM: {
2901                         guint32 size = (ins->opcode == OP_IMUL_IMM) ? 4 : 8;
2902                         
2903                         switch (ins->inst_imm) {
2904                         case 2:
2905                                 /* MOV r1, r2 */
2906                                 /* ADD r1, r1 */
2907                                 if (ins->dreg != ins->sreg1)
2908                                         amd64_mov_reg_reg (code, ins->dreg, ins->sreg1, size);
2909                                 amd64_alu_reg_reg (code, X86_ADD, ins->dreg, ins->dreg);
2910                                 break;
2911                         case 3:
2912                                 /* LEA r1, [r2 + r2*2] */
2913                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 1);
2914                                 break;
2915                         case 5:
2916                                 /* LEA r1, [r2 + r2*4] */
2917                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 2);
2918                                 break;
2919                         case 6:
2920                                 /* LEA r1, [r2 + r2*2] */
2921                                 /* ADD r1, r1          */
2922                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 1);
2923                                 amd64_alu_reg_reg (code, X86_ADD, ins->dreg, ins->dreg);
2924                                 break;
2925                         case 9:
2926                                 /* LEA r1, [r2 + r2*8] */
2927                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 3);
2928                                 break;
2929                         case 10:
2930                                 /* LEA r1, [r2 + r2*4] */
2931                                 /* ADD r1, r1          */
2932                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 2);
2933                                 amd64_alu_reg_reg (code, X86_ADD, ins->dreg, ins->dreg);
2934                                 break;
2935                         case 12:
2936                                 /* LEA r1, [r2 + r2*2] */
2937                                 /* SHL r1, 2           */
2938                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 1);
2939                                 amd64_shift_reg_imm (code, X86_SHL, ins->dreg, 2);
2940                                 break;
2941                         case 25:
2942                                 /* LEA r1, [r2 + r2*4] */
2943                                 /* LEA r1, [r1 + r1*4] */
2944                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 2);
2945                                 amd64_lea_memindex (code, ins->dreg, ins->dreg, 0, ins->dreg, 2);
2946                                 break;
2947                         case 100:
2948                                 /* LEA r1, [r2 + r2*4] */
2949                                 /* SHL r1, 2           */
2950                                 /* LEA r1, [r1 + r1*4] */
2951                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 2);
2952                                 amd64_shift_reg_imm (code, X86_SHL, ins->dreg, 2);
2953                                 amd64_lea_memindex (code, ins->dreg, ins->dreg, 0, ins->dreg, 2);
2954                                 break;
2955                         default:
2956                                 amd64_imul_reg_reg_imm_size (code, ins->dreg, ins->sreg1, ins->inst_imm, size);
2957                                 break;
2958                         }
2959                         break;
2960                 }
2961                 case OP_LDIV:
2962                 case OP_LREM:
2963                         /* Regalloc magic makes the div/rem cases the same */
2964                         if (ins->sreg2 == AMD64_RDX) {
2965                                 amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RDX, 8);
2966                                 amd64_cdq (code);
2967                                 amd64_div_membase (code, AMD64_RSP, -8, TRUE);
2968                         } else {
2969                                 amd64_cdq (code);
2970                                 amd64_div_reg (code, ins->sreg2, TRUE);
2971                         }
2972                         break;
2973                 case OP_LDIV_UN:
2974                 case OP_LREM_UN:
2975                         if (ins->sreg2 == AMD64_RDX) {
2976                                 amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RDX, 8);
2977                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RDX, AMD64_RDX);
2978                                 amd64_div_membase (code, AMD64_RSP, -8, FALSE);
2979                         } else {
2980                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RDX, AMD64_RDX);
2981                                 amd64_div_reg (code, ins->sreg2, FALSE);
2982                         }
2983                         break;
2984                 case OP_IDIV:
2985                 case OP_IREM:
2986                         if (ins->sreg2 == AMD64_RDX) {
2987                                 amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RDX, 8);
2988                                 amd64_cdq_size (code, 4);
2989                                 amd64_div_membase_size (code, AMD64_RSP, -8, TRUE, 4);
2990                         } else {
2991                                 amd64_cdq_size (code, 4);
2992                                 amd64_div_reg_size (code, ins->sreg2, TRUE, 4);
2993                         }
2994                         break;
2995                 case OP_IDIV_UN:
2996                 case OP_IREM_UN:
2997                         if (ins->sreg2 == AMD64_RDX) {
2998                                 amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RDX, 8);
2999                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RDX, AMD64_RDX);
3000                                 amd64_div_membase_size (code, AMD64_RSP, -8, FALSE, 4);
3001                         } else {
3002                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RDX, AMD64_RDX);
3003                                 amd64_div_reg_size (code, ins->sreg2, FALSE, 4);
3004                         }
3005                         break;
3006                 case OP_LMUL_OVF:
3007                         amd64_imul_reg_reg (code, ins->sreg1, ins->sreg2);
3008                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_O, FALSE, "OverflowException");
3009                         break;
3010                 case OP_LOR:
3011                         amd64_alu_reg_reg (code, X86_OR, ins->sreg1, ins->sreg2);
3012                         break;
3013                 case OP_OR_IMM:
3014                 case OP_LOR_IMM:
3015                         g_assert (amd64_is_imm32 (ins->inst_imm));
3016                         amd64_alu_reg_imm (code, X86_OR, ins->sreg1, ins->inst_imm);
3017                         break;
3018                 case OP_LXOR:
3019                         amd64_alu_reg_reg (code, X86_XOR, ins->sreg1, ins->sreg2);
3020                         break;
3021                 case OP_XOR_IMM:
3022                 case OP_LXOR_IMM:
3023                         g_assert (amd64_is_imm32 (ins->inst_imm));
3024                         amd64_alu_reg_imm (code, X86_XOR, ins->sreg1, ins->inst_imm);
3025                         break;
3026                 case OP_LSHL:
3027                         g_assert (ins->sreg2 == AMD64_RCX);
3028                         amd64_shift_reg (code, X86_SHL, ins->dreg);
3029                         break;
3030                 case OP_LSHR:
3031                         g_assert (ins->sreg2 == AMD64_RCX);
3032                         amd64_shift_reg (code, X86_SAR, ins->dreg);
3033                         break;
3034                 case OP_SHR_IMM:
3035                         g_assert (amd64_is_imm32 (ins->inst_imm));
3036                         amd64_shift_reg_imm_size (code, X86_SAR, ins->dreg, ins->inst_imm, 4);
3037                         break;
3038                 case OP_LSHR_IMM:
3039                         g_assert (amd64_is_imm32 (ins->inst_imm));
3040                         amd64_shift_reg_imm (code, X86_SAR, ins->dreg, ins->inst_imm);
3041                         break;
3042                 case OP_SHR_UN_IMM:
3043                         g_assert (amd64_is_imm32 (ins->inst_imm));
3044                         amd64_shift_reg_imm_size (code, X86_SHR, ins->dreg, ins->inst_imm, 4);
3045                         break;
3046                 case OP_LSHR_UN_IMM:
3047                         g_assert (amd64_is_imm32 (ins->inst_imm));
3048                         amd64_shift_reg_imm (code, X86_SHR, ins->dreg, ins->inst_imm);
3049                         break;
3050                 case OP_LSHR_UN:
3051                         g_assert (ins->sreg2 == AMD64_RCX);
3052                         amd64_shift_reg (code, X86_SHR, ins->dreg);
3053                         break;
3054                 case OP_SHL_IMM:
3055                         g_assert (amd64_is_imm32 (ins->inst_imm));
3056                         amd64_shift_reg_imm_size (code, X86_SHL, ins->dreg, ins->inst_imm, 4);
3057                         break;
3058                 case OP_LSHL_IMM:
3059                         g_assert (amd64_is_imm32 (ins->inst_imm));
3060                         amd64_shift_reg_imm (code, X86_SHL, ins->dreg, ins->inst_imm);
3061                         break;
3062
3063                 case OP_IADDCC:
3064                 case OP_IADD:
3065                         amd64_alu_reg_reg_size (code, X86_ADD, ins->sreg1, ins->sreg2, 4);
3066                         break;
3067                 case OP_IADC:
3068                         amd64_alu_reg_reg_size (code, X86_ADC, ins->sreg1, ins->sreg2, 4);
3069                         break;
3070                 case OP_IADD_IMM:
3071                         amd64_alu_reg_imm_size (code, X86_ADD, ins->dreg, ins->inst_imm, 4);
3072                         break;
3073                 case OP_IADC_IMM:
3074                         amd64_alu_reg_imm_size (code, X86_ADC, ins->dreg, ins->inst_imm, 4);
3075                         break;
3076                 case OP_ISUBCC:
3077                 case OP_ISUB:
3078                         amd64_alu_reg_reg_size (code, X86_SUB, ins->sreg1, ins->sreg2, 4);
3079                         break;
3080                 case OP_ISBB:
3081                         amd64_alu_reg_reg_size (code, X86_SBB, ins->sreg1, ins->sreg2, 4);
3082                         break;
3083                 case OP_ISUB_IMM:
3084                         amd64_alu_reg_imm_size (code, X86_SUB, ins->dreg, ins->inst_imm, 4);
3085                         break;
3086                 case OP_ISBB_IMM:
3087                         amd64_alu_reg_imm_size (code, X86_SBB, ins->dreg, ins->inst_imm, 4);
3088                         break;
3089                 case OP_IAND:
3090                         amd64_alu_reg_reg_size (code, X86_AND, ins->sreg1, ins->sreg2, 4);
3091                         break;
3092                 case OP_IAND_IMM:
3093                         amd64_alu_reg_imm_size (code, X86_AND, ins->sreg1, ins->inst_imm, 4);
3094                         break;
3095                 case OP_IOR:
3096                         amd64_alu_reg_reg_size (code, X86_OR, ins->sreg1, ins->sreg2, 4);
3097                         break;
3098                 case OP_IOR_IMM:
3099                         amd64_alu_reg_imm_size (code, X86_OR, ins->sreg1, ins->inst_imm, 4);
3100                         break;
3101                 case OP_IXOR:
3102                         amd64_alu_reg_reg_size (code, X86_XOR, ins->sreg1, ins->sreg2, 4);
3103                         break;
3104                 case OP_IXOR_IMM:
3105                         amd64_alu_reg_imm_size (code, X86_XOR, ins->sreg1, ins->inst_imm, 4);
3106                         break;
3107                 case OP_INEG:
3108                         amd64_neg_reg_size (code, ins->sreg1, 4);
3109                         break;
3110                 case OP_INOT:
3111                         amd64_not_reg_size (code, ins->sreg1, 4);
3112                         break;
3113                 case OP_ISHL:
3114                         g_assert (ins->sreg2 == AMD64_RCX);
3115                         amd64_shift_reg_size (code, X86_SHL, ins->dreg, 4);
3116                         break;
3117                 case OP_ISHR:
3118                         g_assert (ins->sreg2 == AMD64_RCX);
3119                         amd64_shift_reg_size (code, X86_SAR, ins->dreg, 4);
3120                         break;
3121                 case OP_ISHR_IMM:
3122                         amd64_shift_reg_imm_size (code, X86_SAR, ins->dreg, ins->inst_imm, 4);
3123                         break;
3124                 case OP_ISHR_UN_IMM:
3125                         amd64_shift_reg_imm_size (code, X86_SHR, ins->dreg, ins->inst_imm, 4);
3126                         break;
3127                 case OP_ISHR_UN:
3128                         g_assert (ins->sreg2 == AMD64_RCX);
3129                         amd64_shift_reg_size (code, X86_SHR, ins->dreg, 4);
3130                         break;
3131                 case OP_ISHL_IMM:
3132                         amd64_shift_reg_imm_size (code, X86_SHL, ins->dreg, ins->inst_imm, 4);
3133                         break;
3134                 case OP_IMUL:
3135                         amd64_imul_reg_reg_size (code, ins->sreg1, ins->sreg2, 4);
3136                         break;
3137                 case OP_IMUL_OVF:
3138                         amd64_imul_reg_reg_size (code, ins->sreg1, ins->sreg2, 4);
3139                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_O, FALSE, "OverflowException");
3140                         break;
3141                 case OP_IMUL_OVF_UN:
3142                 case OP_LMUL_OVF_UN: {
3143                         /* the mul operation and the exception check should most likely be split */
3144                         int non_eax_reg, saved_eax = FALSE, saved_edx = FALSE;
3145                         int size = (ins->opcode == OP_IMUL_OVF_UN) ? 4 : 8;
3146                         /*g_assert (ins->sreg2 == X86_EAX);
3147                         g_assert (ins->dreg == X86_EAX);*/
3148                         if (ins->sreg2 == X86_EAX) {
3149                                 non_eax_reg = ins->sreg1;
3150                         } else if (ins->sreg1 == X86_EAX) {
3151                                 non_eax_reg = ins->sreg2;
3152                         } else {
3153                                 /* no need to save since we're going to store to it anyway */
3154                                 if (ins->dreg != X86_EAX) {
3155                                         saved_eax = TRUE;
3156                                         amd64_push_reg (code, X86_EAX);
3157                                 }
3158                                 amd64_mov_reg_reg (code, X86_EAX, ins->sreg1, size);
3159                                 non_eax_reg = ins->sreg2;
3160                         }
3161                         if (ins->dreg == X86_EDX) {
3162                                 if (!saved_eax) {
3163                                         saved_eax = TRUE;
3164                                         amd64_push_reg (code, X86_EAX);
3165                                 }
3166                         } else {
3167                                 saved_edx = TRUE;
3168                                 amd64_push_reg (code, X86_EDX);
3169                         }
3170                         amd64_mul_reg_size (code, non_eax_reg, FALSE, size);
3171                         /* save before the check since pop and mov don't change the flags */
3172                         if (ins->dreg != X86_EAX)
3173                                 amd64_mov_reg_reg (code, ins->dreg, X86_EAX, size);
3174                         if (saved_edx)
3175                                 amd64_pop_reg (code, X86_EDX);
3176                         if (saved_eax)
3177                                 amd64_pop_reg (code, X86_EAX);
3178                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_O, FALSE, "OverflowException");
3179                         break;
3180                 }
3181                 case OP_ICOMPARE:
3182                         amd64_alu_reg_reg_size (code, X86_CMP, ins->sreg1, ins->sreg2, 4);
3183                         break;
3184                 case OP_ICOMPARE_IMM:
3185                         amd64_alu_reg_imm_size (code, X86_CMP, ins->sreg1, ins->inst_imm, 4);
3186                         break;
3187                 case OP_IBEQ:
3188                 case OP_IBLT:
3189                 case OP_IBGT:
3190                 case OP_IBGE:
3191                 case OP_IBLE:
3192                 case OP_LBEQ:
3193                 case OP_LBLT:
3194                 case OP_LBGT:
3195                 case OP_LBGE:
3196                 case OP_LBLE:
3197                 case OP_IBNE_UN:
3198                 case OP_IBLT_UN:
3199                 case OP_IBGT_UN:
3200                 case OP_IBGE_UN:
3201                 case OP_IBLE_UN:
3202                 case OP_LBNE_UN:
3203                 case OP_LBLT_UN:
3204                 case OP_LBGT_UN:
3205                 case OP_LBGE_UN:
3206                 case OP_LBLE_UN:
3207                         EMIT_COND_BRANCH (ins, cc_table [mono_opcode_to_cond (ins->opcode)], cc_signed_table [mono_opcode_to_cond (ins->opcode)]);
3208                         break;
3209
3210                 case OP_LNOT:
3211                         amd64_not_reg (code, ins->sreg1);
3212                         break;
3213                 case OP_LNEG:
3214                         amd64_neg_reg (code, ins->sreg1);
3215                         break;
3216
3217                 case OP_ICONST:
3218                 case OP_I8CONST:
3219                         if ((((guint64)ins->inst_c0) >> 32) == 0)
3220                                 amd64_mov_reg_imm_size (code, ins->dreg, ins->inst_c0, 4);
3221                         else
3222                                 amd64_mov_reg_imm_size (code, ins->dreg, ins->inst_c0, 8);
3223                         break;
3224                 case OP_AOTCONST:
3225                         mono_add_patch_info (cfg, offset, (MonoJumpInfoType)ins->inst_i1, ins->inst_p0);
3226                         amd64_mov_reg_membase (code, ins->dreg, AMD64_RIP, 0, 8);
3227                         break;
3228                 case OP_MOVE:
3229                         amd64_mov_reg_reg (code, ins->dreg, ins->sreg1, sizeof (gpointer));
3230                         break;
3231                 case OP_AMD64_SET_XMMREG_R4: {
3232                         if (use_sse2) {
3233                                 amd64_sse_cvtsd2ss_reg_reg (code, ins->dreg, ins->sreg1);
3234                         }
3235                         else {
3236                                 amd64_fst_membase (code, AMD64_RSP, -8, FALSE, TRUE);
3237                                 /* ins->dreg is set to -1 by the reg allocator */
3238                                 amd64_movss_reg_membase (code, ins->backend.reg3, AMD64_RSP, -8);
3239                         }
3240                         break;
3241                 }
3242                 case OP_AMD64_SET_XMMREG_R8: {
3243                         if (use_sse2) {
3244                                 if (ins->dreg != ins->sreg1)
3245                                         amd64_sse_movsd_reg_reg (code, ins->dreg, ins->sreg1);
3246                         }
3247                         else {
3248                                 amd64_fst_membase (code, AMD64_RSP, -8, TRUE, TRUE);
3249                                 /* ins->dreg is set to -1 by the reg allocator */
3250                                 amd64_movsd_reg_membase (code, ins->backend.reg3, AMD64_RSP, -8);
3251                         }
3252                         break;
3253                 }
3254                 case OP_JMP: {
3255                         /*
3256                          * Note: this 'frame destruction' logic is useful for tail calls, too.
3257                          * Keep in sync with the code in emit_epilog.
3258                          */
3259                         int pos = 0, i;
3260
3261                         /* FIXME: no tracing support... */
3262                         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
3263                                 code = mono_arch_instrument_epilog (cfg, mono_profiler_method_leave, code, FALSE);
3264
3265                         g_assert (!cfg->method->save_lmf);
3266
3267                         code = emit_load_volatile_arguments (cfg, code);
3268
3269                         if (cfg->arch.omit_fp) {
3270                                 guint32 save_offset = 0;
3271                                 /* Pop callee-saved registers */
3272                                 for (i = 0; i < AMD64_NREG; ++i)
3273                                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
3274                                                 amd64_mov_reg_membase (code, i, AMD64_RSP, save_offset, 8);
3275                                                 save_offset += 8;
3276                                         }
3277                                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, cfg->arch.stack_alloc_size);
3278                         }
3279                         else {
3280                                 for (i = 0; i < AMD64_NREG; ++i)
3281                                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i)))
3282                                                 pos -= sizeof (gpointer);
3283                         
3284                                 if (pos)
3285                                         amd64_lea_membase (code, AMD64_RSP, AMD64_RBP, pos);
3286
3287                                 /* Pop registers in reverse order */
3288                                 for (i = AMD64_NREG - 1; i > 0; --i)
3289                                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
3290                                                 amd64_pop_reg (code, i);
3291                                         }
3292
3293                                 amd64_leave (code);
3294                         }
3295
3296                         offset = code - cfg->native_code;
3297                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_METHOD_JUMP, ins->inst_p0);
3298                         if (cfg->compile_aot)
3299                                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, 8);
3300                         else
3301                                 amd64_set_reg_template (code, AMD64_R11);
3302                         amd64_jump_reg (code, AMD64_R11);
3303                         break;
3304                 }
3305                 case OP_CHECK_THIS:
3306                         /* ensure ins->sreg1 is not NULL */
3307                         amd64_alu_membase_imm_size (code, X86_CMP, ins->sreg1, 0, 0, 4);
3308                         break;
3309                 case OP_ARGLIST: {
3310                         amd64_lea_membase (code, AMD64_R11, cfg->frame_reg, cfg->sig_cookie);
3311                         amd64_mov_membase_reg (code, ins->sreg1, 0, AMD64_R11, 8);
3312                         break;
3313                 }
3314                 case OP_FCALL:
3315                 case OP_LCALL:
3316                 case OP_VCALL:
3317                 case OP_VOIDCALL:
3318                 case OP_CALL:
3319                         call = (MonoCallInst*)ins;
3320                         /*
3321                          * The AMD64 ABI forces callers to know about varargs.
3322                          */
3323                         if ((call->signature->call_convention == MONO_CALL_VARARG) && (call->signature->pinvoke))
3324                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
3325                         else if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && (cfg->method->klass->image != mono_defaults.corlib)) {
3326                                 /* 
3327                                  * Since the unmanaged calling convention doesn't contain a 
3328                                  * 'vararg' entry, we have to treat every pinvoke call as a
3329                                  * potential vararg call.
3330                                  */
3331                                 guint32 nregs, i;
3332                                 nregs = 0;
3333                                 for (i = 0; i < AMD64_XMM_NREG; ++i)
3334                                         if (call->used_fregs & (1 << i))
3335                                                 nregs ++;
3336                                 if (!nregs)
3337                                         amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
3338                                 else
3339                                         amd64_mov_reg_imm (code, AMD64_RAX, nregs);
3340                         }
3341
3342                         if (ins->flags & MONO_INST_HAS_METHOD)
3343                                 code = emit_call (cfg, code, MONO_PATCH_INFO_METHOD, call->method);
3344                         else
3345                                 code = emit_call (cfg, code, MONO_PATCH_INFO_ABS, call->fptr);
3346                         if (call->stack_usage && !CALLCONV_IS_STDCALL (call->signature->call_convention))
3347                                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, call->stack_usage);
3348                         code = emit_move_return_value (cfg, ins, code);
3349                         break;
3350                 case OP_FCALL_REG:
3351                 case OP_LCALL_REG:
3352                 case OP_VCALL_REG:
3353                 case OP_VOIDCALL_REG:
3354                 case OP_CALL_REG:
3355                         call = (MonoCallInst*)ins;
3356
3357                         if (AMD64_IS_ARGUMENT_REG (ins->sreg1)) {
3358                                 amd64_mov_reg_reg (code, AMD64_R11, ins->sreg1, 8);
3359                                 ins->sreg1 = AMD64_R11;
3360                         }
3361
3362                         /*
3363                          * The AMD64 ABI forces callers to know about varargs.
3364                          */
3365                         if ((call->signature->call_convention == MONO_CALL_VARARG) && (call->signature->pinvoke)) {
3366                                 if (ins->sreg1 == AMD64_RAX) {
3367                                         amd64_mov_reg_reg (code, AMD64_R11, AMD64_RAX, 8);
3368                                         ins->sreg1 = AMD64_R11;
3369                                 }
3370                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
3371                         }
3372                         amd64_call_reg (code, ins->sreg1);
3373                         if (call->stack_usage && !CALLCONV_IS_STDCALL (call->signature->call_convention))
3374                                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, call->stack_usage);
3375                         code = emit_move_return_value (cfg, ins, code);
3376                         break;
3377                 case OP_FCALL_MEMBASE:
3378                 case OP_LCALL_MEMBASE:
3379                 case OP_VCALL_MEMBASE:
3380                 case OP_VOIDCALL_MEMBASE:
3381                 case OP_CALL_MEMBASE:
3382                         call = (MonoCallInst*)ins;
3383
3384                         if (AMD64_IS_ARGUMENT_REG (ins->sreg1)) {
3385                                 /* 
3386                                  * Can't use R11 because it is clobbered by the trampoline 
3387                                  * code, and the reg value is needed by get_vcall_slot_addr.
3388                                  */
3389                                 amd64_mov_reg_reg (code, AMD64_RAX, ins->sreg1, 8);
3390                                 ins->sreg1 = AMD64_RAX;
3391                         }
3392
3393                         amd64_call_membase (code, ins->sreg1, ins->inst_offset);
3394                         if (call->stack_usage && !CALLCONV_IS_STDCALL (call->signature->call_convention))
3395                                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, call->stack_usage);
3396                         code = emit_move_return_value (cfg, ins, code);
3397                         break;
3398                 case OP_AMD64_SAVE_SP_TO_LMF:
3399                         amd64_mov_membase_reg (code, cfg->frame_reg, cfg->arch.lmf_offset + G_STRUCT_OFFSET (MonoLMF, rsp), AMD64_RSP, 8);
3400                         break;
3401                 case OP_OUTARG:
3402                 case OP_X86_PUSH:
3403                         amd64_push_reg (code, ins->sreg1);
3404                         break;
3405                 case OP_X86_PUSH_IMM:
3406                         g_assert (amd64_is_imm32 (ins->inst_imm));
3407                         amd64_push_imm (code, ins->inst_imm);
3408                         break;
3409                 case OP_X86_PUSH_MEMBASE:
3410                         amd64_push_membase (code, ins->inst_basereg, ins->inst_offset);
3411                         break;
3412                 case OP_X86_PUSH_OBJ: 
3413                         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, ins->inst_imm);
3414                         amd64_push_reg (code, AMD64_RDI);
3415                         amd64_push_reg (code, AMD64_RSI);
3416                         amd64_push_reg (code, AMD64_RCX);
3417                         if (ins->inst_offset)
3418                                 amd64_lea_membase (code, AMD64_RSI, ins->inst_basereg, ins->inst_offset);
3419                         else
3420                                 amd64_mov_reg_reg (code, AMD64_RSI, ins->inst_basereg, 8);
3421                         amd64_lea_membase (code, AMD64_RDI, AMD64_RSP, 3 * 8);
3422                         amd64_mov_reg_imm (code, AMD64_RCX, (ins->inst_imm >> 3));
3423                         amd64_cld (code);
3424                         amd64_prefix (code, X86_REP_PREFIX);
3425                         amd64_movsd (code);
3426                         amd64_pop_reg (code, AMD64_RCX);
3427                         amd64_pop_reg (code, AMD64_RSI);
3428                         amd64_pop_reg (code, AMD64_RDI);
3429                         break;
3430                 case OP_X86_LEA:
3431                         amd64_lea_memindex (code, ins->dreg, ins->sreg1, ins->inst_imm, ins->sreg2, ins->backend.shift_amount);
3432                         break;
3433                 case OP_X86_LEA_MEMBASE:
3434                         amd64_lea_membase (code, ins->dreg, ins->sreg1, ins->inst_imm);
3435                         break;
3436                 case OP_X86_XCHG:
3437                         amd64_xchg_reg_reg (code, ins->sreg1, ins->sreg2, 4);
3438                         break;
3439                 case OP_LOCALLOC:
3440                         /* keep alignment */
3441                         amd64_alu_reg_imm (code, X86_ADD, ins->sreg1, MONO_ARCH_FRAME_ALIGNMENT - 1);
3442                         amd64_alu_reg_imm (code, X86_AND, ins->sreg1, ~(MONO_ARCH_FRAME_ALIGNMENT - 1));
3443                         code = mono_emit_stack_alloc (code, ins);
3444                         amd64_mov_reg_reg (code, ins->dreg, AMD64_RSP, 8);
3445                         break;
3446                 case OP_LOCALLOC_IMM: {
3447                         guint32 size = ins->inst_imm;
3448                         size = (size + (MONO_ARCH_FRAME_ALIGNMENT - 1)) & ~ (MONO_ARCH_FRAME_ALIGNMENT - 1);
3449
3450                         if (ins->flags & MONO_INST_INIT) {
3451                                 /* FIXME: Optimize this */
3452                                 amd64_mov_reg_imm (code, ins->dreg, size);
3453                                 ins->sreg1 = ins->dreg;
3454
3455                                 code = mono_emit_stack_alloc (code, ins);
3456                                 amd64_mov_reg_reg (code, ins->dreg, AMD64_RSP, 8);
3457                         } else {
3458                                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, size);
3459                                 amd64_mov_reg_reg (code, ins->dreg, AMD64_RSP, 8);
3460                         }
3461                         break;
3462                 }
3463                 case OP_THROW: {
3464                         amd64_mov_reg_reg (code, AMD64_ARG_REG1, ins->sreg1, 8);
3465                         code = emit_call (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD, 
3466                                              (gpointer)"mono_arch_throw_exception");
3467                         break;
3468                 }
3469                 case OP_RETHROW: {
3470                         amd64_mov_reg_reg (code, AMD64_ARG_REG1, ins->sreg1, 8);
3471                         code = emit_call (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD, 
3472                                              (gpointer)"mono_arch_rethrow_exception");
3473                         break;
3474                 }
3475                 case OP_CALL_HANDLER: 
3476                         /* Align stack */
3477                         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
3478                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_BB, ins->inst_target_bb);
3479                         amd64_call_imm (code, 0);
3480                         /* Restore stack alignment */
3481                         amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
3482                         break;
3483                 case OP_START_HANDLER: {
3484                         MonoInst *spvar = mono_find_spvar_for_region (cfg, bb->region);
3485                         amd64_mov_membase_reg (code, spvar->inst_basereg, spvar->inst_offset, AMD64_RSP, 8);
3486                         break;
3487                 }
3488                 case OP_ENDFINALLY: {
3489                         MonoInst *spvar = mono_find_spvar_for_region (cfg, bb->region);
3490                         amd64_mov_reg_membase (code, AMD64_RSP, spvar->inst_basereg, spvar->inst_offset, 8);
3491                         amd64_ret (code);
3492                         break;
3493                 }
3494                 case OP_ENDFILTER: {
3495                         MonoInst *spvar = mono_find_spvar_for_region (cfg, bb->region);
3496                         amd64_mov_reg_membase (code, AMD64_RSP, spvar->inst_basereg, spvar->inst_offset, 8);
3497                         /* The local allocator will put the result into RAX */
3498                         amd64_ret (code);
3499                         break;
3500                 }
3501
3502                 case OP_LABEL:
3503                         ins->inst_c0 = code - cfg->native_code;
3504                         break;
3505                 case OP_BR:
3506                         if (ins->flags & MONO_INST_BRLABEL) {
3507                                 if (ins->inst_i0->inst_c0) {
3508                                         amd64_jump_code (code, cfg->native_code + ins->inst_i0->inst_c0);
3509                                 } else {
3510                                         mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_LABEL, ins->inst_i0);
3511                                         if ((cfg->opt & MONO_OPT_BRANCH) &&
3512                                             x86_is_imm8 (ins->inst_i0->inst_c1 - cpos))
3513                                                 x86_jump8 (code, 0);
3514                                         else 
3515                                                 x86_jump32 (code, 0);
3516                                 }
3517                         } else {
3518                                 if (ins->inst_target_bb->native_offset) {
3519                                         amd64_jump_code (code, cfg->native_code + ins->inst_target_bb->native_offset); 
3520                                 } else {
3521                                         mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_BB, ins->inst_target_bb);
3522                                         if ((cfg->opt & MONO_OPT_BRANCH) &&
3523                                             x86_is_imm8 (ins->inst_target_bb->max_offset - cpos))
3524                                                 x86_jump8 (code, 0);
3525                                         else 
3526                                                 x86_jump32 (code, 0);
3527                                 } 
3528                         }
3529                         break;
3530                 case OP_BR_REG:
3531                         amd64_jump_reg (code, ins->sreg1);
3532                         break;
3533                 case OP_CEQ:
3534                 case OP_LCEQ:
3535                 case OP_ICEQ:
3536                 case OP_CLT:
3537                 case OP_LCLT:
3538                 case OP_ICLT:
3539                 case OP_CGT:
3540                 case OP_ICGT:
3541                 case OP_LCGT:
3542                 case OP_CLT_UN:
3543                 case OP_LCLT_UN:
3544                 case OP_ICLT_UN:
3545                 case OP_CGT_UN:
3546                 case OP_LCGT_UN:
3547                 case OP_ICGT_UN:
3548                         amd64_set_reg (code, cc_table [mono_opcode_to_cond (ins->opcode)], ins->dreg, cc_signed_table [mono_opcode_to_cond (ins->opcode)]);
3549                         amd64_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
3550                         break;
3551                 case OP_COND_EXC_EQ:
3552                 case OP_COND_EXC_NE_UN:
3553                 case OP_COND_EXC_LT:
3554                 case OP_COND_EXC_LT_UN:
3555                 case OP_COND_EXC_GT:
3556                 case OP_COND_EXC_GT_UN:
3557                 case OP_COND_EXC_GE:
3558                 case OP_COND_EXC_GE_UN:
3559                 case OP_COND_EXC_LE:
3560                 case OP_COND_EXC_LE_UN:
3561                 case OP_COND_EXC_IEQ:
3562                 case OP_COND_EXC_INE_UN:
3563                 case OP_COND_EXC_ILT:
3564                 case OP_COND_EXC_ILT_UN:
3565                 case OP_COND_EXC_IGT:
3566                 case OP_COND_EXC_IGT_UN:
3567                 case OP_COND_EXC_IGE:
3568                 case OP_COND_EXC_IGE_UN:
3569                 case OP_COND_EXC_ILE:
3570                 case OP_COND_EXC_ILE_UN:
3571                         EMIT_COND_SYSTEM_EXCEPTION (cc_table [mono_opcode_to_cond (ins->opcode)], cc_signed_table [mono_opcode_to_cond (ins->opcode)], ins->inst_p1);
3572                         break;
3573                 case OP_COND_EXC_OV:
3574                 case OP_COND_EXC_NO:
3575                 case OP_COND_EXC_C:
3576                 case OP_COND_EXC_NC:
3577                         EMIT_COND_SYSTEM_EXCEPTION (branch_cc_table [ins->opcode - OP_COND_EXC_EQ], 
3578                                                     (ins->opcode < OP_COND_EXC_NE_UN), ins->inst_p1);
3579                         break;
3580                 case OP_COND_EXC_IOV:
3581                 case OP_COND_EXC_INO:
3582                 case OP_COND_EXC_IC:
3583                 case OP_COND_EXC_INC:
3584                         EMIT_COND_SYSTEM_EXCEPTION (branch_cc_table [ins->opcode - OP_COND_EXC_IEQ], 
3585                                                     (ins->opcode < OP_COND_EXC_INE_UN), ins->inst_p1);
3586                         break;
3587
3588                 /* floating point opcodes */
3589                 case OP_R8CONST: {
3590                         double d = *(double *)ins->inst_p0;
3591
3592                         if (use_sse2) {
3593                                 if ((d == 0.0) && (mono_signbit (d) == 0)) {
3594                                         amd64_sse_xorpd_reg_reg (code, ins->dreg, ins->dreg);
3595                                 }
3596                                 else {
3597                                         mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_R8, ins->inst_p0);
3598                                         amd64_sse_movsd_reg_membase (code, ins->dreg, AMD64_RIP, 0);
3599                                 }
3600                         }
3601                         else if ((d == 0.0) && (mono_signbit (d) == 0)) {
3602                                 amd64_fldz (code);
3603                         } else if (d == 1.0) {
3604                                 x86_fld1 (code);
3605                         } else {
3606                                 mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_R8, ins->inst_p0);
3607                                 amd64_fld_membase (code, AMD64_RIP, 0, TRUE);
3608                         }
3609                         break;
3610                 }
3611                 case OP_R4CONST: {
3612                         float f = *(float *)ins->inst_p0;
3613
3614                         if (use_sse2) {
3615                                 if ((f == 0.0) && (mono_signbit (f) == 0)) {
3616                                         amd64_sse_xorpd_reg_reg (code, ins->dreg, ins->dreg);
3617                                 }
3618                                 else {
3619                                         mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_R4, ins->inst_p0);
3620                                         amd64_sse_movss_reg_membase (code, ins->dreg, AMD64_RIP, 0);
3621                                         amd64_sse_cvtss2sd_reg_reg (code, ins->dreg, ins->dreg);
3622                                 }
3623                         }
3624                         else if ((f == 0.0) && (mono_signbit (f) == 0)) {
3625                                 amd64_fldz (code);
3626                         } else if (f == 1.0) {
3627                                 x86_fld1 (code);
3628                         } else {
3629                                 mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_R4, ins->inst_p0);
3630                                 amd64_fld_membase (code, AMD64_RIP, 0, FALSE);
3631                         }
3632                         break;
3633                 }
3634                 case OP_STORER8_MEMBASE_REG:
3635                         if (use_sse2)
3636                                 amd64_sse_movsd_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1);
3637                         else
3638                                 amd64_fst_membase (code, ins->inst_destbasereg, ins->inst_offset, TRUE, TRUE);
3639                         break;
3640                 case OP_LOADR8_SPILL_MEMBASE:
3641                         if (use_sse2)
3642                                 g_assert_not_reached ();
3643                         amd64_fld_membase (code, ins->inst_basereg, ins->inst_offset, TRUE);
3644                         amd64_fxch (code, 1);
3645                         break;
3646                 case OP_LOADR8_MEMBASE:
3647                         if (use_sse2)
3648                                 amd64_sse_movsd_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset);
3649                         else
3650                                 amd64_fld_membase (code, ins->inst_basereg, ins->inst_offset, TRUE);
3651                         break;
3652                 case OP_STORER4_MEMBASE_REG:
3653                         if (use_sse2) {
3654                                 /* This requires a double->single conversion */
3655                                 amd64_sse_cvtsd2ss_reg_reg (code, AMD64_XMM15, ins->sreg1);
3656                                 amd64_sse_movss_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, AMD64_XMM15);
3657                         }
3658                         else
3659                                 amd64_fst_membase (code, ins->inst_destbasereg, ins->inst_offset, FALSE, TRUE);
3660                         break;
3661                 case OP_LOADR4_MEMBASE:
3662                         if (use_sse2) {
3663                                 amd64_sse_movss_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset);
3664                                 amd64_sse_cvtss2sd_reg_reg (code, ins->dreg, ins->dreg);
3665                         }
3666                         else
3667                                 amd64_fld_membase (code, ins->inst_basereg, ins->inst_offset, FALSE);
3668                         break;
3669                 case OP_ICONV_TO_R4: /* FIXME: change precision */
3670                 case OP_ICONV_TO_R8:
3671                         if (use_sse2)
3672                                 amd64_sse_cvtsi2sd_reg_reg_size (code, ins->dreg, ins->sreg1, 4);
3673                         else {
3674                                 amd64_push_reg (code, ins->sreg1);
3675                                 amd64_fild_membase (code, AMD64_RSP, 0, FALSE);
3676                                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
3677                         }
3678                         break;
3679                 case OP_LCONV_TO_R4: /* FIXME: change precision */
3680                 case OP_LCONV_TO_R8:
3681                         if (use_sse2)
3682                                 amd64_sse_cvtsi2sd_reg_reg (code, ins->dreg, ins->sreg1);
3683                         else {
3684                                 amd64_push_reg (code, ins->sreg1);
3685                                 amd64_fild_membase (code, AMD64_RSP, 0, TRUE);
3686                                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
3687                         }
3688                         break;
3689                 case OP_X86_FP_LOAD_I8:
3690                         if (use_sse2)
3691                                 g_assert_not_reached ();
3692                         amd64_fild_membase (code, ins->inst_basereg, ins->inst_offset, TRUE);
3693                         break;
3694                 case OP_X86_FP_LOAD_I4:
3695                         if (use_sse2)
3696                                 g_assert_not_reached ();
3697                         amd64_fild_membase (code, ins->inst_basereg, ins->inst_offset, FALSE);
3698                         break;
3699                 case OP_FCONV_TO_R4:
3700                         /* FIXME: nothing to do ?? */
3701                         break;
3702                 case OP_FCONV_TO_I1:
3703                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 1, TRUE);
3704                         break;
3705                 case OP_FCONV_TO_U1:
3706                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 1, FALSE);
3707                         break;
3708                 case OP_FCONV_TO_I2:
3709                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 2, TRUE);
3710                         break;
3711                 case OP_FCONV_TO_U2:
3712                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 2, FALSE);
3713                         break;
3714                 case OP_FCONV_TO_U4:
3715                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 4, FALSE);                  
3716                         break;
3717                 case OP_FCONV_TO_I4:
3718                 case OP_FCONV_TO_I:
3719                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 4, TRUE);
3720                         break;
3721                 case OP_FCONV_TO_I8:
3722                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 8, TRUE);
3723                         break;
3724                 case OP_LCONV_TO_R_UN: { 
3725                         static guint8 mn[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f, 0x40 };
3726                         guint8 *br [2];
3727
3728                         if (use_sse2) {
3729                                 /* Based on gcc code */
3730                                 amd64_test_reg_reg (code, ins->sreg1, ins->sreg1);
3731                                 br [0] = code; x86_branch8 (code, X86_CC_S, 0, TRUE);
3732
3733                                 /* Positive case */
3734                                 amd64_sse_cvtsi2sd_reg_reg (code, ins->dreg, ins->sreg1);
3735                                 br [1] = code; x86_jump8 (code, 0);
3736                                 amd64_patch (br [0], code);
3737
3738                                 /* Negative case */
3739                                 /* Save to the red zone */
3740                                 amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RAX, 8);
3741                                 amd64_mov_membase_reg (code, AMD64_RSP, -16, AMD64_RCX, 8);
3742                                 amd64_mov_reg_reg (code, AMD64_RCX, ins->sreg1, 8);
3743                                 amd64_mov_reg_reg (code, AMD64_RAX, ins->sreg1, 8);
3744                                 amd64_alu_reg_imm (code, X86_AND, AMD64_RCX, 1);
3745                                 amd64_shift_reg_imm (code, X86_SHR, AMD64_RAX, 1);
3746                                 amd64_alu_reg_imm (code, X86_OR, AMD64_RAX, AMD64_RCX);
3747                                 amd64_sse_cvtsi2sd_reg_reg (code, ins->dreg, AMD64_RAX);
3748                                 amd64_sse_addsd_reg_reg (code, ins->dreg, ins->dreg);
3749                                 /* Restore */
3750                                 amd64_mov_reg_membase (code, AMD64_RCX, AMD64_RSP, -16, 8);
3751                                 amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RSP, -8, 8);
3752                                 amd64_patch (br [1], code);
3753
3754                                 break;
3755                         }
3756
3757                         /* load 64bit integer to FP stack */
3758                         amd64_push_imm (code, 0);
3759                         amd64_push_reg (code, ins->sreg2);
3760                         amd64_push_reg (code, ins->sreg1);
3761                         amd64_fild_membase (code, AMD64_RSP, 0, TRUE);
3762                         /* store as 80bit FP value */
3763                         x86_fst80_membase (code, AMD64_RSP, 0);
3764                         
3765                         /* test if lreg is negative */
3766                         amd64_test_reg_reg (code, ins->sreg2, ins->sreg2);
3767                         br [0] = code; x86_branch8 (code, X86_CC_GEZ, 0, TRUE);
3768         
3769                         /* add correction constant mn */
3770                         x86_fld80_mem (code, (gssize)mn);
3771                         x86_fld80_membase (code, AMD64_RSP, 0);
3772                         amd64_fp_op_reg (code, X86_FADD, 1, TRUE);
3773                         x86_fst80_membase (code, AMD64_RSP, 0);
3774
3775                         amd64_patch (br [0], code);
3776
3777                         x86_fld80_membase (code, AMD64_RSP, 0);
3778                         amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 12);
3779
3780                         break;
3781                 }
3782                 case OP_LCONV_TO_OVF_U4:
3783                         amd64_alu_reg_imm (code, X86_CMP, ins->sreg1, 0);
3784                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_LT, TRUE, "OverflowException");
3785                         amd64_mov_reg_reg (code, ins->dreg, ins->sreg1, 8);
3786                         break;
3787                 case OP_LCONV_TO_OVF_I4_UN:
3788                         amd64_alu_reg_imm (code, X86_CMP, ins->sreg1, 0x7fffffff);
3789                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_GT, FALSE, "OverflowException");
3790                         amd64_mov_reg_reg (code, ins->dreg, ins->sreg1, 8);
3791                         break;
3792                 case OP_FMOVE:
3793                         if (use_sse2 && (ins->dreg != ins->sreg1))
3794                                 amd64_sse_movsd_reg_reg (code, ins->dreg, ins->sreg1);
3795                         break;
3796                 case OP_FADD:
3797                         if (use_sse2)
3798                                 amd64_sse_addsd_reg_reg (code, ins->dreg, ins->sreg2);
3799                         else
3800                                 amd64_fp_op_reg (code, X86_FADD, 1, TRUE);
3801                         break;
3802                 case OP_FSUB:
3803                         if (use_sse2)
3804                                 amd64_sse_subsd_reg_reg (code, ins->dreg, ins->sreg2);
3805                         else
3806                                 amd64_fp_op_reg (code, X86_FSUB, 1, TRUE);
3807                         break;          
3808                 case OP_FMUL:
3809                         if (use_sse2)
3810                                 amd64_sse_mulsd_reg_reg (code, ins->dreg, ins->sreg2);
3811                         else
3812                                 amd64_fp_op_reg (code, X86_FMUL, 1, TRUE);
3813                         break;          
3814                 case OP_FDIV:
3815                         if (use_sse2)
3816                                 amd64_sse_divsd_reg_reg (code, ins->dreg, ins->sreg2);
3817                         else
3818                                 amd64_fp_op_reg (code, X86_FDIV, 1, TRUE);
3819                         break;          
3820                 case OP_FNEG:
3821                         if (use_sse2) {
3822                                 static double r8_0 = -0.0;
3823
3824                                 g_assert (ins->sreg1 == ins->dreg);
3825                                         
3826                                 mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_R8, &r8_0);
3827                                 amd64_sse_xorpd_reg_membase (code, ins->dreg, AMD64_RIP, 0);
3828                         }
3829                         else
3830                                 amd64_fchs (code);
3831                         break;          
3832                 case OP_SIN:
3833                         if (use_sse2) {
3834                                 EMIT_SSE2_FPFUNC (code, fsin, ins->dreg, ins->sreg1);
3835                         }
3836                         else {
3837                                 amd64_fsin (code);
3838                                 amd64_fldz (code);
3839                                 amd64_fp_op_reg (code, X86_FADD, 1, TRUE);
3840                         }
3841                         break;          
3842                 case OP_COS:
3843                         if (use_sse2) {
3844                                 EMIT_SSE2_FPFUNC (code, fcos, ins->dreg, ins->sreg1);
3845                         }
3846                         else {
3847                                 amd64_fcos (code);
3848                                 amd64_fldz (code);
3849                                 amd64_fp_op_reg (code, X86_FADD, 1, TRUE);
3850                         }
3851                         break;          
3852                 case OP_ABS:
3853                         if (use_sse2) {
3854                                 EMIT_SSE2_FPFUNC (code, fabs, ins->dreg, ins->sreg1);
3855                         }
3856                         else
3857                                 amd64_fabs (code);
3858                         break;          
3859                 case OP_TAN: {
3860                         /* 
3861                          * it really doesn't make sense to inline all this code,
3862                          * it's here just to show that things may not be as simple 
3863                          * as they appear.
3864                          */
3865                         guchar *check_pos, *end_tan, *pop_jump;
3866                         if (use_sse2)
3867                                 g_assert_not_reached ();
3868                         amd64_push_reg (code, AMD64_RAX);
3869                         amd64_fptan (code);
3870                         amd64_fnstsw (code);
3871                         amd64_test_reg_imm (code, AMD64_RAX, X86_FP_C2);
3872                         check_pos = code;
3873                         x86_branch8 (code, X86_CC_NE, 0, FALSE);
3874                         amd64_fstp (code, 0); /* pop the 1.0 */
3875                         end_tan = code;
3876                         x86_jump8 (code, 0);
3877                         amd64_fldpi (code);
3878                         amd64_fp_op (code, X86_FADD, 0);
3879                         amd64_fxch (code, 1);
3880                         x86_fprem1 (code);
3881                         amd64_fstsw (code);
3882                         amd64_test_reg_imm (code, AMD64_RAX, X86_FP_C2);
3883                         pop_jump = code;
3884                         x86_branch8 (code, X86_CC_NE, 0, FALSE);
3885                         amd64_fstp (code, 1);
3886                         amd64_fptan (code);
3887                         amd64_patch (pop_jump, code);
3888                         amd64_fstp (code, 0); /* pop the 1.0 */
3889                         amd64_patch (check_pos, code);
3890                         amd64_patch (end_tan, code);
3891                         amd64_fldz (code);
3892                         amd64_fp_op_reg (code, X86_FADD, 1, TRUE);
3893                         amd64_pop_reg (code, AMD64_RAX);
3894                         break;
3895                 }
3896                 case OP_ATAN:
3897                         if (use_sse2)
3898                                 g_assert_not_reached ();
3899                         x86_fld1 (code);
3900                         amd64_fpatan (code);
3901                         amd64_fldz (code);
3902                         amd64_fp_op_reg (code, X86_FADD, 1, TRUE);
3903                         break;          
3904                 case OP_SQRT:
3905                         if (use_sse2) {
3906                                 EMIT_SSE2_FPFUNC (code, fsqrt, ins->dreg, ins->sreg1);
3907                         }
3908                         else
3909                                 amd64_fsqrt (code);
3910                         break;
3911                 case OP_IMIN:
3912                         g_assert (cfg->opt & MONO_OPT_CMOV);
3913                         g_assert (ins->dreg == ins->sreg1);
3914                         amd64_alu_reg_reg_size (code, X86_CMP, ins->sreg1, ins->sreg2, 4);
3915                         amd64_cmov_reg_size (code, X86_CC_GT, TRUE, ins->dreg, ins->sreg2, 4);
3916                         break;
3917                 case OP_IMAX:
3918                         g_assert (cfg->opt & MONO_OPT_CMOV);
3919                         g_assert (ins->dreg == ins->sreg1);
3920                         amd64_alu_reg_reg_size (code, X86_CMP, ins->sreg1, ins->sreg2, 4);
3921                         amd64_cmov_reg_size (code, X86_CC_LT, TRUE, ins->dreg, ins->sreg2, 4);
3922                         break;
3923                 case OP_LMIN:
3924                         g_assert (cfg->opt & MONO_OPT_CMOV);
3925                         g_assert (ins->dreg == ins->sreg1);
3926                         amd64_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2);
3927                         amd64_cmov_reg (code, X86_CC_GT, TRUE, ins->dreg, ins->sreg2);
3928                         break;
3929                 case OP_LMAX:
3930                         g_assert (cfg->opt & MONO_OPT_CMOV);
3931                         g_assert (ins->dreg == ins->sreg1);
3932                         amd64_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2);
3933                         amd64_cmov_reg (code, X86_CC_LT, TRUE, ins->dreg, ins->sreg2);
3934                         break;  
3935                 case OP_X86_FPOP:
3936                         if (!use_sse2)
3937                                 amd64_fstp (code, 0);
3938                         break;          
3939                 case OP_FREM: {
3940                         guint8 *l1, *l2;
3941
3942                         if (use_sse2)
3943                                 g_assert_not_reached ();
3944                         amd64_push_reg (code, AMD64_RAX);
3945                         /* we need to exchange ST(0) with ST(1) */
3946                         amd64_fxch (code, 1);
3947
3948                         /* this requires a loop, because fprem somtimes 
3949                          * returns a partial remainder */
3950                         l1 = code;
3951                         /* looks like MS is using fprem instead of the IEEE compatible fprem1 */
3952                         /* x86_fprem1 (code); */
3953                         amd64_fprem (code);
3954                         amd64_fnstsw (code);
3955                         amd64_alu_reg_imm (code, X86_AND, AMD64_RAX, X86_FP_C2);
3956                         l2 = code + 2;
3957                         x86_branch8 (code, X86_CC_NE, l1 - l2, FALSE);
3958
3959                         /* pop result */
3960                         amd64_fstp (code, 1);
3961
3962                         amd64_pop_reg (code, AMD64_RAX);
3963                         break;
3964                 }
3965                 case OP_FCOMPARE:
3966                         if (use_sse2) {
3967                                 /* 
3968                                  * The two arguments are swapped because the fbranch instructions
3969                                  * depend on this for the non-sse case to work.
3970                                  */
3971                                 amd64_sse_comisd_reg_reg (code, ins->sreg2, ins->sreg1);
3972                                 break;
3973                         }
3974                         if (cfg->opt & MONO_OPT_FCMOV) {
3975                                 amd64_fcomip (code, 1);
3976                                 amd64_fstp (code, 0);
3977                                 break;
3978                         }
3979                         /* this overwrites EAX */
3980                         EMIT_FPCOMPARE(code);
3981                         amd64_alu_reg_imm (code, X86_AND, AMD64_RAX, X86_FP_CC_MASK);
3982                         break;
3983                 case OP_FCEQ:
3984                         if (use_sse2 || (cfg->opt & MONO_OPT_FCMOV)) {
3985                                 /* zeroing the register at the start results in 
3986                                  * shorter and faster code (we can also remove the widening op)
3987                                  */
3988                                 guchar *unordered_check;
3989                                 amd64_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
3990                                 
3991                                 if (use_sse2)
3992                                         amd64_sse_comisd_reg_reg (code, ins->sreg1, ins->sreg2);
3993                                 else {
3994                                         amd64_fcomip (code, 1);
3995                                         amd64_fstp (code, 0);
3996                                 }
3997                                 unordered_check = code;
3998                                 x86_branch8 (code, X86_CC_P, 0, FALSE);
3999                                 amd64_set_reg (code, X86_CC_EQ, ins->dreg, FALSE);
4000                                 amd64_patch (unordered_check, code);
4001                                 break;
4002                         }
4003                         if (ins->dreg != AMD64_RAX) 
4004                                 amd64_push_reg (code, AMD64_RAX);
4005
4006                         EMIT_FPCOMPARE(code);
4007                         amd64_alu_reg_imm (code, X86_AND, AMD64_RAX, X86_FP_CC_MASK);
4008                         amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, 0x4000);
4009                         amd64_set_reg (code, X86_CC_EQ, ins->dreg, TRUE);
4010                         amd64_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
4011
4012                         if (ins->dreg != AMD64_RAX) 
4013                                 amd64_pop_reg (code, AMD64_RAX);
4014                         break;
4015                 case OP_FCLT:
4016                 case OP_FCLT_UN:
4017                         if (use_sse2 || (cfg->opt & MONO_OPT_FCMOV)) {
4018                                 /* zeroing the register at the start results in 
4019                                  * shorter and faster code (we can also remove the widening op)
4020                                  */
4021                                 amd64_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
4022                                 if (use_sse2)
4023                                         amd64_sse_comisd_reg_reg (code, ins->sreg2, ins->sreg1);
4024                                 else {
4025                                         amd64_fcomip (code, 1);
4026                                         amd64_fstp (code, 0);
4027                                 }
4028                                 if (ins->opcode == OP_FCLT_UN) {
4029                                         guchar *unordered_check = code;
4030                                         guchar *jump_to_end;
4031                                         x86_branch8 (code, X86_CC_P, 0, FALSE);
4032                                         amd64_set_reg (code, X86_CC_GT, ins->dreg, FALSE);
4033                                         jump_to_end = code;
4034                                         x86_jump8 (code, 0);
4035                                         amd64_patch (unordered_check, code);
4036                                         amd64_inc_reg (code, ins->dreg);
4037                                         amd64_patch (jump_to_end, code);
4038                                 } else {
4039                                         amd64_set_reg (code, X86_CC_GT, ins->dreg, FALSE);
4040                                 }
4041                                 break;
4042                         }
4043                         if (ins->dreg != AMD64_RAX) 
4044                                 amd64_push_reg (code, AMD64_RAX);
4045
4046                         EMIT_FPCOMPARE(code);
4047                         amd64_alu_reg_imm (code, X86_AND, AMD64_RAX, X86_FP_CC_MASK);
4048                         if (ins->opcode == OP_FCLT_UN) {
4049                                 guchar *is_not_zero_check, *end_jump;
4050                                 is_not_zero_check = code;
4051                                 x86_branch8 (code, X86_CC_NZ, 0, TRUE);
4052                                 end_jump = code;
4053                                 x86_jump8 (code, 0);
4054                                 amd64_patch (is_not_zero_check, code);
4055                                 amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, X86_FP_CC_MASK);
4056
4057                                 amd64_patch (end_jump, code);
4058                         }
4059                         amd64_set_reg (code, X86_CC_EQ, ins->dreg, TRUE);
4060                         amd64_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
4061
4062                         if (ins->dreg != AMD64_RAX) 
4063                                 amd64_pop_reg (code, AMD64_RAX);
4064                         break;
4065                 case OP_FCGT:
4066                 case OP_FCGT_UN:
4067                         if (use_sse2 || (cfg->opt & MONO_OPT_FCMOV)) {
4068                                 /* zeroing the register at the start results in 
4069                                  * shorter and faster code (we can also remove the widening op)
4070                                  */
4071                                 guchar *unordered_check;
4072                                 amd64_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
4073                                 if (use_sse2)
4074                                         amd64_sse_comisd_reg_reg (code, ins->sreg2, ins->sreg1);
4075                                 else {
4076                                         amd64_fcomip (code, 1);
4077                                         amd64_fstp (code, 0);
4078                                 }
4079                                 if (ins->opcode == OP_FCGT) {
4080                                         unordered_check = code;
4081                                         x86_branch8 (code, X86_CC_P, 0, FALSE);
4082                                         amd64_set_reg (code, X86_CC_LT, ins->dreg, FALSE);
4083                                         amd64_patch (unordered_check, code);
4084                                 } else {
4085                                         amd64_set_reg (code, X86_CC_LT, ins->dreg, FALSE);
4086                                 }
4087                                 break;
4088                         }
4089                         if (ins->dreg != AMD64_RAX) 
4090                                 amd64_push_reg (code, AMD64_RAX);
4091
4092                         EMIT_FPCOMPARE(code);
4093                         amd64_alu_reg_imm (code, X86_AND, AMD64_RAX, X86_FP_CC_MASK);
4094                         amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, X86_FP_C0);
4095                         if (ins->opcode == OP_FCGT_UN) {
4096                                 guchar *is_not_zero_check, *end_jump;
4097                                 is_not_zero_check = code;
4098                                 x86_branch8 (code, X86_CC_NZ, 0, TRUE);
4099                                 end_jump = code;
4100                                 x86_jump8 (code, 0);
4101                                 amd64_patch (is_not_zero_check, code);
4102                                 amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, X86_FP_CC_MASK);
4103
4104                                 amd64_patch (end_jump, code);
4105                         }
4106                         amd64_set_reg (code, X86_CC_EQ, ins->dreg, TRUE);
4107                         amd64_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
4108
4109                         if (ins->dreg != AMD64_RAX) 
4110                                 amd64_pop_reg (code, AMD64_RAX);
4111                         break;
4112                 case OP_FCLT_MEMBASE:
4113                 case OP_FCGT_MEMBASE:
4114                 case OP_FCLT_UN_MEMBASE:
4115                 case OP_FCGT_UN_MEMBASE:
4116                 case OP_FCEQ_MEMBASE: {
4117                         guchar *unordered_check, *jump_to_end;
4118                         int x86_cond;
4119                         g_assert (use_sse2);
4120
4121                         amd64_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
4122                         amd64_sse_comisd_reg_membase (code, ins->sreg1, ins->sreg2, ins->inst_offset);
4123
4124                         switch (ins->opcode) {
4125                         case OP_FCEQ_MEMBASE:
4126                                 x86_cond = X86_CC_EQ;
4127                                 break;
4128                         case OP_FCLT_MEMBASE:
4129                         case OP_FCLT_UN_MEMBASE:
4130                                 x86_cond = X86_CC_LT;
4131                                 break;
4132                         case OP_FCGT_MEMBASE:
4133                         case OP_FCGT_UN_MEMBASE:
4134                                 x86_cond = X86_CC_GT;
4135                                 break;
4136                         default:
4137                                 g_assert_not_reached ();
4138                         }
4139
4140                         unordered_check = code;
4141                         x86_branch8 (code, X86_CC_P, 0, FALSE);
4142                         amd64_set_reg (code, x86_cond, ins->dreg, FALSE);
4143
4144                         switch (ins->opcode) {
4145                         case OP_FCEQ_MEMBASE:
4146                         case OP_FCLT_MEMBASE:
4147                         case OP_FCGT_MEMBASE:
4148                                 amd64_patch (unordered_check, code);
4149                                 break;
4150                         case OP_FCLT_UN_MEMBASE:
4151                         case OP_FCGT_UN_MEMBASE:
4152                                 jump_to_end = code;
4153                                 x86_jump8 (code, 0);
4154                                 amd64_patch (unordered_check, code);
4155                                 amd64_inc_reg (code, ins->dreg);
4156                                 amd64_patch (jump_to_end, code);
4157                                 break;
4158                         default:
4159                                 break;
4160                         }
4161                         break;
4162                 }
4163                 case OP_FBEQ:
4164                         if (use_sse2 || (cfg->opt & MONO_OPT_FCMOV)) {
4165                                 guchar *jump = code;
4166                                 x86_branch8 (code, X86_CC_P, 0, TRUE);
4167                                 EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
4168                                 amd64_patch (jump, code);
4169                                 break;
4170                         }
4171                         amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, 0x4000);
4172                         EMIT_COND_BRANCH (ins, X86_CC_EQ, TRUE);
4173                         break;
4174                 case OP_FBNE_UN:
4175                         /* Branch if C013 != 100 */
4176                         if (use_sse2 || (cfg->opt & MONO_OPT_FCMOV)) {
4177                                 /* branch if !ZF or (PF|CF) */
4178                                 EMIT_COND_BRANCH (ins, X86_CC_NE, FALSE);
4179                                 EMIT_COND_BRANCH (ins, X86_CC_P, FALSE);
4180                                 EMIT_COND_BRANCH (ins, X86_CC_B, FALSE);
4181                                 break;
4182                         }
4183                         amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, X86_FP_C3);
4184                         EMIT_COND_BRANCH (ins, X86_CC_NE, FALSE);
4185                         break;
4186                 case OP_FBLT:
4187                         if (use_sse2 || (cfg->opt & MONO_OPT_FCMOV)) {
4188                                 EMIT_COND_BRANCH (ins, X86_CC_GT, FALSE);
4189                                 break;
4190                         }
4191                         EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
4192                         break;
4193                 case OP_FBLT_UN:
4194                         if (use_sse2 || (cfg->opt & MONO_OPT_FCMOV)) {
4195                                 EMIT_COND_BRANCH (ins, X86_CC_P, FALSE);
4196                                 EMIT_COND_BRANCH (ins, X86_CC_GT, FALSE);
4197                                 break;
4198                         }
4199                         if (ins->opcode == OP_FBLT_UN) {
4200                                 guchar *is_not_zero_check, *end_jump;
4201                                 is_not_zero_check = code;
4202                                 x86_branch8 (code, X86_CC_NZ, 0, TRUE);
4203                                 end_jump = code;
4204                                 x86_jump8 (code, 0);
4205                                 amd64_patch (is_not_zero_check, code);
4206                                 amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, X86_FP_CC_MASK);
4207
4208                                 amd64_patch (end_jump, code);
4209                         }
4210                         EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
4211                         break;
4212                 case OP_FBGT:
4213                 case OP_FBGT_UN:
4214                         if (use_sse2 || (cfg->opt & MONO_OPT_FCMOV)) {
4215                                 if (ins->opcode == OP_FBGT) {
4216                                         guchar *br1;
4217
4218                                         /* skip branch if C1=1 */
4219                                         br1 = code;
4220                                         x86_branch8 (code, X86_CC_P, 0, FALSE);
4221                                         /* branch if (C0 | C3) = 1 */
4222                                         EMIT_COND_BRANCH (ins, X86_CC_LT, FALSE);
4223                                         amd64_patch (br1, code);
4224                                         break;
4225                                 } else {
4226                                         EMIT_COND_BRANCH (ins, X86_CC_LT, FALSE);
4227                                 }
4228                                 break;
4229                         }
4230                         amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, X86_FP_C0);
4231                         if (ins->opcode == OP_FBGT_UN) {
4232                                 guchar *is_not_zero_check, *end_jump;
4233                                 is_not_zero_check = code;
4234                                 x86_branch8 (code, X86_CC_NZ, 0, TRUE);
4235                                 end_jump = code;
4236                                 x86_jump8 (code, 0);
4237                                 amd64_patch (is_not_zero_check, code);
4238                                 amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, X86_FP_CC_MASK);
4239
4240                                 amd64_patch (end_jump, code);
4241                         }
4242                         EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
4243                         break;
4244                 case OP_FBGE:
4245                         /* Branch if C013 == 100 or 001 */
4246                         if (use_sse2 || (cfg->opt & MONO_OPT_FCMOV)) {
4247                                 guchar *br1;
4248
4249                                 /* skip branch if C1=1 */
4250                                 br1 = code;
4251                                 x86_branch8 (code, X86_CC_P, 0, FALSE);
4252                                 /* branch if (C0 | C3) = 1 */
4253                                 EMIT_COND_BRANCH (ins, X86_CC_BE, FALSE);
4254                                 amd64_patch (br1, code);
4255                                 break;
4256                         }
4257                         amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, X86_FP_C0);
4258                         EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
4259                         amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, X86_FP_C3);
4260                         EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
4261                         break;
4262                 case OP_FBGE_UN:
4263                         /* Branch if C013 == 000 */
4264                         if (use_sse2 || (cfg->opt & MONO_OPT_FCMOV)) {
4265                                 EMIT_COND_BRANCH (ins, X86_CC_LE, FALSE);
4266                                 break;
4267                         }
4268                         EMIT_COND_BRANCH (ins, X86_CC_NE, FALSE);
4269                         break;
4270                 case OP_FBLE:
4271                         /* Branch if C013=000 or 100 */
4272                         if (use_sse2 || (cfg->opt & MONO_OPT_FCMOV)) {
4273                                 guchar *br1;
4274
4275                                 /* skip branch if C1=1 */
4276                                 br1 = code;
4277                                 x86_branch8 (code, X86_CC_P, 0, FALSE);
4278                                 /* branch if C0=0 */
4279                                 EMIT_COND_BRANCH (ins, X86_CC_NB, FALSE);
4280                                 amd64_patch (br1, code);
4281                                 break;
4282                         }
4283                         amd64_alu_reg_imm (code, X86_AND, AMD64_RAX, (X86_FP_C0|X86_FP_C1));
4284                         amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, 0);
4285                         EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
4286                         break;
4287                 case OP_FBLE_UN:
4288                         /* Branch if C013 != 001 */
4289                         if (use_sse2 || (cfg->opt & MONO_OPT_FCMOV)) {
4290                                 EMIT_COND_BRANCH (ins, X86_CC_P, FALSE);
4291                                 EMIT_COND_BRANCH (ins, X86_CC_GE, FALSE);
4292                                 break;
4293                         }
4294                         amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, X86_FP_C0);
4295                         EMIT_COND_BRANCH (ins, X86_CC_NE, FALSE);
4296                         break;
4297                 case OP_CKFINITE:
4298                         if (use_sse2) {
4299                                 /* Transfer value to the fp stack */
4300                                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 16);
4301                                 amd64_movsd_membase_reg (code, AMD64_RSP, 0, ins->sreg1);
4302                                 amd64_fld_membase (code, AMD64_RSP, 0, TRUE);
4303                         }
4304                         amd64_push_reg (code, AMD64_RAX);
4305                         amd64_fxam (code);
4306                         amd64_fnstsw (code);
4307                         amd64_alu_reg_imm (code, X86_AND, AMD64_RAX, 0x4100);
4308                         amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, X86_FP_C0);
4309                         amd64_pop_reg (code, AMD64_RAX);
4310                         if (use_sse2) {
4311                                 amd64_fstp (code, 0);
4312                         }                               
4313                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_EQ, FALSE, "ArithmeticException");
4314                         if (use_sse2)
4315                                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 16);
4316                         break;
4317                 case OP_TLS_GET: {
4318                         code = emit_tls_get (code, ins->dreg, ins->inst_offset);
4319                         break;
4320                 }
4321                 case OP_MEMORY_BARRIER: {
4322                         /* Not needed on amd64 */
4323                         break;
4324                 }
4325                 case OP_ATOMIC_ADD_I4:
4326                 case OP_ATOMIC_ADD_I8: {
4327                         int dreg = ins->dreg;
4328                         guint32 size = (ins->opcode == OP_ATOMIC_ADD_I4) ? 4 : 8;
4329
4330                         if (dreg == ins->inst_basereg)
4331                                 dreg = AMD64_R11;
4332                         
4333                         if (dreg != ins->sreg2)
4334                                 amd64_mov_reg_reg (code, ins->dreg, ins->sreg2, size);
4335
4336                         x86_prefix (code, X86_LOCK_PREFIX);
4337                         amd64_xadd_membase_reg (code, ins->inst_basereg, ins->inst_offset, dreg, size);
4338
4339                         if (dreg != ins->dreg)
4340                                 amd64_mov_reg_reg (code, ins->dreg, dreg, size);
4341
4342                         break;
4343                 }
4344                 case OP_ATOMIC_ADD_NEW_I4:
4345                 case OP_ATOMIC_ADD_NEW_I8: {
4346                         int dreg = ins->dreg;
4347                         guint32 size = (ins->opcode == OP_ATOMIC_ADD_NEW_I4) ? 4 : 8;
4348
4349                         if ((dreg == ins->sreg2) || (dreg == ins->inst_basereg))
4350                                 dreg = AMD64_R11;
4351
4352                         amd64_mov_reg_reg (code, dreg, ins->sreg2, size);
4353                         amd64_prefix (code, X86_LOCK_PREFIX);
4354                         amd64_xadd_membase_reg (code, ins->inst_basereg, ins->inst_offset, dreg, size);
4355                         /* dreg contains the old value, add with sreg2 value */
4356                         amd64_alu_reg_reg_size (code, X86_ADD, dreg, ins->sreg2, size);
4357                         
4358                         if (ins->dreg != dreg)
4359                                 amd64_mov_reg_reg (code, ins->dreg, dreg, size);
4360
4361                         break;
4362                 }
4363                 case OP_ATOMIC_EXCHANGE_I4:
4364                 case OP_ATOMIC_EXCHANGE_I8: {
4365                         guchar *br[2];
4366                         int sreg2 = ins->sreg2;
4367                         int breg = ins->inst_basereg;
4368                         guint32 size = (ins->opcode == OP_ATOMIC_EXCHANGE_I4) ? 4 : 8;
4369
4370                         /* 
4371                          * See http://msdn.microsoft.com/msdnmag/issues/0700/Win32/ for
4372                          * an explanation of how this works.
4373                          */
4374
4375                         /* cmpxchg uses eax as comperand, need to make sure we can use it
4376                          * hack to overcome limits in x86 reg allocator 
4377                          * (req: dreg == eax and sreg2 != eax and breg != eax) 
4378                          */
4379                         /* The pushes invalidate rsp */
4380                         if ((breg == AMD64_RAX) || (breg == AMD64_RSP)) {
4381                                 amd64_mov_reg_reg (code, AMD64_R11, breg, 8);
4382                                 breg = AMD64_R11;
4383                         }
4384
4385                         if (ins->dreg != AMD64_RAX)
4386                                 amd64_push_reg (code, AMD64_RAX);
4387                         
4388                         /* We need the EAX reg for the cmpxchg */
4389                         if (ins->sreg2 == AMD64_RAX) {
4390                                 amd64_push_reg (code, AMD64_RDX);
4391                                 amd64_mov_reg_reg (code, AMD64_RDX, AMD64_RAX, size);
4392                                 sreg2 = AMD64_RDX;
4393                         }
4394
4395                         amd64_mov_reg_membase (code, AMD64_RAX, breg, ins->inst_offset, size);
4396
4397                         br [0] = code; amd64_prefix (code, X86_LOCK_PREFIX);
4398                         amd64_cmpxchg_membase_reg_size (code, breg, ins->inst_offset, sreg2, size);
4399                         br [1] = code; amd64_branch8 (code, X86_CC_NE, -1, FALSE);
4400                         amd64_patch (br [1], br [0]);
4401
4402                         if (ins->dreg != AMD64_RAX) {
4403                                 amd64_mov_reg_reg (code, ins->dreg, AMD64_RAX, size);
4404                                 amd64_pop_reg (code, AMD64_RAX);
4405                         }
4406
4407                         if (ins->sreg2 != sreg2)
4408                                 amd64_pop_reg (code, AMD64_RDX);
4409
4410                         break;
4411                 }
4412                 default:
4413                         g_warning ("unknown opcode %s in %s()\n", mono_inst_name (ins->opcode), __FUNCTION__);
4414                         g_assert_not_reached ();
4415                 }
4416
4417                 if ((code - cfg->native_code - offset) > max_len) {
4418                         g_warning ("wrong maximal instruction length of instruction %s (expected %d, got %ld)",
4419                                    mono_inst_name (ins->opcode), max_len, code - cfg->native_code - offset);
4420                         g_assert_not_reached ();
4421                 }
4422                
4423                 cpos += max_len;
4424
4425                 last_offset = offset;
4426         }
4427
4428         cfg->code_len = code - cfg->native_code;
4429 }
4430
4431 void
4432 mono_arch_register_lowlevel_calls (void)
4433 {
4434 }
4435
4436 void
4437 mono_arch_patch_code (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *ji, gboolean run_cctors)
4438 {
4439         MonoJumpInfo *patch_info;
4440         gboolean compile_aot = !run_cctors;
4441
4442         for (patch_info = ji; patch_info; patch_info = patch_info->next) {
4443                 unsigned char *ip = patch_info->ip.i + code;
4444                 unsigned char *target;
4445
4446                 target = mono_resolve_patch_target (method, domain, code, patch_info, run_cctors);
4447
4448                 if (compile_aot) {
4449                         switch (patch_info->type) {
4450                         case MONO_PATCH_INFO_BB:
4451                         case MONO_PATCH_INFO_LABEL:
4452                                 break;
4453                         default:
4454                                 /* No need to patch these */
4455                                 continue;
4456                         }
4457                 }
4458
4459                 switch (patch_info->type) {
4460                 case MONO_PATCH_INFO_NONE:
4461                         continue;
4462                 case MONO_PATCH_INFO_METHOD_REL:
4463                 case MONO_PATCH_INFO_R8:
4464                 case MONO_PATCH_INFO_R4:
4465                         g_assert_not_reached ();
4466                         continue;
4467                 case MONO_PATCH_INFO_BB:
4468                         break;
4469                 default:
4470                         break;
4471                 }
4472
4473                 /* 
4474                  * Debug code to help track down problems where the target of a near call is
4475                  * is not valid.
4476                  */
4477                 if (amd64_is_near_call (ip)) {
4478                         gint64 disp = (guint8*)target - (guint8*)ip;
4479
4480                         if (!amd64_is_imm32 (disp)) {
4481                                 printf ("TYPE: %d\n", patch_info->type);
4482                                 switch (patch_info->type) {
4483                                 case MONO_PATCH_INFO_INTERNAL_METHOD:
4484                                         printf ("V: %s\n", patch_info->data.name);
4485                                         break;
4486                                 case MONO_PATCH_INFO_METHOD_JUMP:
4487                                 case MONO_PATCH_INFO_METHOD:
4488                                         printf ("V: %s\n", patch_info->data.method->name);
4489                                         break;
4490                                 default:
4491                                         break;
4492                                 }
4493                         }
4494                 }
4495
4496                 amd64_patch (ip, (gpointer)target);
4497         }
4498 }
4499
4500 /*
4501  * This macro is used for testing whenever the unwinder works correctly at every point
4502  * where an async exception can happen.
4503  */
4504 /* This will generate a SIGSEGV at the given point in the code */
4505 #define async_exc_point(code) do { \
4506     if (mono_inject_async_exc_method && mono_method_desc_full_match (mono_inject_async_exc_method, cfg->method)) { \
4507          if (cfg->arch.async_point_count == mono_inject_async_exc_pos) \
4508              amd64_mov_reg_mem (code, AMD64_RAX, 0, 4); \
4509          cfg->arch.async_point_count ++; \
4510     } \
4511 } while (0)
4512
4513 guint8 *
4514 mono_arch_emit_prolog (MonoCompile *cfg)
4515 {
4516         MonoMethod *method = cfg->method;
4517         MonoBasicBlock *bb;
4518         MonoMethodSignature *sig;
4519         MonoInst *ins;
4520         int alloc_size, pos, max_offset, i, quad;
4521         guint8 *code;
4522         CallInfo *cinfo;
4523         gint32 lmf_offset = cfg->arch.lmf_offset;
4524         gboolean args_clobbered = FALSE;
4525         gboolean trace = FALSE;
4526
4527         cfg->code_size =  MAX (((MonoMethodNormal *)method)->header->code_size * 4, 10240);
4528
4529         code = cfg->native_code = g_malloc (cfg->code_size);
4530
4531         if (mono_jit_trace_calls != NULL && mono_trace_eval (method))
4532                 trace = TRUE;
4533
4534         /* Amount of stack space allocated by register saving code */
4535         pos = 0;
4536
4537         /* 
4538          * The prolog consists of the following parts:
4539          * FP present:
4540          * - push rbp, mov rbp, rsp
4541          * - save callee saved regs using pushes
4542          * - allocate frame
4543          * - save rgctx if needed
4544          * - save lmf if needed
4545          * FP not present:
4546          * - allocate frame
4547          * - save rgctx if needed
4548          * - save lmf if needed
4549          * - save callee saved regs using moves
4550          */
4551
4552         async_exc_point (code);
4553
4554         if (!cfg->arch.omit_fp) {
4555                 amd64_push_reg (code, AMD64_RBP);
4556                 async_exc_point (code);
4557                 amd64_mov_reg_reg (code, AMD64_RBP, AMD64_RSP, sizeof (gpointer));
4558                 async_exc_point (code);
4559         }
4560
4561         /* Save callee saved registers */
4562         if (!cfg->arch.omit_fp && !method->save_lmf) {
4563                 for (i = 0; i < AMD64_NREG; ++i)
4564                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
4565                                 amd64_push_reg (code, i);
4566                                 pos += sizeof (gpointer);
4567                                 async_exc_point (code);
4568                         }
4569         }
4570
4571         if (cfg->arch.omit_fp) {
4572                 /* 
4573                  * On enter, the stack is misaligned by the the pushing of the return
4574                  * address. It is either made aligned by the pushing of %rbp, or by
4575                  * this.
4576                  */
4577                 alloc_size = ALIGN_TO (cfg->stack_offset, 8);
4578                 if ((alloc_size % 16) == 0)
4579                         alloc_size += 8;
4580         } else {
4581                 alloc_size = ALIGN_TO (cfg->stack_offset, MONO_ARCH_FRAME_ALIGNMENT);
4582
4583                 alloc_size -= pos;
4584         }
4585
4586         cfg->arch.stack_alloc_size = alloc_size;
4587
4588         /* Allocate stack frame */
4589         if (alloc_size) {
4590                 /* See mono_emit_stack_alloc */
4591 #if defined(PLATFORM_WIN32) || defined(MONO_ARCH_SIGSEGV_ON_ALTSTACK)
4592                 guint32 remaining_size = alloc_size;
4593                 while (remaining_size >= 0x1000) {
4594                         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 0x1000);
4595                         async_exc_point (code);
4596                         amd64_test_membase_reg (code, AMD64_RSP, 0, AMD64_RSP);
4597                         remaining_size -= 0x1000;
4598                 }
4599                 if (remaining_size) {
4600                         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, remaining_size);
4601                         async_exc_point (code);
4602                 }
4603 #else
4604                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, alloc_size);
4605                 async_exc_point (code);
4606 #endif
4607         }
4608
4609         /* Stack alignment check */
4610 #if 0
4611         {
4612                 amd64_mov_reg_reg (code, AMD64_RAX, AMD64_RSP, 8);
4613                 amd64_alu_reg_imm (code, X86_AND, AMD64_RAX, 0xf);
4614                 amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, 0);
4615                 x86_branch8 (code, X86_CC_EQ, 2, FALSE);
4616                 amd64_breakpoint (code);
4617         }
4618 #endif
4619
4620         /* Save LMF */
4621         if (method->save_lmf) {
4622                 /* 
4623                  * The ip field is not set, the exception handling code will obtain it from the stack location pointed to by the sp field.
4624                  */
4625                 /* sp is saved right before calls */
4626                 /* Skip method (only needed for trampoline LMF frames) */
4627                 /* Save callee saved regs */
4628                 amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbx), AMD64_RBX, 8);
4629                 amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbp), AMD64_RBP, 8);
4630                 amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r12), AMD64_R12, 8);
4631                 amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r13), AMD64_R13, 8);
4632                 amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r14), AMD64_R14, 8);
4633                 amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r15), AMD64_R15, 8);
4634         }
4635
4636         /* Save callee saved registers */
4637         if (cfg->arch.omit_fp && !method->save_lmf) {
4638                 gint32 save_area_offset = 0;
4639
4640                 /* Save caller saved registers after sp is adjusted */
4641                 /* The registers are saved at the bottom of the frame */
4642                 /* FIXME: Optimize this so the regs are saved at the end of the frame in increasing order */
4643                 for (i = 0; i < AMD64_NREG; ++i)
4644                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
4645                                 amd64_mov_membase_reg (code, AMD64_RSP, save_area_offset, i, 8);
4646                                 save_area_offset += 8;
4647                                 async_exc_point (code);
4648                         }
4649         }
4650
4651         /* store runtime generic context */
4652         if (cfg->rgctx_var) {
4653                 g_assert (cfg->rgctx_var->opcode == OP_REGOFFSET &&
4654                                 (cfg->rgctx_var->inst_basereg == AMD64_RBP || cfg->rgctx_var->inst_basereg == AMD64_RSP));
4655
4656                 amd64_mov_membase_reg (code, cfg->rgctx_var->inst_basereg, cfg->rgctx_var->inst_offset, MONO_ARCH_RGCTX_REG, 8);
4657         }
4658
4659         /* compute max_offset in order to use short forward jumps */
4660         max_offset = 0;
4661         if (cfg->opt & MONO_OPT_BRANCH) {
4662                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4663                         bb->max_offset = max_offset;
4664
4665                         if (cfg->prof_options & MONO_PROFILE_COVERAGE)
4666                                 max_offset += 6;
4667                         /* max alignment for loops */
4668                         if ((cfg->opt & MONO_OPT_LOOP) && bb_is_loop_start (bb))
4669                                 max_offset += LOOP_ALIGNMENT;
4670
4671                         MONO_BB_FOR_EACH_INS (bb, ins) {
4672                                 if (ins->opcode == OP_LABEL)
4673                                         ins->inst_c1 = max_offset;
4674                                 
4675                                 max_offset += ((guint8 *)ins_get_spec (ins->opcode))[MONO_INST_LEN];
4676                         }
4677                 }
4678         }
4679
4680         sig = mono_method_signature (method);
4681         pos = 0;
4682
4683         cinfo = cfg->arch.cinfo;
4684
4685         if (sig->ret->type != MONO_TYPE_VOID) {
4686                 /* Save volatile arguments to the stack */
4687                 if (cfg->vret_addr && (cfg->vret_addr->opcode != OP_REGVAR))
4688                         amd64_mov_membase_reg (code, cfg->vret_addr->inst_basereg, cfg->vret_addr->inst_offset, cinfo->ret.reg, 8);
4689         }
4690
4691         /* Keep this in sync with emit_load_volatile_arguments */
4692         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
4693                 ArgInfo *ainfo = cinfo->args + i;
4694                 gint32 stack_offset;
4695                 MonoType *arg_type;
4696
4697                 ins = cfg->args [i];
4698
4699                 if ((ins->flags & MONO_INST_IS_DEAD) && !trace)
4700                         /* Unused arguments */
4701                         continue;
4702
4703                 if (sig->hasthis && (i == 0))
4704                         arg_type = &mono_defaults.object_class->byval_arg;
4705                 else
4706                         arg_type = sig->params [i - sig->hasthis];
4707
4708                 stack_offset = ainfo->offset + ARGS_OFFSET;
4709
4710                 /* Save volatile arguments to the stack */
4711                 if (ins->opcode != OP_REGVAR) {
4712                         switch (ainfo->storage) {
4713                         case ArgInIReg: {
4714                                 guint32 size = 8;
4715
4716                                 /* FIXME: I1 etc */
4717                                 /*
4718                                 if (stack_offset & 0x1)
4719                                         size = 1;
4720                                 else if (stack_offset & 0x2)
4721                                         size = 2;
4722                                 else if (stack_offset & 0x4)
4723                                         size = 4;
4724                                 else
4725                                         size = 8;
4726                                 */
4727                                 amd64_mov_membase_reg (code, ins->inst_basereg, ins->inst_offset, ainfo->reg, size);
4728                                 break;
4729                         }
4730                         case ArgInFloatSSEReg:
4731                                 amd64_movss_membase_reg (code, ins->inst_basereg, ins->inst_offset, ainfo->reg);
4732                                 break;
4733                         case ArgInDoubleSSEReg:
4734                                 amd64_movsd_membase_reg (code, ins->inst_basereg, ins->inst_offset, ainfo->reg);
4735                                 break;
4736                         case ArgValuetypeInReg:
4737                                 for (quad = 0; quad < 2; quad ++) {
4738                                         switch (ainfo->pair_storage [quad]) {
4739                                         case ArgInIReg:
4740                                                 amd64_mov_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof (gpointer)), ainfo->pair_regs [quad], sizeof (gpointer));
4741                                                 break;
4742                                         case ArgInFloatSSEReg:
4743                                                 amd64_movss_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof (gpointer)), ainfo->pair_regs [quad]);
4744                                                 break;
4745                                         case ArgInDoubleSSEReg:
4746                                                 amd64_movsd_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof (gpointer)), ainfo->pair_regs [quad]);
4747                                                 break;
4748                                         case ArgNone:
4749                                                 break;
4750                                         default:
4751                                                 g_assert_not_reached ();
4752                                         }
4753                                 }
4754                                 break;
4755                         default:
4756                                 break;
4757                         }
4758                 } else {
4759                         /* Argument allocated to (non-volatile) register */
4760                         switch (ainfo->storage) {
4761                         case ArgInIReg:
4762                                 amd64_mov_reg_reg (code, ins->dreg, ainfo->reg, 8);
4763                                 break;
4764                         case ArgOnStack:
4765                                 amd64_mov_reg_membase (code, ins->dreg, AMD64_RBP, ARGS_OFFSET + ainfo->offset, 8);
4766                                 break;
4767                         default:
4768                                 g_assert_not_reached ();
4769                         }
4770                 }
4771         }
4772
4773         /* Might need to attach the thread to the JIT  or change the domain for the callback */
4774         if (method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
4775                 guint64 domain = (guint64)cfg->domain;
4776
4777                 args_clobbered = TRUE;
4778
4779                 /* 
4780                  * The call might clobber argument registers, but they are already
4781                  * saved to the stack/global regs.
4782                  */
4783                 if (appdomain_tls_offset != -1 && lmf_tls_offset != -1) {
4784                         guint8 *buf, *no_domain_branch;
4785
4786                         code = emit_tls_get (code, AMD64_RAX, appdomain_tls_offset);
4787                         if ((domain >> 32) == 0)
4788                                 amd64_mov_reg_imm_size (code, AMD64_ARG_REG1, domain, 4);
4789                         else
4790                                 amd64_mov_reg_imm_size (code, AMD64_ARG_REG1, domain, 8);
4791                         amd64_alu_reg_reg (code, X86_CMP, AMD64_RAX, AMD64_ARG_REG1);
4792                         no_domain_branch = code;
4793                         x86_branch8 (code, X86_CC_NE, 0, 0);
4794                         code = emit_tls_get ( code, AMD64_RAX, lmf_addr_tls_offset);
4795                         amd64_test_reg_reg (code, AMD64_RAX, AMD64_RAX);
4796                         buf = code;
4797                         x86_branch8 (code, X86_CC_NE, 0, 0);
4798                         amd64_patch (no_domain_branch, code);
4799                         code = emit_call (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD, (gpointer)"mono_jit_thread_attach");
4800                         amd64_patch (buf, code);
4801                 } else {
4802                         g_assert (!cfg->compile_aot);
4803                         if ((domain >> 32) == 0)
4804                                 amd64_mov_reg_imm_size (code, AMD64_ARG_REG1, domain, 4);
4805                         else
4806                                 amd64_mov_reg_imm_size (code, AMD64_ARG_REG1, domain, 8);
4807                         code = emit_call (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD, (gpointer)"mono_jit_thread_attach");
4808                 }
4809         }
4810
4811         if (method->save_lmf) {
4812                 if ((lmf_tls_offset != -1) && !optimize_for_xen) {
4813                         /*
4814                          * Optimized version which uses the mono_lmf TLS variable instead of indirection
4815                          * through the mono_lmf_addr TLS variable.
4816                          */
4817                         /* %rax = previous_lmf */
4818                         x86_prefix (code, X86_FS_PREFIX);
4819                         amd64_mov_reg_mem (code, AMD64_RAX, lmf_tls_offset, 8);
4820
4821                         /* Save previous_lmf */
4822                         amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), AMD64_RAX, 8);
4823                         /* Set new lmf */
4824                         if (lmf_offset == 0) {
4825                                 x86_prefix (code, X86_FS_PREFIX);
4826                                 amd64_mov_mem_reg (code, lmf_tls_offset, cfg->frame_reg, 8);
4827                         } else {
4828                                 amd64_lea_membase (code, AMD64_R11, cfg->frame_reg, lmf_offset);
4829                                 x86_prefix (code, X86_FS_PREFIX);
4830                                 amd64_mov_mem_reg (code, lmf_tls_offset, AMD64_R11, 8);
4831                         }
4832                 } else {
4833                         if (lmf_addr_tls_offset != -1) {
4834                                 /* Load lmf quicky using the FS register */
4835                                 code = emit_tls_get (code, AMD64_RAX, lmf_addr_tls_offset);
4836                         }
4837                         else {
4838                                 /* 
4839                                  * The call might clobber argument registers, but they are already
4840                                  * saved to the stack/global regs.
4841                                  */
4842                                 args_clobbered = TRUE;
4843                                 code = emit_call (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD, 
4844                                                                   (gpointer)"mono_get_lmf_addr");               
4845                         }
4846
4847                         /* Save lmf_addr */
4848                         amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, lmf_addr), AMD64_RAX, 8);
4849                         /* Save previous_lmf */
4850                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RAX, 0, 8);
4851                         amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), AMD64_R11, 8);
4852                         /* Set new lmf */
4853                         amd64_lea_membase (code, AMD64_R11, cfg->frame_reg, lmf_offset);
4854                         amd64_mov_membase_reg (code, AMD64_RAX, 0, AMD64_R11, 8);
4855                 }
4856         }
4857
4858         if (trace) {
4859                 args_clobbered = TRUE;
4860                 code = mono_arch_instrument_prolog (cfg, mono_trace_enter_method, code, TRUE);
4861         }
4862
4863         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
4864                 args_clobbered = TRUE;
4865
4866         /*
4867          * Optimize the common case of the first bblock making a call with the same
4868          * arguments as the method. This works because the arguments are still in their
4869          * original argument registers.
4870          * FIXME: Generalize this
4871          */
4872         if (!args_clobbered) {
4873                 MonoBasicBlock *first_bb = cfg->bb_entry;
4874                 MonoInst *next;
4875
4876                 next = mono_inst_list_first (&first_bb->ins_list);
4877                 if (!next && first_bb->next_bb) {
4878                         first_bb = first_bb->next_bb;
4879                         next = mono_inst_list_first (&first_bb->ins_list);
4880                 }
4881
4882                 if (first_bb->in_count > 1)
4883                         next = NULL;
4884
4885                 for (i = 0; next && i < sig->param_count + sig->hasthis; ++i) {
4886                         ArgInfo *ainfo = cinfo->args + i;
4887                         gboolean match = FALSE;
4888                         
4889                         ins = cfg->args [i];
4890                         if (ins->opcode != OP_REGVAR) {
4891                                 switch (ainfo->storage) {
4892                                 case ArgInIReg: {
4893                                         if (((next->opcode == OP_LOAD_MEMBASE) || (next->opcode == OP_LOADI4_MEMBASE)) && next->inst_basereg == ins->inst_basereg && next->inst_offset == ins->inst_offset) {
4894                                                 if (next->dreg == ainfo->reg) {
4895                                                         NULLIFY_INS (next);
4896                                                         match = TRUE;
4897                                                 } else {
4898                                                         next->opcode = OP_MOVE;
4899                                                         next->sreg1 = ainfo->reg;
4900                                                         /* Only continue if the instruction doesn't change argument regs */
4901                                                         if (next->dreg == ainfo->reg || next->dreg == AMD64_RAX)
4902                                                                 match = TRUE;
4903                                                 }
4904                                         }
4905                                         break;
4906                                 }
4907                                 default:
4908                                         break;
4909                                 }
4910                         } else {
4911                                 /* Argument allocated to (non-volatile) register */
4912                                 switch (ainfo->storage) {
4913                                 case ArgInIReg:
4914                                         if (next->opcode == OP_MOVE && next->sreg1 == ins->dreg && next->dreg == ainfo->reg) {
4915                                                 NULLIFY_INS (next);
4916                                                 match = TRUE;
4917                                         }
4918                                         break;
4919                                 default:
4920                                         break;
4921                                 }
4922                         }
4923
4924                         if (match) {
4925                                 next = mono_inst_list_next (&next->node, &first_bb->ins_list);
4926                                 if (!next)
4927                                         break;
4928                         }
4929                 }
4930         }
4931
4932         cfg->code_len = code - cfg->native_code;
4933
4934         g_assert (cfg->code_len < cfg->code_size);
4935
4936         return code;
4937 }
4938
4939 void
4940 mono_arch_emit_epilog (MonoCompile *cfg)
4941 {
4942         MonoMethod *method = cfg->method;
4943         int quad, pos, i;
4944         guint8 *code;
4945         int max_epilog_size = 16;
4946         CallInfo *cinfo;
4947         gint32 lmf_offset = cfg->arch.lmf_offset;
4948         
4949         if (cfg->method->save_lmf)
4950                 max_epilog_size += 256;
4951         
4952         if (mono_jit_trace_calls != NULL)
4953                 max_epilog_size += 50;
4954
4955         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
4956                 max_epilog_size += 50;
4957
4958         max_epilog_size += (AMD64_NREG * 2);
4959
4960         while (cfg->code_len + max_epilog_size > (cfg->code_size - 16)) {
4961                 cfg->code_size *= 2;
4962                 cfg->native_code = g_realloc (cfg->native_code, cfg->code_size);
4963                 mono_jit_stats.code_reallocs++;
4964         }
4965
4966         code = cfg->native_code + cfg->code_len;
4967
4968         if (mono_jit_trace_calls != NULL && mono_trace_eval (method))
4969                 code = mono_arch_instrument_epilog (cfg, mono_trace_leave_method, code, TRUE);
4970
4971         /* the code restoring the registers must be kept in sync with OP_JMP */
4972         pos = 0;
4973         
4974         if (method->save_lmf) {
4975                 if ((lmf_tls_offset != -1) && !optimize_for_xen) {
4976                         /*
4977                          * Optimized version which uses the mono_lmf TLS variable instead of indirection
4978                          * through the mono_lmf_addr TLS variable.
4979                          */
4980                         /* reg = previous_lmf */
4981                         amd64_mov_reg_membase (code, AMD64_R11, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), 8);
4982                         x86_prefix (code, X86_FS_PREFIX);
4983                         amd64_mov_mem_reg (code, lmf_tls_offset, AMD64_R11, 8);
4984                 } else {
4985                         /* Restore previous lmf */
4986                         amd64_mov_reg_membase (code, AMD64_RCX, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), 8);
4987                         amd64_mov_reg_membase (code, AMD64_R11, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, lmf_addr), 8);
4988                         amd64_mov_membase_reg (code, AMD64_R11, 0, AMD64_RCX, 8);
4989                 }
4990
4991                 /* Restore caller saved regs */
4992                 if (cfg->used_int_regs & (1 << AMD64_RBP)) {
4993                         amd64_mov_reg_membase (code, AMD64_RBP, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbp), 8);
4994                 }
4995                 if (cfg->used_int_regs & (1 << AMD64_RBX)) {
4996                         amd64_mov_reg_membase (code, AMD64_RBX, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbx), 8);
4997                 }
4998                 if (cfg->used_int_regs & (1 << AMD64_R12)) {
4999                         amd64_mov_reg_membase (code, AMD64_R12, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r12), 8);
5000                 }
5001                 if (cfg->used_int_regs & (1 << AMD64_R13)) {
5002                         amd64_mov_reg_membase (code, AMD64_R13, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r13), 8);
5003                 }
5004                 if (cfg->used_int_regs & (1 << AMD64_R14)) {
5005                         amd64_mov_reg_membase (code, AMD64_R14, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r14), 8);
5006                 }
5007                 if (cfg->used_int_regs & (1 << AMD64_R15)) {
5008                         amd64_mov_reg_membase (code, AMD64_R15, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r15), 8);
5009                 }
5010         } else {
5011
5012                 if (cfg->arch.omit_fp) {
5013                         gint32 save_area_offset = 0;
5014
5015                         for (i = 0; i < AMD64_NREG; ++i)
5016                                 if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
5017                                         amd64_mov_reg_membase (code, i, AMD64_RSP, save_area_offset, 8);
5018                                         save_area_offset += 8;
5019                                 }
5020                 }
5021                 else {
5022                         for (i = 0; i < AMD64_NREG; ++i)
5023                                 if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i)))
5024                                         pos -= sizeof (gpointer);
5025
5026                         if (pos) {
5027                                 if (pos == - sizeof (gpointer)) {
5028                                         /* Only one register, so avoid lea */
5029                                         for (i = AMD64_NREG - 1; i > 0; --i)
5030                                                 if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
5031                                                         amd64_mov_reg_membase (code, i, AMD64_RBP, pos, 8);
5032                                                 }
5033                                 }
5034                                 else {
5035                                         amd64_lea_membase (code, AMD64_RSP, AMD64_RBP, pos);
5036
5037                                         /* Pop registers in reverse order */
5038                                         for (i = AMD64_NREG - 1; i > 0; --i)
5039                                                 if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
5040                                                         amd64_pop_reg (code, i);
5041                                                 }
5042                                 }
5043                         }
5044                 }
5045         }
5046
5047         /* Load returned vtypes into registers if needed */
5048         cinfo = cfg->arch.cinfo;
5049         if (cinfo->ret.storage == ArgValuetypeInReg) {
5050                 ArgInfo *ainfo = &cinfo->ret;
5051                 MonoInst *inst = cfg->ret;
5052
5053                 for (quad = 0; quad < 2; quad ++) {
5054                         switch (ainfo->pair_storage [quad]) {
5055                         case ArgInIReg:
5056                                 amd64_mov_reg_membase (code, ainfo->pair_regs [quad], inst->inst_basereg, inst->inst_offset + (quad * sizeof (gpointer)), sizeof (gpointer));
5057                                 break;
5058                         case ArgInFloatSSEReg:
5059                                 amd64_movss_reg_membase (code, ainfo->pair_regs [quad], inst->inst_basereg, inst->inst_offset + (quad * sizeof (gpointer)));
5060                                 break;
5061                         case ArgInDoubleSSEReg:
5062                                 amd64_movsd_reg_membase (code, ainfo->pair_regs [quad], inst->inst_basereg, inst->inst_offset + (quad * sizeof (gpointer)));
5063                                 break;
5064                         case ArgNone:
5065                                 break;
5066                         default:
5067                                 g_assert_not_reached ();
5068                         }
5069                 }
5070         }
5071
5072         if (cfg->arch.omit_fp) {
5073                 if (cfg->arch.stack_alloc_size)
5074                         amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, cfg->arch.stack_alloc_size);
5075         } else {
5076                 amd64_leave (code);
5077         }
5078         async_exc_point (code);
5079         amd64_ret (code);
5080
5081         cfg->code_len = code - cfg->native_code;
5082
5083         g_assert (cfg->code_len < cfg->code_size);
5084
5085         if (cfg->arch.omit_fp) {
5086                 /* 
5087                  * Encode the stack size into used_int_regs so the exception handler
5088                  * can access it.
5089                  */
5090                 g_assert (cfg->arch.stack_alloc_size < (1 << 16));
5091                 cfg->used_int_regs |= (1 << 31) | (cfg->arch.stack_alloc_size << 16);
5092         }
5093 }
5094
5095 void
5096 mono_arch_emit_exceptions (MonoCompile *cfg)
5097 {
5098         MonoJumpInfo *patch_info;
5099         int nthrows, i;
5100         guint8 *code;
5101         MonoClass *exc_classes [16];
5102         guint8 *exc_throw_start [16], *exc_throw_end [16];
5103         guint32 code_size = 0;
5104
5105         /* Compute needed space */
5106         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5107                 if (patch_info->type == MONO_PATCH_INFO_EXC)
5108                         code_size += 40;
5109                 if (patch_info->type == MONO_PATCH_INFO_R8)
5110                         code_size += 8 + 15; /* sizeof (double) + alignment */
5111                 if (patch_info->type == MONO_PATCH_INFO_R4)
5112                         code_size += 4 + 15; /* sizeof (float) + alignment */
5113         }
5114
5115         while (cfg->code_len + code_size > (cfg->code_size - 16)) {
5116                 cfg->code_size *= 2;
5117                 cfg->native_code = g_realloc (cfg->native_code, cfg->code_size);
5118                 mono_jit_stats.code_reallocs++;
5119         }
5120
5121         code = cfg->native_code + cfg->code_len;
5122
5123         /* add code to raise exceptions */
5124         nthrows = 0;
5125         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5126                 switch (patch_info->type) {
5127                 case MONO_PATCH_INFO_EXC: {
5128                         MonoClass *exc_class;
5129                         guint8 *buf, *buf2;
5130                         guint32 throw_ip;
5131
5132                         amd64_patch (patch_info->ip.i + cfg->native_code, code);
5133
5134                         exc_class = mono_class_from_name (mono_defaults.corlib, "System", patch_info->data.name);
5135                         g_assert (exc_class);
5136                         throw_ip = patch_info->ip.i;
5137
5138                         //x86_breakpoint (code);
5139                         /* Find a throw sequence for the same exception class */
5140                         for (i = 0; i < nthrows; ++i)
5141                                 if (exc_classes [i] == exc_class)
5142                                         break;
5143                         if (i < nthrows) {
5144                                 amd64_mov_reg_imm (code, AMD64_ARG_REG2, (exc_throw_end [i] - cfg->native_code) - throw_ip);
5145                                 x86_jump_code (code, exc_throw_start [i]);
5146                                 patch_info->type = MONO_PATCH_INFO_NONE;
5147                         }
5148                         else {
5149                                 buf = code;
5150                                 amd64_mov_reg_imm_size (code, AMD64_ARG_REG2, 0xf0f0f0f0, 4);
5151                                 buf2 = code;
5152
5153                                 if (nthrows < 16) {
5154                                         exc_classes [nthrows] = exc_class;
5155                                         exc_throw_start [nthrows] = code;
5156                                 }
5157                                 amd64_mov_reg_imm (code, AMD64_ARG_REG1, exc_class->type_token);
5158                                 patch_info->data.name = "mono_arch_throw_corlib_exception";
5159                                 patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
5160                                 patch_info->ip.i = code - cfg->native_code;
5161
5162                                 code = emit_call_body (cfg, code, patch_info->type, patch_info->data.name);
5163
5164                                 amd64_mov_reg_imm (buf, AMD64_ARG_REG2, (code - cfg->native_code) - throw_ip);
5165                                 while (buf < buf2)
5166                                         x86_nop (buf);
5167
5168                                 if (nthrows < 16) {
5169                                         exc_throw_end [nthrows] = code;
5170                                         nthrows ++;
5171                                 }
5172                         }
5173                         break;
5174                 }
5175                 default:
5176                         /* do nothing */
5177                         break;
5178                 }
5179         }
5180
5181         /* Handle relocations with RIP relative addressing */
5182         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5183                 gboolean remove = FALSE;
5184
5185                 switch (patch_info->type) {
5186                 case MONO_PATCH_INFO_R8:
5187                 case MONO_PATCH_INFO_R4: {
5188                         guint8 *pos;
5189
5190                         if (use_sse2) {
5191                                 /* The SSE opcodes require a 16 byte alignment */
5192                                 code = (guint8*)ALIGN_TO (code, 16);
5193                         } else {
5194                                 code = (guint8*)ALIGN_TO (code, 8);
5195                         }
5196
5197                         pos = cfg->native_code + patch_info->ip.i;
5198
5199
5200                         if (use_sse2) {
5201                                 if (IS_REX (pos [1]))
5202                                         *(guint32*)(pos + 5) = (guint8*)code - pos - 9;
5203                                 else
5204                                         *(guint32*)(pos + 4) = (guint8*)code - pos - 8;
5205                         } else {
5206                                 *(guint32*)(pos + 3) = (guint8*)code - pos - 7;
5207                         }
5208
5209                         if (patch_info->type == MONO_PATCH_INFO_R8) {
5210                                 *(double*)code = *(double*)patch_info->data.target;
5211                                 code += sizeof (double);
5212                         } else {
5213                                 *(float*)code = *(float*)patch_info->data.target;
5214                                 code += sizeof (float);
5215                         }
5216
5217                         remove = TRUE;
5218                         break;
5219                 }
5220                 default:
5221                         break;
5222                 }
5223
5224                 if (remove) {
5225                         if (patch_info == cfg->patch_info)
5226                                 cfg->patch_info = patch_info->next;
5227                         else {
5228                                 MonoJumpInfo *tmp;
5229
5230                                 for (tmp = cfg->patch_info; tmp->next != patch_info; tmp = tmp->next)
5231                                         ;
5232                                 tmp->next = patch_info->next;
5233                         }
5234                 }
5235         }
5236
5237         cfg->code_len = code - cfg->native_code;
5238
5239         g_assert (cfg->code_len < cfg->code_size);
5240
5241 }
5242
5243 void*
5244 mono_arch_instrument_prolog (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments)
5245 {
5246         guchar *code = p;
5247         CallInfo *cinfo = NULL;
5248         MonoMethodSignature *sig;
5249         MonoInst *inst;
5250         int i, n, stack_area = 0;
5251
5252         /* Keep this in sync with mono_arch_get_argument_info */
5253
5254         if (enable_arguments) {
5255                 /* Allocate a new area on the stack and save arguments there */
5256                 sig = mono_method_signature (cfg->method);
5257
5258                 cinfo = get_call_info (cfg, cfg->mempool, sig, FALSE);
5259
5260                 n = sig->param_count + sig->hasthis;
5261
5262                 stack_area = ALIGN_TO (n * 8, 16);
5263
5264                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, stack_area);
5265
5266                 for (i = 0; i < n; ++i) {
5267                         inst = cfg->args [i];
5268
5269                         if (inst->opcode == OP_REGVAR)
5270                                 amd64_mov_membase_reg (code, AMD64_RSP, (i * 8), inst->dreg, 8);
5271                         else {
5272                                 amd64_mov_reg_membase (code, AMD64_R11, inst->inst_basereg, inst->inst_offset, 8);
5273                                 amd64_mov_membase_reg (code, AMD64_RSP, (i * 8), AMD64_R11, 8);
5274                         }
5275                 }
5276         }
5277
5278         mono_add_patch_info (cfg, code-cfg->native_code, MONO_PATCH_INFO_METHODCONST, cfg->method);
5279         amd64_set_reg_template (code, AMD64_ARG_REG1);
5280         amd64_mov_reg_reg (code, AMD64_ARG_REG2, AMD64_RSP, 8);
5281         code = emit_call (cfg, code, MONO_PATCH_INFO_ABS, (gpointer)func);
5282
5283         if (enable_arguments)
5284                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, stack_area);
5285
5286         return code;
5287 }
5288
5289 enum {
5290         SAVE_NONE,
5291         SAVE_STRUCT,
5292         SAVE_EAX,
5293         SAVE_EAX_EDX,
5294         SAVE_XMM
5295 };
5296
5297 void*
5298 mono_arch_instrument_epilog (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments)
5299 {
5300         guchar *code = p;
5301         int save_mode = SAVE_NONE;
5302         MonoMethod *method = cfg->method;
5303         int rtype = mono_type_get_underlying_type (mono_method_signature (method)->ret)->type;
5304         
5305         switch (rtype) {
5306         case MONO_TYPE_VOID:
5307                 /* special case string .ctor icall */
5308                 if (strcmp (".ctor", method->name) && method->klass == mono_defaults.string_class)
5309                         save_mode = SAVE_EAX;
5310                 else
5311                         save_mode = SAVE_NONE;
5312                 break;
5313         case MONO_TYPE_I8:
5314         case MONO_TYPE_U8:
5315                 save_mode = SAVE_EAX;
5316                 break;
5317         case MONO_TYPE_R4:
5318         case MONO_TYPE_R8:
5319                 save_mode = SAVE_XMM;
5320                 break;
5321         case MONO_TYPE_GENERICINST:
5322                 if (!mono_type_generic_inst_is_valuetype (mono_method_signature (method)->ret)) {
5323                         save_mode = SAVE_EAX;
5324                         break;
5325                 }
5326                 /* Fall through */
5327         case MONO_TYPE_VALUETYPE:
5328                 save_mode = SAVE_STRUCT;
5329                 break;
5330         default:
5331                 save_mode = SAVE_EAX;
5332                 break;
5333         }
5334
5335         /* Save the result and copy it into the proper argument register */
5336         switch (save_mode) {
5337         case SAVE_EAX:
5338                 amd64_push_reg (code, AMD64_RAX);
5339                 /* Align stack */
5340                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
5341                 if (enable_arguments)
5342                         amd64_mov_reg_reg (code, AMD64_ARG_REG2, AMD64_RAX, 8);
5343                 break;
5344         case SAVE_STRUCT:
5345                 /* FIXME: */
5346                 if (enable_arguments)
5347                         amd64_mov_reg_imm (code, AMD64_ARG_REG2, 0);
5348                 break;
5349         case SAVE_XMM:
5350                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
5351                 amd64_movsd_membase_reg (code, AMD64_RSP, 0, AMD64_XMM0);
5352                 /* Align stack */
5353                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
5354                 /* 
5355                  * The result is already in the proper argument register so no copying
5356                  * needed.
5357                  */
5358                 break;
5359         case SAVE_NONE:
5360                 break;
5361         default:
5362                 g_assert_not_reached ();
5363         }
5364
5365         /* Set %al since this is a varargs call */
5366         if (save_mode == SAVE_XMM)
5367                 amd64_mov_reg_imm (code, AMD64_RAX, 1);
5368         else
5369                 amd64_mov_reg_imm (code, AMD64_RAX, 0);
5370
5371         mono_add_patch_info (cfg, code-cfg->native_code, MONO_PATCH_INFO_METHODCONST, method);
5372         amd64_set_reg_template (code, AMD64_ARG_REG1);
5373         code = emit_call (cfg, code, MONO_PATCH_INFO_ABS, (gpointer)func);
5374
5375         /* Restore result */
5376         switch (save_mode) {
5377         case SAVE_EAX:
5378                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
5379                 amd64_pop_reg (code, AMD64_RAX);
5380                 break;
5381         case SAVE_STRUCT:
5382                 /* FIXME: */
5383                 break;
5384         case SAVE_XMM:
5385                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
5386                 amd64_movsd_reg_membase (code, AMD64_XMM0, AMD64_RSP, 0);
5387                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
5388                 break;
5389         case SAVE_NONE:
5390                 break;
5391         default:
5392                 g_assert_not_reached ();
5393         }
5394
5395         return code;
5396 }
5397
5398 void
5399 mono_arch_flush_icache (guint8 *code, gint size)
5400 {
5401         /* Not needed */
5402 }
5403
5404 void
5405 mono_arch_flush_register_windows (void)
5406 {
5407 }
5408
5409 gboolean 
5410 mono_arch_is_inst_imm (gint64 imm)
5411 {
5412         return amd64_is_imm32 (imm);
5413 }
5414
5415 /*
5416  * Determine whenever the trap whose info is in SIGINFO is caused by
5417  * integer overflow.
5418  */
5419 gboolean
5420 mono_arch_is_int_overflow (void *sigctx, void *info)
5421 {
5422         MonoContext ctx;
5423         guint8* rip;
5424         int reg;
5425         gint64 value;
5426
5427         mono_arch_sigctx_to_monoctx (sigctx, &ctx);
5428
5429         rip = (guint8*)ctx.rip;
5430
5431         if (IS_REX (rip [0])) {
5432                 reg = amd64_rex_b (rip [0]);
5433                 rip ++;
5434         }
5435         else
5436                 reg = 0;
5437
5438         if ((rip [0] == 0xf7) && (x86_modrm_mod (rip [1]) == 0x3) && (x86_modrm_reg (rip [1]) == 0x7)) {
5439                 /* idiv REG */
5440                 reg += x86_modrm_rm (rip [1]);
5441
5442                 switch (reg) {
5443                 case AMD64_RAX:
5444                         value = ctx.rax;
5445                         break;
5446                 case AMD64_RBX:
5447                         value = ctx.rbx;
5448                         break;
5449                 case AMD64_RCX:
5450                         value = ctx.rcx;
5451                         break;
5452                 case AMD64_RDX:
5453                         value = ctx.rdx;
5454                         break;
5455                 case AMD64_RBP:
5456                         value = ctx.rbp;
5457                         break;
5458                 case AMD64_RSP:
5459                         value = ctx.rsp;
5460                         break;
5461                 case AMD64_RSI:
5462                         value = ctx.rsi;
5463                         break;
5464                 case AMD64_RDI:
5465                         value = ctx.rdi;
5466                         break;
5467                 case AMD64_R12:
5468                         value = ctx.r12;
5469                         break;
5470                 case AMD64_R13:
5471                         value = ctx.r13;
5472                         break;
5473                 case AMD64_R14:
5474                         value = ctx.r14;
5475                         break;
5476                 case AMD64_R15:
5477                         value = ctx.r15;
5478                         break;
5479                 default:
5480                         g_assert_not_reached ();
5481                         reg = -1;
5482                 }                       
5483
5484                 if (value == -1)
5485                         return TRUE;
5486         }
5487
5488         return FALSE;
5489 }
5490
5491 guint32
5492 mono_arch_get_patch_offset (guint8 *code)
5493 {
5494         return 3;
5495 }
5496
5497 /**
5498  * mono_breakpoint_clean_code:
5499  *
5500  * Copy @size bytes from @code - @offset to the buffer @buf. If the debugger inserted software
5501  * breakpoints in the original code, they are removed in the copy.
5502  *
5503  * Returns TRUE if no sw breakpoint was present.
5504  */
5505 gboolean
5506 mono_breakpoint_clean_code (guint8 *method_start, guint8 *code, int offset, guint8 *buf, int size)
5507 {
5508         int i;
5509         gboolean can_write = TRUE;
5510         /*
5511          * If method_start is non-NULL we need to perform bound checks, since we access memory
5512          * at code - offset we could go before the start of the method and end up in a different
5513          * page of memory that is not mapped or read incorrect data anyway. We zero-fill the bytes
5514          * instead.
5515          */
5516         if (!method_start || code - offset >= method_start) {
5517                 memcpy (buf, code - offset, size);
5518         } else {
5519                 int diff = code - method_start;
5520                 memset (buf, 0, size);
5521                 memcpy (buf + offset - diff, method_start, diff + size - offset);
5522         }
5523         code -= offset;
5524         for (i = 0; i < MONO_BREAKPOINT_ARRAY_SIZE; ++i) {
5525                 int idx = mono_breakpoint_info_index [i];
5526                 guint8 *ptr;
5527                 if (idx < 1)
5528                         continue;
5529                 ptr = mono_breakpoint_info [idx].address;
5530                 if (ptr >= code && ptr < code + size) {
5531                         guint8 saved_byte = mono_breakpoint_info [idx].saved_byte;
5532                         can_write = FALSE;
5533                         /*g_print ("patching %p with 0x%02x (was: 0x%02x)\n", ptr, saved_byte, buf [ptr - code]);*/
5534                         buf [ptr - code] = saved_byte;
5535                 }
5536         }
5537         return can_write;
5538 }
5539
5540 gpointer
5541 mono_arch_get_vcall_slot (guint8 *code, gpointer *regs, int *displacement)
5542 {
5543         guint8 buf [10];
5544         guint32 reg;
5545         gint32 disp;
5546         guint8 rex = 0;
5547
5548         mono_breakpoint_clean_code (NULL, code, 9, buf, sizeof (buf));
5549         code = buf + 9;
5550
5551         *displacement = 0;
5552
5553         /* go to the start of the call instruction
5554          *
5555          * address_byte = (m << 6) | (o << 3) | reg
5556          * call opcode: 0xff address_byte displacement
5557          * 0xff m=1,o=2 imm8
5558          * 0xff m=2,o=2 imm32
5559          */
5560         code -= 7;
5561
5562         /* 
5563          * A given byte sequence can match more than case here, so we have to be
5564          * really careful about the ordering of the cases. Longer sequences
5565          * come first.
5566          */
5567 #ifdef MONO_ARCH_HAVE_IMT
5568         if ((code [-2] == 0x41) && (code [-1] == 0xbb) && (code [4] == 0xff) && (x86_modrm_mod (code [5]) == 1) && (x86_modrm_reg (code [5]) == 2) && ((signed char)code [6] < 0)) {
5569                 /* IMT-based interface calls: with MONO_ARCH_IMT_REG == r11
5570                  * 41 bb 14 f8 28 08       mov    $0x828f814,%r11d
5571                  * ff 50 fc                call   *0xfffffffc(%rax)
5572                  */
5573                 reg = amd64_modrm_rm (code [5]);
5574                 disp = (signed char)code [6];
5575                 /* R10 is clobbered by the IMT thunk code */
5576                 g_assert (reg != AMD64_R10);
5577         }
5578 #else
5579         if (0) {
5580         }
5581 #endif
5582         else if ((code [-1] == 0x8b) && (amd64_modrm_mod (code [0]) == 0x2) && (code [5] == 0xff) && (amd64_modrm_reg (code [6]) == 0x2) && (amd64_modrm_mod (code [6]) == 0x0)) {
5583                         /*
5584                          * This is a interface call
5585                          * 48 8b 80 f0 e8 ff ff   mov    0xffffffffffffe8f0(%rax),%rax
5586                          * ff 10                  callq  *(%rax)
5587                          */
5588                 if (IS_REX (code [4]))
5589                         rex = code [4];
5590                 reg = amd64_modrm_rm (code [6]);
5591                 disp = 0;
5592                 /* R10 is clobbered by the IMT thunk code */
5593                 g_assert (reg != AMD64_R10);
5594         } else if ((code [0] == 0x41) && (code [1] == 0xff) && (code [2] == 0x15)) {
5595                 /* call OFFSET(%rip) */
5596                 disp = *(guint32*)(code + 3);
5597                 return (gpointer*)(code + disp + 7);
5598         }
5599         else if ((code [1] == 0xff) && (amd64_modrm_reg (code [2]) == 0x2) && (amd64_modrm_mod (code [2]) == 0x2)) {
5600                 /* call *[reg+disp32] */
5601                 if (IS_REX (code [0]))
5602                         rex = code [0];
5603                 reg = amd64_modrm_rm (code [2]);
5604                 disp = *(gint32*)(code + 3);
5605                 /* R10 is clobbered by the IMT thunk code */
5606                 g_assert (reg != AMD64_R10);
5607         }
5608         else if (code [2] == 0xe8) {
5609                 /* call <ADDR> */
5610                 return NULL;
5611         }
5612         else if (IS_REX (code [4]) && (code [5] == 0xff) && (amd64_modrm_reg (code [6]) == 0x2) && (amd64_modrm_mod (code [6]) == 0x3)) {
5613                 /* call *%reg */
5614                 return NULL;
5615         }
5616         else if ((code [4] == 0xff) && (amd64_modrm_reg (code [5]) == 0x2) && (amd64_modrm_mod (code [5]) == 0x1)) {
5617                 /* call *[reg+disp8] */
5618                 if (IS_REX (code [3]))
5619                         rex = code [3];
5620                 reg = amd64_modrm_rm (code [5]);
5621                 disp = *(gint8*)(code + 6);
5622                 //printf ("B: [%%r%d+0x%x]\n", reg, disp);
5623         }
5624         else if ((code [5] == 0xff) && (amd64_modrm_reg (code [6]) == 0x2) && (amd64_modrm_mod (code [6]) == 0x0)) {
5625                         /*
5626                          * This is a interface call: should check the above code can't catch it earlier 
5627                          * 8b 40 30   mov    0x30(%eax),%eax
5628                          * ff 10      call   *(%eax)
5629                          */
5630                 if (IS_REX (code [4]))
5631                         rex = code [4];
5632                 reg = amd64_modrm_rm (code [6]);
5633                 disp = 0;
5634         }
5635         else
5636                 g_assert_not_reached ();
5637
5638         reg += amd64_rex_b (rex);
5639
5640         /* R11 is clobbered by the trampoline code */
5641         g_assert (reg != AMD64_R11);
5642
5643         *displacement = disp;
5644         return regs [reg];
5645 }
5646
5647 gpointer*
5648 mono_arch_get_vcall_slot_addr (guint8* code, gpointer *regs)
5649 {
5650         gpointer vt;
5651         int displacement;
5652         vt = mono_arch_get_vcall_slot (code, regs, &displacement);
5653         if (!vt)
5654                 return NULL;
5655         return (gpointer*)((char*)vt + displacement);
5656 }
5657
5658 int
5659 mono_arch_get_this_arg_reg (MonoMethodSignature *sig)
5660 {
5661         int this_reg = AMD64_ARG_REG1;
5662
5663         if (MONO_TYPE_ISSTRUCT (sig->ret)) {
5664                 CallInfo *cinfo = get_call_info (NULL, NULL, sig, FALSE);
5665                 
5666                 if (cinfo->ret.storage != ArgValuetypeInReg)
5667                         this_reg = AMD64_ARG_REG2;
5668                 g_free (cinfo);
5669         }
5670
5671         return this_reg;
5672 }
5673
5674 gpointer
5675 mono_arch_get_this_arg_from_call (MonoMethodSignature *sig, gssize *regs, guint8 *code)
5676 {
5677         return (gpointer)regs [mono_arch_get_this_arg_reg (sig)];
5678 }
5679
5680 #define MAX_ARCH_DELEGATE_PARAMS 10
5681
5682 gpointer
5683 mono_arch_get_delegate_invoke_impl (MonoMethodSignature *sig, gboolean has_target)
5684 {
5685         guint8 *code, *start;
5686         int i;
5687
5688         if (sig->param_count > MAX_ARCH_DELEGATE_PARAMS)
5689                 return NULL;
5690
5691         /* FIXME: Support more cases */
5692         if (MONO_TYPE_ISSTRUCT (sig->ret))
5693                 return NULL;
5694
5695         if (has_target) {
5696                 static guint8* cached = NULL;
5697                 mono_mini_arch_lock ();
5698                 if (cached) {
5699                         mono_mini_arch_unlock ();
5700                         return cached;
5701                 }
5702
5703                 start = code = mono_global_codeman_reserve (64);
5704
5705                 /* Replace the this argument with the target */
5706                 amd64_mov_reg_reg (code, AMD64_RAX, AMD64_ARG_REG1, 8);
5707                 amd64_mov_reg_membase (code, AMD64_ARG_REG1, AMD64_RAX, G_STRUCT_OFFSET (MonoDelegate, target), 8);
5708                 amd64_jump_membase (code, AMD64_RAX, G_STRUCT_OFFSET (MonoDelegate, method_ptr));
5709
5710                 g_assert ((code - start) < 64);
5711
5712                 cached = start;
5713                 mono_debug_add_delegate_trampoline (start, code - start);
5714                 mono_mini_arch_unlock ();
5715         } else {
5716                 static guint8* cache [MAX_ARCH_DELEGATE_PARAMS + 1] = {NULL};
5717                 for (i = 0; i < sig->param_count; ++i)
5718                         if (!mono_is_regsize_var (sig->params [i]))
5719                                 return NULL;
5720                 if (sig->param_count > 4)
5721                         return NULL;
5722
5723                 mono_mini_arch_lock ();
5724                 code = cache [sig->param_count];
5725                 if (code) {
5726                         mono_mini_arch_unlock ();
5727                         return code;
5728                 }
5729
5730                 start = code = mono_global_codeman_reserve (64);
5731
5732                 if (sig->param_count == 0) {
5733                         amd64_jump_membase (code, AMD64_ARG_REG1, G_STRUCT_OFFSET (MonoDelegate, method_ptr));
5734                 } else {
5735                         /* We have to shift the arguments left */
5736                         amd64_mov_reg_reg (code, AMD64_RAX, AMD64_ARG_REG1, 8);
5737                         for (i = 0; i < sig->param_count; ++i)
5738                                 amd64_mov_reg_reg (code, param_regs [i], param_regs [i + 1], 8);
5739
5740                         amd64_jump_membase (code, AMD64_RAX, G_STRUCT_OFFSET (MonoDelegate, method_ptr));
5741                 }
5742                 g_assert ((code - start) < 64);
5743
5744                 cache [sig->param_count] = start;
5745                 
5746                 mono_debug_add_delegate_trampoline (start, code - start);
5747                 mono_mini_arch_unlock ();
5748         }
5749
5750         return start;
5751 }
5752
5753 /*
5754  * Support for fast access to the thread-local lmf structure using the GS
5755  * segment register on NPTL + kernel 2.6.x.
5756  */
5757
5758 static gboolean tls_offset_inited = FALSE;
5759
5760 void
5761 mono_arch_setup_jit_tls_data (MonoJitTlsData *tls)
5762 {
5763         if (!tls_offset_inited) {
5764                 tls_offset_inited = TRUE;
5765 #ifdef MONO_XEN_OPT
5766                 optimize_for_xen = access ("/proc/xen", F_OK) == 0;
5767 #endif
5768                 appdomain_tls_offset = mono_domain_get_tls_offset ();
5769                 lmf_tls_offset = mono_get_lmf_tls_offset ();
5770                 lmf_addr_tls_offset = mono_get_lmf_addr_tls_offset ();
5771                 thread_tls_offset = mono_thread_get_tls_offset ();
5772         }               
5773 }
5774
5775 void
5776 mono_arch_free_jit_tls_data (MonoJitTlsData *tls)
5777 {
5778 }
5779
5780 void
5781 mono_arch_emit_this_vret_args (MonoCompile *cfg, MonoCallInst *inst, int this_reg, int this_type, int vt_reg)
5782 {
5783         MonoCallInst *call = (MonoCallInst*)inst;
5784         CallInfo * cinfo = get_call_info (cfg, cfg->mempool, inst->signature, FALSE);
5785
5786         if (vt_reg != -1) {
5787                 MonoInst *vtarg;
5788
5789                 if (cinfo->ret.storage == ArgValuetypeInReg) {
5790                         /*
5791                          * The valuetype is in RAX:RDX after the call, need to be copied to
5792                          * the stack. Push the address here, so the call instruction can
5793                          * access it.
5794                          */
5795                         MONO_INST_NEW (cfg, vtarg, OP_X86_PUSH);
5796                         vtarg->sreg1 = vt_reg;
5797                         mono_bblock_add_inst (cfg->cbb, vtarg);
5798
5799                         /* Align stack */
5800                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SUB_IMM, X86_ESP, X86_ESP, 8);
5801                 }
5802                 else {
5803                         MONO_INST_NEW (cfg, vtarg, OP_MOVE);
5804                         vtarg->sreg1 = vt_reg;
5805                         vtarg->dreg = mono_regstate_next_int (cfg->rs);
5806                         mono_bblock_add_inst (cfg->cbb, vtarg);
5807
5808                         mono_call_inst_add_outarg_reg (cfg, call, vtarg->dreg, cinfo->ret.reg, FALSE);
5809                 }
5810         }
5811
5812         /* add the this argument */
5813         if (this_reg != -1) {
5814                 MonoInst *this;
5815                 MONO_INST_NEW (cfg, this, OP_MOVE);
5816                 this->type = this_type;
5817                 this->sreg1 = this_reg;
5818                 this->dreg = mono_regstate_next_int (cfg->rs);
5819                 mono_bblock_add_inst (cfg->cbb, this);
5820
5821                 mono_call_inst_add_outarg_reg (cfg, call, this->dreg, cinfo->args [0].reg, FALSE);
5822         }
5823 }
5824
5825 #ifdef MONO_ARCH_HAVE_IMT
5826
5827 #define CMP_SIZE (6 + 1)
5828 #define CMP_REG_REG_SIZE (4 + 1)
5829 #define BR_SMALL_SIZE 2
5830 #define BR_LARGE_SIZE 6
5831 #define MOV_REG_IMM_SIZE 10
5832 #define MOV_REG_IMM_32BIT_SIZE 6
5833 #define JUMP_REG_SIZE (2 + 1)
5834
5835 static int
5836 imt_branch_distance (MonoIMTCheckItem **imt_entries, int start, int target)
5837 {
5838         int i, distance = 0;
5839         for (i = start; i < target; ++i)
5840                 distance += imt_entries [i]->chunk_size;
5841         return distance;
5842 }
5843
5844 /*
5845  * LOCKING: called with the domain lock held
5846  */
5847 gpointer
5848 mono_arch_build_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count)
5849 {
5850         int i;
5851         int size = 0;
5852         guint8 *code, *start;
5853         gboolean vtable_is_32bit = ((gsize)(vtable) == (gsize)(int)(gsize)(vtable));
5854
5855         for (i = 0; i < count; ++i) {
5856                 MonoIMTCheckItem *item = imt_entries [i];
5857                 if (item->is_equals) {
5858                         if (item->check_target_idx) {
5859                                 if (!item->compare_done) {
5860                                         if (amd64_is_imm32 (item->method))
5861                                                 item->chunk_size += CMP_SIZE;
5862                                         else
5863                                                 item->chunk_size += MOV_REG_IMM_SIZE + CMP_REG_REG_SIZE;
5864                                 }
5865                                 if (vtable_is_32bit)
5866                                         item->chunk_size += MOV_REG_IMM_32BIT_SIZE;
5867                                 else
5868                                         item->chunk_size += MOV_REG_IMM_SIZE;
5869                                 item->chunk_size += BR_SMALL_SIZE + JUMP_REG_SIZE;
5870                         } else {
5871                                 if (vtable_is_32bit)
5872                                         item->chunk_size += MOV_REG_IMM_32BIT_SIZE;
5873                                 else
5874                                         item->chunk_size += MOV_REG_IMM_SIZE;
5875                                 item->chunk_size += JUMP_REG_SIZE;
5876                                 /* with assert below:
5877                                  * item->chunk_size += CMP_SIZE + BR_SMALL_SIZE + 1;
5878                                  */
5879                         }
5880                 } else {
5881                         if (amd64_is_imm32 (item->method))
5882                                 item->chunk_size += CMP_SIZE;
5883                         else
5884                                 item->chunk_size += MOV_REG_IMM_SIZE + CMP_REG_REG_SIZE;
5885                         item->chunk_size += BR_LARGE_SIZE;
5886                         imt_entries [item->check_target_idx]->compare_done = TRUE;
5887                 }
5888                 size += item->chunk_size;
5889         }
5890         code = mono_code_manager_reserve (domain->code_mp, size);
5891         start = code;
5892         for (i = 0; i < count; ++i) {
5893                 MonoIMTCheckItem *item = imt_entries [i];
5894                 item->code_target = code;
5895                 if (item->is_equals) {
5896                         if (item->check_target_idx) {
5897                                 if (!item->compare_done) {
5898                                         if (amd64_is_imm32 (item->method))
5899                                                 amd64_alu_reg_imm (code, X86_CMP, MONO_ARCH_IMT_REG, (guint32)(gssize)item->method);
5900                                         else {
5901                                                 amd64_mov_reg_imm (code, AMD64_R10, item->method);
5902                                                 amd64_alu_reg_reg (code, X86_CMP, MONO_ARCH_IMT_REG, AMD64_R10);
5903                                         }
5904                                 }
5905                                 item->jmp_code = code;
5906                                 amd64_branch8 (code, X86_CC_NE, 0, FALSE);
5907                                 amd64_mov_reg_imm (code, AMD64_R11, & (vtable->vtable [item->vtable_slot]));
5908                                 amd64_jump_membase (code, AMD64_R11, 0);
5909                         } else {
5910                                 /* enable the commented code to assert on wrong method */
5911 #if 0
5912                                 if (amd64_is_imm32 (item->method))
5913                                         amd64_alu_reg_imm (code, X86_CMP, MONO_ARCH_IMT_REG, (guint32)(gssize)item->method);
5914                                 else {
5915                                         amd64_mov_reg_imm (code, AMD64_R10, item->method);
5916                                         amd64_alu_reg_reg (code, X86_CMP, MONO_ARCH_IMT_REG, AMD64_R10);
5917                                 }
5918                                 item->jmp_code = code;
5919                                 amd64_branch8 (code, X86_CC_NE, 0, FALSE);
5920                                 amd64_mov_reg_imm (code, AMD64_R11, & (vtable->vtable [item->vtable_slot]));
5921                                 amd64_jump_membase (code, AMD64_R11, 0);
5922                                 amd64_patch (item->jmp_code, code);
5923                                 amd64_breakpoint (code);
5924                                 item->jmp_code = NULL;
5925 #else
5926                                 amd64_mov_reg_imm (code, AMD64_R11, & (vtable->vtable [item->vtable_slot]));
5927                                 amd64_jump_membase (code, AMD64_R11, 0);
5928 #endif
5929                         }
5930                 } else {
5931                         if (amd64_is_imm32 (item->method))
5932                                 amd64_alu_reg_imm (code, X86_CMP, MONO_ARCH_IMT_REG, (guint32)(gssize)item->method);
5933                         else {
5934                                 amd64_mov_reg_imm (code, AMD64_R10, item->method);
5935                                 amd64_alu_reg_reg (code, X86_CMP, MONO_ARCH_IMT_REG, AMD64_R10);
5936                         }
5937                         item->jmp_code = code;
5938                         if (x86_is_imm8 (imt_branch_distance (imt_entries, i, item->check_target_idx)))
5939                                 x86_branch8 (code, X86_CC_GE, 0, FALSE);
5940                         else
5941                                 x86_branch32 (code, X86_CC_GE, 0, FALSE);
5942                 }
5943                 g_assert (code - item->code_target <= item->chunk_size);
5944         }
5945         /* patch the branches to get to the target items */
5946         for (i = 0; i < count; ++i) {
5947                 MonoIMTCheckItem *item = imt_entries [i];
5948                 if (item->jmp_code) {
5949                         if (item->check_target_idx) {
5950                                 amd64_patch (item->jmp_code, imt_entries [item->check_target_idx]->code_target);
5951                         }
5952                 }
5953         }
5954                 
5955         mono_stats.imt_thunks_size += code - start;
5956         g_assert (code - start <= size);
5957
5958         return start;
5959 }
5960
5961 MonoMethod*
5962 mono_arch_find_imt_method (gpointer *regs, guint8 *code)
5963 {
5964         /* 
5965          * R11 is clobbered by the trampoline code, so we have to retrieve the method 
5966          * from the code.
5967          * 41 bb c0 f7 89 00     mov    $0x89f7c0,%r11d
5968          * ff 90 68 ff ff ff     callq  *0xffffffffffffff68(%rax)
5969          */
5970         /* Similar to get_vcall_slot_addr () */
5971
5972         /* Find the start of the call instruction */
5973         code -= 7;
5974         if ((code [-2] == 0x41) && (code [-1] == 0xbb) && (code [4] == 0xff) && (x86_modrm_mod (code [5]) == 1) && (x86_modrm_reg (code [5]) == 2) && ((signed char)code [6] < 0)) {
5975                 /* IMT-based interface calls
5976                  * 41 bb 14 f8 28 08       mov    $0x828f814,%r11
5977                  * ff 50 fc                call   *0xfffffffc(%rax)
5978                  */
5979                 code += 4;
5980         } else if ((code [1] == 0xff) && (amd64_modrm_reg (code [2]) == 0x2) && (amd64_modrm_mod (code [2]) == 0x2)) {
5981                 /* call *[reg+disp32] */
5982                 code += 1;
5983         } else if ((code [4] == 0xff) && (amd64_modrm_reg (code [5]) == 0x2) && (amd64_modrm_mod (code [5]) == 0x1)) {
5984                 /* call *[reg+disp8] */
5985                 code += 4;
5986         } else
5987                 g_assert_not_reached ();
5988
5989         /* Find the start of the mov instruction */
5990         code -= 10;
5991         if (code [0] == 0x49 && code [1] == 0xbb) {
5992                 return (MonoMethod*)*(gssize*)(code + 2);
5993         } else if (code [3] == 0x4d && code [4] == 0x8b && code [5] == 0x1d) {
5994                 /* mov    <OFFSET>(%rip),%r11 */
5995                 return (MonoMethod*)*(gssize*)(code + 10 + *(guint32*)(code + 6));
5996         } else if (code [4] == 0x41 && code [5] == 0xbb) {
5997                 return (MonoMethod*)(gssize)*(guint32*)(code + 6);
5998         } else {
5999                 int i;
6000
6001                 printf ("Unknown call sequence: ");
6002                 for (i = -10; i < 20; ++i)
6003                         printf ("%x ", code [i]);
6004                 g_assert_not_reached ();
6005                 return NULL;
6006         }
6007 }
6008
6009 MonoObject*
6010 mono_arch_find_this_argument (gpointer *regs, MonoMethod *method, MonoGenericSharingContext *gsctx)
6011 {
6012         return mono_arch_get_this_arg_from_call (mono_method_signature (method), (gssize*)regs, NULL);
6013 }
6014 #endif
6015
6016 MonoRuntimeGenericContext*
6017 mono_arch_find_static_call_rgctx (gpointer *regs, guint8 *code)
6018 {
6019         return (MonoRuntimeGenericContext*) regs [MONO_ARCH_RGCTX_REG];
6020 }
6021
6022 MonoInst*
6023 mono_arch_get_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
6024 {
6025         MonoInst *ins = NULL;
6026
6027         if (cmethod->klass == mono_defaults.math_class) {
6028                 if (strcmp (cmethod->name, "Sin") == 0) {
6029                         MONO_INST_NEW (cfg, ins, OP_SIN);
6030                         ins->inst_i0 = args [0];
6031                 } else if (strcmp (cmethod->name, "Cos") == 0) {
6032                         MONO_INST_NEW (cfg, ins, OP_COS);
6033                         ins->inst_i0 = args [0];
6034                 } else if (strcmp (cmethod->name, "Tan") == 0) {
6035                         if (use_sse2)
6036                                 return ins;
6037                         MONO_INST_NEW (cfg, ins, OP_TAN);
6038                         ins->inst_i0 = args [0];
6039                 } else if (strcmp (cmethod->name, "Atan") == 0) {
6040                         if (use_sse2)
6041                                 return ins;
6042                         MONO_INST_NEW (cfg, ins, OP_ATAN);
6043                         ins->inst_i0 = args [0];
6044                 } else if (strcmp (cmethod->name, "Sqrt") == 0) {
6045                         MONO_INST_NEW (cfg, ins, OP_SQRT);
6046                         ins->inst_i0 = args [0];
6047                 } else if (strcmp (cmethod->name, "Abs") == 0 && fsig->params [0]->type == MONO_TYPE_R8) {
6048                         MONO_INST_NEW (cfg, ins, OP_ABS);
6049                         ins->inst_i0 = args [0];
6050                 }
6051
6052                 if (cfg->opt & MONO_OPT_CMOV) {
6053                         int opcode = 0;
6054
6055                         if (strcmp (cmethod->name, "Min") == 0) {
6056                                 if (fsig->params [0]->type == MONO_TYPE_I4)
6057                                         opcode = OP_IMIN;
6058                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
6059                                         opcode = OP_LMIN;
6060                         } else if (strcmp (cmethod->name, "Max") == 0) {
6061                                 if (fsig->params [0]->type == MONO_TYPE_I4)
6062                                         opcode = OP_IMAX;
6063                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
6064                                         opcode = OP_LMAX;
6065                         }               
6066
6067                         if (opcode) {
6068                                 MONO_INST_NEW (cfg, ins, opcode);
6069                                 ins->inst_i0 = args [0];
6070                                 ins->inst_i1 = args [1];
6071                         }
6072                 }
6073
6074 #if 0
6075                 /* OP_FREM is not IEEE compatible */
6076                 else if (strcmp (cmethod->name, "IEEERemainder") == 0) {
6077                         MONO_INST_NEW (cfg, ins, OP_FREM);
6078                         ins->inst_i0 = args [0];
6079                         ins->inst_i1 = args [1];
6080                 }
6081 #endif
6082         } else if(cmethod->klass->image == mono_defaults.corlib &&
6083                            (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
6084                            (strcmp (cmethod->klass->name, "Interlocked") == 0)) {
6085                 /* 
6086                  * Can't implement CompareExchange methods this way since they have
6087                  * three arguments.
6088                  */
6089         }
6090
6091         return ins;
6092 }
6093
6094 gboolean
6095 mono_arch_print_tree (MonoInst *tree, int arity)
6096 {
6097         return 0;
6098 }
6099
6100 MonoInst* mono_arch_get_domain_intrinsic (MonoCompile* cfg)
6101 {
6102         MonoInst* ins;
6103         
6104         if (appdomain_tls_offset == -1)
6105                 return NULL;
6106         
6107         MONO_INST_NEW (cfg, ins, OP_TLS_GET);
6108         ins->inst_offset = appdomain_tls_offset;
6109         return ins;
6110 }
6111
6112 MonoInst* mono_arch_get_thread_intrinsic (MonoCompile* cfg)
6113 {
6114         MonoInst* ins;
6115         
6116         if (thread_tls_offset == -1)
6117                 return NULL;
6118         
6119         MONO_INST_NEW (cfg, ins, OP_TLS_GET);
6120         ins->inst_offset = thread_tls_offset;
6121         return ins;
6122 }
6123
6124 #define _CTX_REG(ctx,fld,i) ((gpointer)((&ctx->fld)[i]))
6125
6126 gpointer
6127 mono_arch_context_get_int_reg (MonoContext *ctx, int reg)
6128 {
6129         switch (reg) {
6130         case AMD64_RCX: return (gpointer)ctx->rcx;
6131         case AMD64_RDX: return (gpointer)ctx->rdx;
6132         case AMD64_RBX: return (gpointer)ctx->rbx;
6133         case AMD64_RBP: return (gpointer)ctx->rbp;
6134         case AMD64_RSP: return (gpointer)ctx->rsp;
6135         default:
6136                 if (reg < 8)
6137                         return _CTX_REG (ctx, rax, reg);
6138                 else if (reg >= 12)
6139                         return _CTX_REG (ctx, r12, reg - 12);
6140                 else
6141                         g_assert_not_reached ();
6142         }
6143 }