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