System.Drawing: added email to icon and test file headers
[mono.git] / mono / mini / mini-amd64.c
1 /*
2  * mini-amd64.c: AMD64 backend for the Mono code generator
3  *
4  * Based on mini-x86.c.
5  *
6  * Authors:
7  *   Paolo Molaro (lupus@ximian.com)
8  *   Dietmar Maurer (dietmar@ximian.com)
9  *   Patrik Torstensson
10  *   Zoltan Varga (vargaz@gmail.com)
11  *
12  * (C) 2003 Ximian, Inc.
13  * Copyright 2003-2011 Novell, Inc (http://www.novell.com)
14  * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
15  */
16 #include "mini.h"
17 #include <string.h>
18 #include <math.h>
19 #ifdef HAVE_UNISTD_H
20 #include <unistd.h>
21 #endif
22
23 #include <mono/metadata/appdomain.h>
24 #include <mono/metadata/debug-helpers.h>
25 #include <mono/metadata/threads.h>
26 #include <mono/metadata/profiler-private.h>
27 #include <mono/metadata/mono-debug.h>
28 #include <mono/metadata/gc-internal.h>
29 #include <mono/utils/mono-math.h>
30 #include <mono/utils/mono-mmap.h>
31 #include <mono/utils/mono-memory-model.h>
32 #include <mono/utils/mono-tls.h>
33
34 #include "trace.h"
35 #include "ir-emit.h"
36 #include "mini-amd64.h"
37 #include "cpu-amd64.h"
38 #include "debugger-agent.h"
39 #include "mini-gc.h"
40
41 static gint lmf_tls_offset = -1;
42 static gint lmf_addr_tls_offset = -1;
43 static gint appdomain_tls_offset = -1;
44
45 #ifdef MONO_XEN_OPT
46 static gboolean optimize_for_xen = TRUE;
47 #else
48 #define optimize_for_xen 0
49 #endif
50
51 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
52
53 #define IS_IMM32(val) ((((guint64)val) >> 32) == 0)
54
55 #define IS_REX(inst) (((inst) >= 0x40) && ((inst) <= 0x4f))
56
57 #ifdef HOST_WIN32
58 /* Under windows, the calling convention is never stdcall */
59 #define CALLCONV_IS_STDCALL(call_conv) (FALSE)
60 #else
61 #define CALLCONV_IS_STDCALL(call_conv) ((call_conv) == MONO_CALL_STDCALL)
62 #endif
63
64 /* This mutex protects architecture specific caches */
65 #define mono_mini_arch_lock() EnterCriticalSection (&mini_arch_mutex)
66 #define mono_mini_arch_unlock() LeaveCriticalSection (&mini_arch_mutex)
67 static CRITICAL_SECTION mini_arch_mutex;
68
69 MonoBreakpointInfo
70 mono_breakpoint_info [MONO_BREAKPOINT_ARRAY_SIZE];
71
72 /* Structure used by the sequence points in AOTed code */
73 typedef struct {
74         gpointer ss_trigger_page;
75         gpointer bp_trigger_page;
76         gpointer bp_addrs [MONO_ZERO_LEN_ARRAY];
77 } SeqPointInfo;
78
79 /*
80  * The code generated for sequence points reads from this location, which is
81  * made read-only when single stepping is enabled.
82  */
83 static gpointer ss_trigger_page;
84
85 /* Enabled breakpoints read from this trigger page */
86 static gpointer bp_trigger_page;
87
88 /* The size of the breakpoint sequence */
89 static int breakpoint_size;
90
91 /* The size of the breakpoint instruction causing the actual fault */
92 static int breakpoint_fault_size;
93
94 /* The size of the single step instruction causing the actual fault */
95 static int single_step_fault_size;
96
97 #ifdef HOST_WIN32
98 /* On Win64 always reserve first 32 bytes for first four arguments */
99 #define ARGS_OFFSET 48
100 #else
101 #define ARGS_OFFSET 16
102 #endif
103 #define GP_SCRATCH_REG AMD64_R11
104
105 /*
106  * AMD64 register usage:
107  * - callee saved registers are used for global register allocation
108  * - %r11 is used for materializing 64 bit constants in opcodes
109  * - the rest is used for local allocation
110  */
111
112 /*
113  * Floating point comparison results:
114  *                  ZF PF CF
115  * A > B            0  0  0
116  * A < B            0  0  1
117  * A = B            1  0  0
118  * A > B            0  0  0
119  * UNORDERED        1  1  1
120  */
121
122 const char*
123 mono_arch_regname (int reg)
124 {
125         switch (reg) {
126         case AMD64_RAX: return "%rax";
127         case AMD64_RBX: return "%rbx";
128         case AMD64_RCX: return "%rcx";
129         case AMD64_RDX: return "%rdx";
130         case AMD64_RSP: return "%rsp";  
131         case AMD64_RBP: return "%rbp";
132         case AMD64_RDI: return "%rdi";
133         case AMD64_RSI: return "%rsi";
134         case AMD64_R8: return "%r8";
135         case AMD64_R9: return "%r9";
136         case AMD64_R10: return "%r10";
137         case AMD64_R11: return "%r11";
138         case AMD64_R12: return "%r12";
139         case AMD64_R13: return "%r13";
140         case AMD64_R14: return "%r14";
141         case AMD64_R15: return "%r15";
142         }
143         return "unknown";
144 }
145
146 static const char * packed_xmmregs [] = {
147         "p:xmm0", "p:xmm1", "p:xmm2", "p:xmm3", "p:xmm4", "p:xmm5", "p:xmm6", "p:xmm7", "p:xmm8",
148         "p:xmm9", "p:xmm10", "p:xmm11", "p:xmm12", "p:xmm13", "p:xmm14", "p:xmm15"
149 };
150
151 static const char * single_xmmregs [] = {
152         "s:xmm0", "s:xmm1", "s:xmm2", "s:xmm3", "s:xmm4", "s:xmm5", "s:xmm6", "s:xmm7", "s:xmm8",
153         "s:xmm9", "s:xmm10", "s:xmm11", "s:xmm12", "s:xmm13", "s:xmm14", "s:xmm15"
154 };
155
156 const char*
157 mono_arch_fregname (int reg)
158 {
159         if (reg < AMD64_XMM_NREG)
160                 return single_xmmregs [reg];
161         else
162                 return "unknown";
163 }
164
165 const char *
166 mono_arch_xregname (int reg)
167 {
168         if (reg < AMD64_XMM_NREG)
169                 return packed_xmmregs [reg];
170         else
171                 return "unknown";
172 }
173
174 G_GNUC_UNUSED static void
175 break_count (void)
176 {
177 }
178
179 G_GNUC_UNUSED static gboolean
180 debug_count (void)
181 {
182         static int count = 0;
183         count ++;
184
185         if (!getenv ("COUNT"))
186                 return TRUE;
187
188         if (count == atoi (getenv ("COUNT"))) {
189                 break_count ();
190         }
191
192         if (count > atoi (getenv ("COUNT"))) {
193                 return FALSE;
194         }
195
196         return TRUE;
197 }
198
199 static gboolean
200 debug_omit_fp (void)
201 {
202 #if 0
203         return debug_count ();
204 #else
205         return TRUE;
206 #endif
207 }
208
209 static inline gboolean
210 amd64_is_near_call (guint8 *code)
211 {
212         /* Skip REX */
213         if ((code [0] >= 0x40) && (code [0] <= 0x4f))
214                 code += 1;
215
216         return code [0] == 0xe8;
217 }
218
219 #ifdef __native_client_codegen__
220
221 /* Keep track of instruction "depth", that is, the level of sub-instruction */
222 /* for any given instruction.  For instance, amd64_call_reg resolves to     */
223 /* amd64_call_reg_internal, which uses amd64_alu_* macros, etc.             */
224 /* We only want to force bundle alignment for the top level instruction,    */
225 /* so NaCl pseudo-instructions can be implemented with sub instructions.    */
226 static MonoNativeTlsKey nacl_instruction_depth;
227
228 static MonoNativeTlsKey nacl_rex_tag;
229 static MonoNativeTlsKey nacl_legacy_prefix_tag;
230
231 void
232 amd64_nacl_clear_legacy_prefix_tag ()
233 {
234         mono_native_tls_set_value (nacl_legacy_prefix_tag, NULL);
235 }
236
237 void
238 amd64_nacl_tag_legacy_prefix (guint8* code)
239 {
240         if (mono_native_tls_get_value (nacl_legacy_prefix_tag) == NULL)
241                 mono_native_tls_set_value (nacl_legacy_prefix_tag, code);
242 }
243
244 void
245 amd64_nacl_tag_rex (guint8* code)
246 {
247         mono_native_tls_set_value (nacl_rex_tag, code);
248 }
249
250 guint8*
251 amd64_nacl_get_legacy_prefix_tag ()
252 {
253         return (guint8*)mono_native_tls_get_value (nacl_legacy_prefix_tag);
254 }
255
256 guint8*
257 amd64_nacl_get_rex_tag ()
258 {
259         return (guint8*)mono_native_tls_get_value (nacl_rex_tag);
260 }
261
262 /* Increment the instruction "depth" described above */
263 void
264 amd64_nacl_instruction_pre ()
265 {
266         intptr_t depth = (intptr_t) mono_native_tls_get_value (nacl_instruction_depth);
267         depth++;
268         mono_native_tls_set_value (nacl_instruction_depth, (gpointer)depth);
269 }
270
271 /* amd64_nacl_instruction_post: Decrement instruction "depth", force bundle */
272 /* alignment if depth == 0 (top level instruction)                          */
273 /* IN: start, end    pointers to instruction beginning and end              */
274 /* OUT: start, end   pointers to beginning and end after possible alignment */
275 /* GLOBALS: nacl_instruction_depth     defined above                        */
276 void
277 amd64_nacl_instruction_post (guint8 **start, guint8 **end)
278 {
279         intptr_t depth = (intptr_t) mono_native_tls_get_value (nacl_instruction_depth);
280         depth--;
281         mono_native_tls_set_value (nacl_instruction_depth, (void*)depth);
282
283         g_assert ( depth >= 0 );
284         if (depth == 0) {
285                 uintptr_t space_in_block;
286                 uintptr_t instlen;
287                 guint8 *prefix = amd64_nacl_get_legacy_prefix_tag ();
288                 /* if legacy prefix is present, and if it was emitted before */
289                 /* the start of the instruction sequence, adjust the start   */
290                 if (prefix != NULL && prefix < *start) {
291                         g_assert (*start - prefix <= 3);/* only 3 are allowed */
292                         *start = prefix;
293                 }
294                 space_in_block = kNaClAlignment - ((uintptr_t)(*start) & kNaClAlignmentMask);
295                 instlen = (uintptr_t)(*end - *start);
296                 /* Only check for instructions which are less than        */
297                 /* kNaClAlignment. The only instructions that should ever */
298                 /* be that long are call sequences, which are already     */
299                 /* padded out to align the return to the next bundle.     */
300                 if (instlen > space_in_block && instlen < kNaClAlignment) {
301                         const size_t MAX_NACL_INST_LENGTH = kNaClAlignment;
302                         guint8 copy_of_instruction[MAX_NACL_INST_LENGTH];
303                         const size_t length = (size_t)((*end)-(*start));
304                         g_assert (length < MAX_NACL_INST_LENGTH);
305                         
306                         memcpy (copy_of_instruction, *start, length);
307                         *start = mono_arch_nacl_pad (*start, space_in_block);
308                         memcpy (*start, copy_of_instruction, length);
309                         *end = *start + length;
310                 }
311                 amd64_nacl_clear_legacy_prefix_tag ();
312                 amd64_nacl_tag_rex (NULL);
313         }
314 }
315
316 /* amd64_nacl_membase_handler: ensure all access to memory of the form      */
317 /*   OFFSET(%rXX) is sandboxed.  For allowable base registers %rip, %rbp,   */
318 /*   %rsp, and %r15, emit the membase as usual.  For all other registers,   */
319 /*   make sure the upper 32-bits are cleared, and use that register in the  */
320 /*   index field of a new address of this form: OFFSET(%r15,%eXX,1)         */
321 /* IN:      code                                                            */
322 /*             pointer to current instruction stream (in the                */
323 /*             middle of an instruction, after opcode is emitted)           */
324 /*          basereg/offset/dreg                                             */
325 /*             operands of normal membase address                           */
326 /* OUT:     code                                                            */
327 /*             pointer to the end of the membase/memindex emit              */
328 /* GLOBALS: nacl_rex_tag                                                    */
329 /*             position in instruction stream that rex prefix was emitted   */
330 /*          nacl_legacy_prefix_tag                                          */
331 /*             (possibly NULL) position in instruction of legacy x86 prefix */
332 void
333 amd64_nacl_membase_handler (guint8** code, gint8 basereg, gint32 offset, gint8 dreg)
334 {
335         gint8 true_basereg = basereg;
336
337         /* Cache these values, they might change  */
338         /* as new instructions are emitted below. */
339         guint8* rex_tag = amd64_nacl_get_rex_tag ();
340         guint8* legacy_prefix_tag = amd64_nacl_get_legacy_prefix_tag ();
341
342         /* 'basereg' is given masked to 0x7 at this point, so check */
343         /* the rex prefix to see if this is an extended register.   */
344         if ((rex_tag != NULL) && IS_REX(*rex_tag) && (*rex_tag & AMD64_REX_B)) {
345                 true_basereg |= 0x8;
346         }
347
348 #define X86_LEA_OPCODE (0x8D)
349
350         if (!amd64_is_valid_nacl_base (true_basereg) && (*(*code-1) != X86_LEA_OPCODE)) {
351                 guint8* old_instruction_start;
352                 
353                 /* This will hold the 'mov %eXX, %eXX' that clears the upper */
354                 /* 32-bits of the old base register (new index register)     */
355                 guint8 buf[32];
356                 guint8* buf_ptr = buf;
357                 size_t insert_len;
358
359                 g_assert (rex_tag != NULL);
360
361                 if (IS_REX(*rex_tag)) {
362                         /* The old rex.B should be the new rex.X */
363                         if (*rex_tag & AMD64_REX_B) {
364                                 *rex_tag |= AMD64_REX_X;
365                         }
366                         /* Since our new base is %r15 set rex.B */
367                         *rex_tag |= AMD64_REX_B;
368                 } else {
369                         /* Shift the instruction by one byte  */
370                         /* so we can insert a rex prefix      */
371                         memmove (rex_tag + 1, rex_tag, (size_t)(*code - rex_tag));
372                         *code += 1;
373                         /* New rex prefix only needs rex.B for %r15 base */
374                         *rex_tag = AMD64_REX(AMD64_REX_B);
375                 }
376
377                 if (legacy_prefix_tag) {
378                         old_instruction_start = legacy_prefix_tag;
379                 } else {
380                         old_instruction_start = rex_tag;
381                 }
382                 
383                 /* Clears the upper 32-bits of the previous base register */
384                 amd64_mov_reg_reg_size (buf_ptr, true_basereg, true_basereg, 4);
385                 insert_len = buf_ptr - buf;
386                 
387                 /* Move the old instruction forward to make */
388                 /* room for 'mov' stored in 'buf_ptr'       */
389                 memmove (old_instruction_start + insert_len, old_instruction_start, (size_t)(*code - old_instruction_start));
390                 *code += insert_len;
391                 memcpy (old_instruction_start, buf, insert_len);
392
393                 /* Sandboxed replacement for the normal membase_emit */
394                 x86_memindex_emit (*code, dreg, AMD64_R15, offset, basereg, 0);
395                 
396         } else {
397                 /* Normal default behavior, emit membase memory location */
398                 x86_membase_emit_body (*code, dreg, basereg, offset);
399         }
400 }
401
402
403 static inline unsigned char*
404 amd64_skip_nops (unsigned char* code)
405 {
406         guint8 in_nop;
407         do {
408                 in_nop = 0;
409                 if (   code[0] == 0x90) {
410                         in_nop = 1;
411                         code += 1;
412                 }
413                 if (   code[0] == 0x66 && code[1] == 0x90) {
414                         in_nop = 1;
415                         code += 2;
416                 }
417                 if (code[0] == 0x0f && code[1] == 0x1f
418                  && code[2] == 0x00) {
419                         in_nop = 1;
420                         code += 3;
421                 }
422                 if (code[0] == 0x0f && code[1] == 0x1f
423                  && code[2] == 0x40 && code[3] == 0x00) {
424                         in_nop = 1;
425                         code += 4;
426                 }
427                 if (code[0] == 0x0f && code[1] == 0x1f
428                  && code[2] == 0x44 && code[3] == 0x00
429                  && code[4] == 0x00) {
430                         in_nop = 1;
431                         code += 5;
432                 }
433                 if (code[0] == 0x66 && code[1] == 0x0f
434                  && code[2] == 0x1f && code[3] == 0x44
435                  && code[4] == 0x00 && code[5] == 0x00) {
436                         in_nop = 1;
437                         code += 6;
438                 }
439                 if (code[0] == 0x0f && code[1] == 0x1f
440                  && code[2] == 0x80 && code[3] == 0x00
441                  && code[4] == 0x00 && code[5] == 0x00
442                  && code[6] == 0x00) {
443                         in_nop = 1;
444                         code += 7;
445                 }
446                 if (code[0] == 0x0f && code[1] == 0x1f
447                  && code[2] == 0x84 && code[3] == 0x00
448                  && code[4] == 0x00 && code[5] == 0x00
449                  && code[6] == 0x00 && code[7] == 0x00) {
450                         in_nop = 1;
451                         code += 8;
452                 }
453         } while ( in_nop );
454         return code;
455 }
456
457 guint8*
458 mono_arch_nacl_skip_nops (guint8* code)
459 {
460   return amd64_skip_nops(code);
461 }
462
463 #endif /*__native_client_codegen__*/
464
465 static inline void 
466 amd64_patch (unsigned char* code, gpointer target)
467 {
468         guint8 rex = 0;
469
470 #ifdef __native_client_codegen__
471         code = amd64_skip_nops (code);
472 #endif
473 #if defined(__native_client_codegen__) && defined(__native_client__)
474         if (nacl_is_code_address (code)) {
475                 /* For tail calls, code is patched after being installed */
476                 /* but not through the normal "patch callsite" method.   */
477                 unsigned char buf[kNaClAlignment];
478                 unsigned char *aligned_code = (uintptr_t)code & ~kNaClAlignmentMask;
479                 int ret;
480                 memcpy (buf, aligned_code, kNaClAlignment);
481                 /* Patch a temp buffer of bundle size, */
482                 /* then install to actual location.    */
483                 amd64_patch (buf + ((uintptr_t)code - (uintptr_t)aligned_code), target);
484                 ret = nacl_dyncode_modify (aligned_code, buf, kNaClAlignment);
485                 g_assert (ret == 0);
486                 return;
487         }
488         target = nacl_modify_patch_target (target);
489 #endif
490
491         /* Skip REX */
492         if ((code [0] >= 0x40) && (code [0] <= 0x4f)) {
493                 rex = code [0];
494                 code += 1;
495         }
496
497         if ((code [0] & 0xf8) == 0xb8) {
498                 /* amd64_set_reg_template */
499                 *(guint64*)(code + 1) = (guint64)target;
500         }
501         else if ((code [0] == 0x8b) && rex && x86_modrm_mod (code [1]) == 0 && x86_modrm_rm (code [1]) == 5) {
502                 /* mov 0(%rip), %dreg */
503                 *(guint32*)(code + 2) = (guint32)(guint64)target - 7;
504         }
505         else if ((code [0] == 0xff) && (code [1] == 0x15)) {
506                 /* call *<OFFSET>(%rip) */
507                 *(guint32*)(code + 2) = ((guint32)(guint64)target) - 7;
508         }
509         else if (code [0] == 0xe8) {
510                 /* call <DISP> */
511                 gint64 disp = (guint8*)target - (guint8*)code;
512                 g_assert (amd64_is_imm32 (disp));
513                 x86_patch (code, (unsigned char*)target);
514         }
515         else
516                 x86_patch (code, (unsigned char*)target);
517 }
518
519 void 
520 mono_amd64_patch (unsigned char* code, gpointer target)
521 {
522         amd64_patch (code, target);
523 }
524
525 typedef enum {
526         ArgInIReg,
527         ArgInFloatSSEReg,
528         ArgInDoubleSSEReg,
529         ArgOnStack,
530         ArgValuetypeInReg,
531         ArgValuetypeAddrInIReg,
532         ArgNone /* only in pair_storage */
533 } ArgStorage;
534
535 typedef struct {
536         gint16 offset;
537         gint8  reg;
538         ArgStorage storage;
539
540         /* Only if storage == ArgValuetypeInReg */
541         ArgStorage pair_storage [2];
542         gint8 pair_regs [2];
543         int nregs;
544 } ArgInfo;
545
546 typedef struct {
547         int nargs;
548         guint32 stack_usage;
549         guint32 reg_usage;
550         guint32 freg_usage;
551         gboolean need_stack_align;
552         gboolean vtype_retaddr;
553         /* The index of the vret arg in the argument list */
554         int vret_arg_index;
555         ArgInfo ret;
556         ArgInfo sig_cookie;
557         ArgInfo args [1];
558 } CallInfo;
559
560 #define DEBUG(a) if (cfg->verbose_level > 1) a
561
562 #ifdef HOST_WIN32
563 #define PARAM_REGS 4
564
565 static AMD64_Reg_No param_regs [] = { AMD64_RCX, AMD64_RDX, AMD64_R8, AMD64_R9 };
566
567 static AMD64_Reg_No return_regs [] = { AMD64_RAX, AMD64_RDX };
568 #else
569 #define PARAM_REGS 6
570  
571 static AMD64_Reg_No param_regs [] = { AMD64_RDI, AMD64_RSI, AMD64_RDX, AMD64_RCX, AMD64_R8, AMD64_R9 };
572
573  static AMD64_Reg_No return_regs [] = { AMD64_RAX, AMD64_RDX };
574 #endif
575
576 static void inline
577 add_general (guint32 *gr, guint32 *stack_size, ArgInfo *ainfo)
578 {
579     ainfo->offset = *stack_size;
580
581     if (*gr >= PARAM_REGS) {
582                 ainfo->storage = ArgOnStack;
583                 /* Since the same stack slot size is used for all arg */
584                 /*  types, it needs to be big enough to hold them all */
585                 (*stack_size) += sizeof(mgreg_t);
586     }
587     else {
588                 ainfo->storage = ArgInIReg;
589                 ainfo->reg = param_regs [*gr];
590                 (*gr) ++;
591     }
592 }
593
594 #ifdef HOST_WIN32
595 #define FLOAT_PARAM_REGS 4
596 #else
597 #define FLOAT_PARAM_REGS 8
598 #endif
599
600 static void inline
601 add_float (guint32 *gr, guint32 *stack_size, ArgInfo *ainfo, gboolean is_double)
602 {
603     ainfo->offset = *stack_size;
604
605     if (*gr >= FLOAT_PARAM_REGS) {
606                 ainfo->storage = ArgOnStack;
607                 /* Since the same stack slot size is used for both float */
608                 /*  types, it needs to be big enough to hold them both */
609                 (*stack_size) += sizeof(mgreg_t);
610     }
611     else {
612                 /* A double register */
613                 if (is_double)
614                         ainfo->storage = ArgInDoubleSSEReg;
615                 else
616                         ainfo->storage = ArgInFloatSSEReg;
617                 ainfo->reg = *gr;
618                 (*gr) += 1;
619     }
620 }
621
622 typedef enum ArgumentClass {
623         ARG_CLASS_NO_CLASS,
624         ARG_CLASS_MEMORY,
625         ARG_CLASS_INTEGER,
626         ARG_CLASS_SSE
627 } ArgumentClass;
628
629 static ArgumentClass
630 merge_argument_class_from_type (MonoType *type, ArgumentClass class1)
631 {
632         ArgumentClass class2 = ARG_CLASS_NO_CLASS;
633         MonoType *ptype;
634
635         ptype = mini_type_get_underlying_type (NULL, type);
636         switch (ptype->type) {
637         case MONO_TYPE_BOOLEAN:
638         case MONO_TYPE_CHAR:
639         case MONO_TYPE_I1:
640         case MONO_TYPE_U1:
641         case MONO_TYPE_I2:
642         case MONO_TYPE_U2:
643         case MONO_TYPE_I4:
644         case MONO_TYPE_U4:
645         case MONO_TYPE_I:
646         case MONO_TYPE_U:
647         case MONO_TYPE_STRING:
648         case MONO_TYPE_OBJECT:
649         case MONO_TYPE_CLASS:
650         case MONO_TYPE_SZARRAY:
651         case MONO_TYPE_PTR:
652         case MONO_TYPE_FNPTR:
653         case MONO_TYPE_ARRAY:
654         case MONO_TYPE_I8:
655         case MONO_TYPE_U8:
656                 class2 = ARG_CLASS_INTEGER;
657                 break;
658         case MONO_TYPE_R4:
659         case MONO_TYPE_R8:
660 #ifdef HOST_WIN32
661                 class2 = ARG_CLASS_INTEGER;
662 #else
663                 class2 = ARG_CLASS_SSE;
664 #endif
665                 break;
666
667         case MONO_TYPE_TYPEDBYREF:
668                 g_assert_not_reached ();
669
670         case MONO_TYPE_GENERICINST:
671                 if (!mono_type_generic_inst_is_valuetype (ptype)) {
672                         class2 = ARG_CLASS_INTEGER;
673                         break;
674                 }
675                 /* fall through */
676         case MONO_TYPE_VALUETYPE: {
677                 MonoMarshalType *info = mono_marshal_load_type_info (ptype->data.klass);
678                 int i;
679
680                 for (i = 0; i < info->num_fields; ++i) {
681                         class2 = class1;
682                         class2 = merge_argument_class_from_type (info->fields [i].field->type, class2);
683                 }
684                 break;
685         }
686         default:
687                 g_assert_not_reached ();
688         }
689
690         /* Merge */
691         if (class1 == class2)
692                 ;
693         else if (class1 == ARG_CLASS_NO_CLASS)
694                 class1 = class2;
695         else if ((class1 == ARG_CLASS_MEMORY) || (class2 == ARG_CLASS_MEMORY))
696                 class1 = ARG_CLASS_MEMORY;
697         else if ((class1 == ARG_CLASS_INTEGER) || (class2 == ARG_CLASS_INTEGER))
698                 class1 = ARG_CLASS_INTEGER;
699         else
700                 class1 = ARG_CLASS_SSE;
701
702         return class1;
703 }
704 #ifdef __native_client_codegen__
705 const guint kNaClAlignment = kNaClAlignmentAMD64;
706 const guint kNaClAlignmentMask = kNaClAlignmentMaskAMD64;
707
708 /* Default alignment for Native Client is 32-byte. */
709 gint8 nacl_align_byte = -32; /* signed version of 0xe0 */
710
711 /* mono_arch_nacl_pad: Add pad bytes of alignment instructions at code,  */
712 /* Check that alignment doesn't cross an alignment boundary.             */
713 guint8*
714 mono_arch_nacl_pad(guint8 *code, int pad)
715 {
716         const int kMaxPadding = 8; /* see amd64-codegen.h:amd64_padding_size() */
717
718         if (pad == 0) return code;
719         /* assertion: alignment cannot cross a block boundary */
720         g_assert (((uintptr_t)code & (~kNaClAlignmentMask)) ==
721                  (((uintptr_t)code + pad - 1) & (~kNaClAlignmentMask)));
722         while (pad >= kMaxPadding) {
723                 amd64_padding (code, kMaxPadding);
724                 pad -= kMaxPadding;
725         }
726         if (pad != 0) amd64_padding (code, pad);
727         return code;
728 }
729 #endif
730
731 static void
732 add_valuetype (MonoGenericSharingContext *gsctx, MonoMethodSignature *sig, ArgInfo *ainfo, MonoType *type,
733                            gboolean is_return,
734                            guint32 *gr, guint32 *fr, guint32 *stack_size)
735 {
736         guint32 size, quad, nquads, i;
737         /* Keep track of the size used in each quad so we can */
738         /* use the right size when copying args/return vars.  */
739         guint32 quadsize [2] = {8, 8};
740         ArgumentClass args [2];
741         MonoMarshalType *info = NULL;
742         MonoClass *klass;
743         MonoGenericSharingContext tmp_gsctx;
744         gboolean pass_on_stack = FALSE;
745         
746         /* 
747          * The gsctx currently contains no data, it is only used for checking whenever
748          * open types are allowed, some callers like mono_arch_get_argument_info ()
749          * don't pass it to us, so work around that.
750          */
751         if (!gsctx)
752                 gsctx = &tmp_gsctx;
753
754         klass = mono_class_from_mono_type (type);
755         size = mini_type_stack_size_full (gsctx, &klass->byval_arg, NULL, sig->pinvoke);
756 #ifndef HOST_WIN32
757         if (!sig->pinvoke && !disable_vtypes_in_regs && ((is_return && (size == 8)) || (!is_return && (size <= 16)))) {
758                 /* We pass and return vtypes of size 8 in a register */
759         } else if (!sig->pinvoke || (size == 0) || (size > 16)) {
760                 pass_on_stack = TRUE;
761         }
762 #else
763         if (!sig->pinvoke) {
764                 pass_on_stack = TRUE;
765         }
766 #endif
767
768         /* If this struct can't be split up naturally into 8-byte */
769         /* chunks (registers), pass it on the stack.              */
770         if (sig->pinvoke && !pass_on_stack) {
771                 guint32 align;
772                 guint32 field_size;
773
774                 info = mono_marshal_load_type_info (klass);
775                 g_assert(info);
776                 for (i = 0; i < info->num_fields; ++i) {
777                         field_size = mono_marshal_type_size (info->fields [i].field->type, 
778                                                            info->fields [i].mspec, 
779                                                            &align, TRUE, klass->unicode);
780                         if ((info->fields [i].offset < 8) && (info->fields [i].offset + field_size) > 8) {
781                                 pass_on_stack = TRUE;
782                                 break;
783                         }
784                 }
785         }
786
787         if (pass_on_stack) {
788                 /* Allways pass in memory */
789                 ainfo->offset = *stack_size;
790                 *stack_size += ALIGN_TO (size, 8);
791                 ainfo->storage = ArgOnStack;
792
793                 return;
794         }
795
796         /* FIXME: Handle structs smaller than 8 bytes */
797         //if ((size % 8) != 0)
798         //      NOT_IMPLEMENTED;
799
800         if (size > 8)
801                 nquads = 2;
802         else
803                 nquads = 1;
804
805         if (!sig->pinvoke) {
806                 /* Always pass in 1 or 2 integer registers */
807                 args [0] = ARG_CLASS_INTEGER;
808                 args [1] = ARG_CLASS_INTEGER;
809                 /* Only the simplest cases are supported */
810                 if (is_return && nquads != 1) {
811                         args [0] = ARG_CLASS_MEMORY;
812                         args [1] = ARG_CLASS_MEMORY;
813                 }
814         } else {
815                 /*
816                  * Implement the algorithm from section 3.2.3 of the X86_64 ABI.
817                  * The X87 and SSEUP stuff is left out since there are no such types in
818                  * the CLR.
819                  */
820                 info = mono_marshal_load_type_info (klass);
821                 g_assert (info);
822
823 #ifndef HOST_WIN32
824                 if (info->native_size > 16) {
825                         ainfo->offset = *stack_size;
826                         *stack_size += ALIGN_TO (info->native_size, 8);
827                         ainfo->storage = ArgOnStack;
828
829                         return;
830                 }
831 #else
832                 switch (info->native_size) {
833                 case 1: case 2: case 4: case 8:
834                         break;
835                 default:
836                         if (is_return) {
837                                 ainfo->storage = ArgOnStack;
838                                 ainfo->offset = *stack_size;
839                                 *stack_size += ALIGN_TO (info->native_size, 8);
840                         }
841                         else {
842                                 ainfo->storage = ArgValuetypeAddrInIReg;
843
844                                 if (*gr < PARAM_REGS) {
845                                         ainfo->pair_storage [0] = ArgInIReg;
846                                         ainfo->pair_regs [0] = param_regs [*gr];
847                                         (*gr) ++;
848                                 }
849                                 else {
850                                         ainfo->pair_storage [0] = ArgOnStack;
851                                         ainfo->offset = *stack_size;
852                                         *stack_size += 8;
853                                 }
854                         }
855
856                         return;
857                 }
858 #endif
859
860                 args [0] = ARG_CLASS_NO_CLASS;
861                 args [1] = ARG_CLASS_NO_CLASS;
862                 for (quad = 0; quad < nquads; ++quad) {
863                         int size;
864                         guint32 align;
865                         ArgumentClass class1;
866                 
867                         if (info->num_fields == 0)
868                                 class1 = ARG_CLASS_MEMORY;
869                         else
870                                 class1 = ARG_CLASS_NO_CLASS;
871                         for (i = 0; i < info->num_fields; ++i) {
872                                 size = mono_marshal_type_size (info->fields [i].field->type, 
873                                                                                            info->fields [i].mspec, 
874                                                                                            &align, TRUE, klass->unicode);
875                                 if ((info->fields [i].offset < 8) && (info->fields [i].offset + size) > 8) {
876                                         /* Unaligned field */
877                                         NOT_IMPLEMENTED;
878                                 }
879
880                                 /* Skip fields in other quad */
881                                 if ((quad == 0) && (info->fields [i].offset >= 8))
882                                         continue;
883                                 if ((quad == 1) && (info->fields [i].offset < 8))
884                                         continue;
885
886                                 /* How far into this quad this data extends.*/
887                                 /* (8 is size of quad) */
888                                 quadsize [quad] = info->fields [i].offset + size - (quad * 8);
889
890                                 class1 = merge_argument_class_from_type (info->fields [i].field->type, class1);
891                         }
892                         g_assert (class1 != ARG_CLASS_NO_CLASS);
893                         args [quad] = class1;
894                 }
895         }
896
897         /* Post merger cleanup */
898         if ((args [0] == ARG_CLASS_MEMORY) || (args [1] == ARG_CLASS_MEMORY))
899                 args [0] = args [1] = ARG_CLASS_MEMORY;
900
901         /* Allocate registers */
902         {
903                 int orig_gr = *gr;
904                 int orig_fr = *fr;
905
906                 ainfo->storage = ArgValuetypeInReg;
907                 ainfo->pair_storage [0] = ainfo->pair_storage [1] = ArgNone;
908                 ainfo->nregs = nquads;
909                 for (quad = 0; quad < nquads; ++quad) {
910                         switch (args [quad]) {
911                         case ARG_CLASS_INTEGER:
912                                 if (*gr >= PARAM_REGS)
913                                         args [quad] = ARG_CLASS_MEMORY;
914                                 else {
915                                         ainfo->pair_storage [quad] = ArgInIReg;
916                                         if (is_return)
917                                                 ainfo->pair_regs [quad] = return_regs [*gr];
918                                         else
919                                                 ainfo->pair_regs [quad] = param_regs [*gr];
920                                         (*gr) ++;
921                                 }
922                                 break;
923                         case ARG_CLASS_SSE:
924                                 if (*fr >= FLOAT_PARAM_REGS)
925                                         args [quad] = ARG_CLASS_MEMORY;
926                                 else {
927                                         if (quadsize[quad] <= 4)
928                                                 ainfo->pair_storage [quad] = ArgInFloatSSEReg;
929                                         else ainfo->pair_storage [quad] = ArgInDoubleSSEReg;
930                                         ainfo->pair_regs [quad] = *fr;
931                                         (*fr) ++;
932                                 }
933                                 break;
934                         case ARG_CLASS_MEMORY:
935                                 break;
936                         default:
937                                 g_assert_not_reached ();
938                         }
939                 }
940
941                 if ((args [0] == ARG_CLASS_MEMORY) || (args [1] == ARG_CLASS_MEMORY)) {
942                         /* Revert possible register assignments */
943                         *gr = orig_gr;
944                         *fr = orig_fr;
945
946                         ainfo->offset = *stack_size;
947                         if (sig->pinvoke)
948                                 *stack_size += ALIGN_TO (info->native_size, 8);
949                         else
950                                 *stack_size += nquads * sizeof(mgreg_t);
951                         ainfo->storage = ArgOnStack;
952                 }
953         }
954 }
955
956 /*
957  * get_call_info:
958  *
959  *  Obtain information about a call according to the calling convention.
960  * For AMD64, see the "System V ABI, x86-64 Architecture Processor Supplement 
961  * Draft Version 0.23" document for more information.
962  */
963 static CallInfo*
964 get_call_info (MonoGenericSharingContext *gsctx, MonoMemPool *mp, MonoMethodSignature *sig)
965 {
966         guint32 i, gr, fr, pstart;
967         MonoType *ret_type;
968         int n = sig->hasthis + sig->param_count;
969         guint32 stack_size = 0;
970         CallInfo *cinfo;
971         gboolean is_pinvoke = sig->pinvoke;
972
973         if (mp)
974                 cinfo = mono_mempool_alloc0 (mp, sizeof (CallInfo) + (sizeof (ArgInfo) * n));
975         else
976                 cinfo = g_malloc0 (sizeof (CallInfo) + (sizeof (ArgInfo) * n));
977
978         cinfo->nargs = n;
979
980         gr = 0;
981         fr = 0;
982
983         /* return value */
984         {
985                 ret_type = mini_type_get_underlying_type (gsctx, sig->ret);
986                 switch (ret_type->type) {
987                 case MONO_TYPE_BOOLEAN:
988                 case MONO_TYPE_I1:
989                 case MONO_TYPE_U1:
990                 case MONO_TYPE_I2:
991                 case MONO_TYPE_U2:
992                 case MONO_TYPE_CHAR:
993                 case MONO_TYPE_I4:
994                 case MONO_TYPE_U4:
995                 case MONO_TYPE_I:
996                 case MONO_TYPE_U:
997                 case MONO_TYPE_PTR:
998                 case MONO_TYPE_FNPTR:
999                 case MONO_TYPE_CLASS:
1000                 case MONO_TYPE_OBJECT:
1001                 case MONO_TYPE_SZARRAY:
1002                 case MONO_TYPE_ARRAY:
1003                 case MONO_TYPE_STRING:
1004                         cinfo->ret.storage = ArgInIReg;
1005                         cinfo->ret.reg = AMD64_RAX;
1006                         break;
1007                 case MONO_TYPE_U8:
1008                 case MONO_TYPE_I8:
1009                         cinfo->ret.storage = ArgInIReg;
1010                         cinfo->ret.reg = AMD64_RAX;
1011                         break;
1012                 case MONO_TYPE_R4:
1013                         cinfo->ret.storage = ArgInFloatSSEReg;
1014                         cinfo->ret.reg = AMD64_XMM0;
1015                         break;
1016                 case MONO_TYPE_R8:
1017                         cinfo->ret.storage = ArgInDoubleSSEReg;
1018                         cinfo->ret.reg = AMD64_XMM0;
1019                         break;
1020                 case MONO_TYPE_GENERICINST:
1021                         if (!mono_type_generic_inst_is_valuetype (ret_type)) {
1022                                 cinfo->ret.storage = ArgInIReg;
1023                                 cinfo->ret.reg = AMD64_RAX;
1024                                 break;
1025                         }
1026                         /* fall through */
1027                 case MONO_TYPE_VALUETYPE: {
1028                         guint32 tmp_gr = 0, tmp_fr = 0, tmp_stacksize = 0;
1029
1030                         add_valuetype (gsctx, sig, &cinfo->ret, sig->ret, TRUE, &tmp_gr, &tmp_fr, &tmp_stacksize);
1031                         if (cinfo->ret.storage == ArgOnStack) {
1032                                 cinfo->vtype_retaddr = TRUE;
1033                                 /* The caller passes the address where the value is stored */
1034                         }
1035                         break;
1036                 }
1037                 case MONO_TYPE_TYPEDBYREF:
1038                         /* Same as a valuetype with size 24 */
1039                         cinfo->vtype_retaddr = TRUE;
1040                         break;
1041                 case MONO_TYPE_VOID:
1042                         break;
1043                 default:
1044                         g_error ("Can't handle as return value 0x%x", sig->ret->type);
1045                 }
1046         }
1047
1048         pstart = 0;
1049         /*
1050          * To simplify get_this_arg_reg () and LLVM integration, emit the vret arg after
1051          * the first argument, allowing 'this' to be always passed in the first arg reg.
1052          * Also do this if the first argument is a reference type, since virtual calls
1053          * are sometimes made using calli without sig->hasthis set, like in the delegate
1054          * invoke wrappers.
1055          */
1056         if (cinfo->vtype_retaddr && !is_pinvoke && (sig->hasthis || (sig->param_count > 0 && MONO_TYPE_IS_REFERENCE (mini_type_get_underlying_type (gsctx, sig->params [0]))))) {
1057                 if (sig->hasthis) {
1058                         add_general (&gr, &stack_size, cinfo->args + 0);
1059                 } else {
1060                         add_general (&gr, &stack_size, &cinfo->args [sig->hasthis + 0]);
1061                         pstart = 1;
1062                 }
1063                 add_general (&gr, &stack_size, &cinfo->ret);
1064                 cinfo->vret_arg_index = 1;
1065         } else {
1066                 /* this */
1067                 if (sig->hasthis)
1068                         add_general (&gr, &stack_size, cinfo->args + 0);
1069
1070                 if (cinfo->vtype_retaddr)
1071                         add_general (&gr, &stack_size, &cinfo->ret);
1072         }
1073
1074         if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG) && (n == 0)) {
1075                 gr = PARAM_REGS;
1076                 fr = FLOAT_PARAM_REGS;
1077                 
1078                 /* Emit the signature cookie just before the implicit arguments */
1079                 add_general (&gr, &stack_size, &cinfo->sig_cookie);
1080         }
1081
1082         for (i = pstart; i < sig->param_count; ++i) {
1083                 ArgInfo *ainfo = &cinfo->args [sig->hasthis + i];
1084                 MonoType *ptype;
1085
1086 #ifdef HOST_WIN32
1087                 /* The float param registers and other param registers must be the same index on Windows x64.*/
1088                 if (gr > fr)
1089                         fr = gr;
1090                 else if (fr > gr)
1091                         gr = fr;
1092 #endif
1093
1094                 if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG) && (i == sig->sentinelpos)) {
1095                         /* We allways pass the sig cookie on the stack for simplicity */
1096                         /* 
1097                          * Prevent implicit arguments + the sig cookie from being passed 
1098                          * in registers.
1099                          */
1100                         gr = PARAM_REGS;
1101                         fr = FLOAT_PARAM_REGS;
1102
1103                         /* Emit the signature cookie just before the implicit arguments */
1104                         add_general (&gr, &stack_size, &cinfo->sig_cookie);
1105                 }
1106
1107                 ptype = mini_type_get_underlying_type (gsctx, sig->params [i]);
1108                 switch (ptype->type) {
1109                 case MONO_TYPE_BOOLEAN:
1110                 case MONO_TYPE_I1:
1111                 case MONO_TYPE_U1:
1112                         add_general (&gr, &stack_size, ainfo);
1113                         break;
1114                 case MONO_TYPE_I2:
1115                 case MONO_TYPE_U2:
1116                 case MONO_TYPE_CHAR:
1117                         add_general (&gr, &stack_size, ainfo);
1118                         break;
1119                 case MONO_TYPE_I4:
1120                 case MONO_TYPE_U4:
1121                         add_general (&gr, &stack_size, ainfo);
1122                         break;
1123                 case MONO_TYPE_I:
1124                 case MONO_TYPE_U:
1125                 case MONO_TYPE_PTR:
1126                 case MONO_TYPE_FNPTR:
1127                 case MONO_TYPE_CLASS:
1128                 case MONO_TYPE_OBJECT:
1129                 case MONO_TYPE_STRING:
1130                 case MONO_TYPE_SZARRAY:
1131                 case MONO_TYPE_ARRAY:
1132                         add_general (&gr, &stack_size, ainfo);
1133                         break;
1134                 case MONO_TYPE_GENERICINST:
1135                         if (!mono_type_generic_inst_is_valuetype (ptype)) {
1136                                 add_general (&gr, &stack_size, ainfo);
1137                                 break;
1138                         }
1139                         /* fall through */
1140                 case MONO_TYPE_VALUETYPE:
1141                         add_valuetype (gsctx, sig, ainfo, sig->params [i], FALSE, &gr, &fr, &stack_size);
1142                         break;
1143                 case MONO_TYPE_TYPEDBYREF:
1144 #ifdef HOST_WIN32
1145                         add_valuetype (gsctx, sig, ainfo, sig->params [i], FALSE, &gr, &fr, &stack_size);
1146 #else
1147                         stack_size += sizeof (MonoTypedRef);
1148                         ainfo->storage = ArgOnStack;
1149 #endif
1150                         break;
1151                 case MONO_TYPE_U8:
1152                 case MONO_TYPE_I8:
1153                         add_general (&gr, &stack_size, ainfo);
1154                         break;
1155                 case MONO_TYPE_R4:
1156                         add_float (&fr, &stack_size, ainfo, FALSE);
1157                         break;
1158                 case MONO_TYPE_R8:
1159                         add_float (&fr, &stack_size, ainfo, TRUE);
1160                         break;
1161                 default:
1162                         g_assert_not_reached ();
1163                 }
1164         }
1165
1166         if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG) && (n > 0) && (sig->sentinelpos == sig->param_count)) {
1167                 gr = PARAM_REGS;
1168                 fr = FLOAT_PARAM_REGS;
1169                 
1170                 /* Emit the signature cookie just before the implicit arguments */
1171                 add_general (&gr, &stack_size, &cinfo->sig_cookie);
1172         }
1173
1174 #ifdef HOST_WIN32
1175         // There always is 32 bytes reserved on the stack when calling on Winx64
1176         stack_size += 0x20;
1177 #endif
1178
1179 #ifndef MONO_AMD64_NO_PUSHES
1180         if (stack_size & 0x8) {
1181                 /* The AMD64 ABI requires each stack frame to be 16 byte aligned */
1182                 cinfo->need_stack_align = TRUE;
1183                 stack_size += 8;
1184         }
1185 #endif
1186
1187         cinfo->stack_usage = stack_size;
1188         cinfo->reg_usage = gr;
1189         cinfo->freg_usage = fr;
1190         return cinfo;
1191 }
1192
1193 /*
1194  * mono_arch_get_argument_info:
1195  * @csig:  a method signature
1196  * @param_count: the number of parameters to consider
1197  * @arg_info: an array to store the result infos
1198  *
1199  * Gathers information on parameters such as size, alignment and
1200  * padding. arg_info should be large enought to hold param_count + 1 entries. 
1201  *
1202  * Returns the size of the argument area on the stack.
1203  */
1204 int
1205 mono_arch_get_argument_info (MonoMethodSignature *csig, int param_count, MonoJitArgumentInfo *arg_info)
1206 {
1207         int k;
1208         CallInfo *cinfo = get_call_info (NULL, NULL, csig);
1209         guint32 args_size = cinfo->stack_usage;
1210
1211         /* The arguments are saved to a stack area in mono_arch_instrument_prolog */
1212         if (csig->hasthis) {
1213                 arg_info [0].offset = 0;
1214         }
1215
1216         for (k = 0; k < param_count; k++) {
1217                 arg_info [k + 1].offset = ((k + csig->hasthis) * 8);
1218                 /* FIXME: */
1219                 arg_info [k + 1].size = 0;
1220         }
1221
1222         g_free (cinfo);
1223
1224         return args_size;
1225 }
1226
1227 gboolean
1228 mono_amd64_tail_call_supported (MonoMethodSignature *caller_sig, MonoMethodSignature *callee_sig)
1229 {
1230         CallInfo *c1, *c2;
1231         gboolean res;
1232
1233         c1 = get_call_info (NULL, NULL, caller_sig);
1234         c2 = get_call_info (NULL, NULL, callee_sig);
1235         res = c1->stack_usage >= c2->stack_usage;
1236         if (callee_sig->ret && MONO_TYPE_ISSTRUCT (callee_sig->ret) && c2->ret.storage != ArgValuetypeInReg)
1237                 /* An address on the callee's stack is passed as the first argument */
1238                 res = FALSE;
1239
1240         g_free (c1);
1241         g_free (c2);
1242
1243         return res;
1244 }
1245
1246 static int 
1247 cpuid (int id, int* p_eax, int* p_ebx, int* p_ecx, int* p_edx)
1248 {
1249 #if defined(MONO_CROSS_COMPILE)
1250         return 0;
1251 #else
1252 #ifndef _MSC_VER
1253         __asm__ __volatile__ ("cpuid"
1254                 : "=a" (*p_eax), "=b" (*p_ebx), "=c" (*p_ecx), "=d" (*p_edx)
1255                 : "a" (id));
1256 #else
1257         int info[4];
1258         __cpuid(info, id);
1259         *p_eax = info[0];
1260         *p_ebx = info[1];
1261         *p_ecx = info[2];
1262         *p_edx = info[3];
1263 #endif
1264         return 1;
1265 #endif
1266 }
1267
1268 /*
1269  * Initialize the cpu to execute managed code.
1270  */
1271 void
1272 mono_arch_cpu_init (void)
1273 {
1274 #ifndef _MSC_VER
1275         guint16 fpcw;
1276
1277         /* spec compliance requires running with double precision */
1278         __asm__  __volatile__ ("fnstcw %0\n": "=m" (fpcw));
1279         fpcw &= ~X86_FPCW_PRECC_MASK;
1280         fpcw |= X86_FPCW_PREC_DOUBLE;
1281         __asm__  __volatile__ ("fldcw %0\n": : "m" (fpcw));
1282         __asm__  __volatile__ ("fnstcw %0\n": "=m" (fpcw));
1283 #else
1284         /* TODO: This is crashing on Win64 right now.
1285         * _control87 (_PC_53, MCW_PC);
1286         */
1287 #endif
1288 }
1289
1290 /*
1291  * Initialize architecture specific code.
1292  */
1293 void
1294 mono_arch_init (void)
1295 {
1296         int flags;
1297
1298         InitializeCriticalSection (&mini_arch_mutex);
1299 #if defined(__native_client_codegen__)
1300         mono_native_tls_alloc (&nacl_instruction_depth, NULL);
1301         mono_native_tls_set_value (nacl_instruction_depth, (gpointer)0);
1302         mono_native_tls_alloc (&nacl_rex_tag, NULL);
1303         mono_native_tls_alloc (&nacl_legacy_prefix_tag, NULL);
1304 #endif
1305
1306 #ifdef MONO_ARCH_NOMAP32BIT
1307         flags = MONO_MMAP_READ;
1308         /* amd64_mov_reg_imm () + amd64_mov_reg_membase () */
1309         breakpoint_size = 13;
1310         breakpoint_fault_size = 3;
1311 #else
1312         flags = MONO_MMAP_READ|MONO_MMAP_32BIT;
1313         /* amd64_mov_reg_mem () */
1314         breakpoint_size = 8;
1315         breakpoint_fault_size = 8;
1316 #endif
1317
1318         /* amd64_alu_membase_imm_size (code, X86_CMP, AMD64_R11, 0, 0, 4); */
1319         single_step_fault_size = 4;
1320
1321         ss_trigger_page = mono_valloc (NULL, mono_pagesize (), flags);
1322         bp_trigger_page = mono_valloc (NULL, mono_pagesize (), flags);
1323         mono_mprotect (bp_trigger_page, mono_pagesize (), 0);
1324
1325         mono_aot_register_jit_icall ("mono_amd64_throw_exception", mono_amd64_throw_exception);
1326         mono_aot_register_jit_icall ("mono_amd64_throw_corlib_exception", mono_amd64_throw_corlib_exception);
1327         mono_aot_register_jit_icall ("mono_amd64_get_original_ip", mono_amd64_get_original_ip);
1328 }
1329
1330 /*
1331  * Cleanup architecture specific code.
1332  */
1333 void
1334 mono_arch_cleanup (void)
1335 {
1336         DeleteCriticalSection (&mini_arch_mutex);
1337 #if defined(__native_client_codegen__)
1338         mono_native_tls_free (nacl_instruction_depth);
1339         mono_native_tls_free (nacl_rex_tag);
1340         mono_native_tls_free (nacl_legacy_prefix_tag);
1341 #endif
1342 }
1343
1344 /*
1345  * This function returns the optimizations supported on this cpu.
1346  */
1347 guint32
1348 mono_arch_cpu_optimizazions (guint32 *exclude_mask)
1349 {
1350         int eax, ebx, ecx, edx;
1351         guint32 opts = 0;
1352
1353         *exclude_mask = 0;
1354         /* Feature Flags function, flags returned in EDX. */
1355         if (cpuid (1, &eax, &ebx, &ecx, &edx)) {
1356                 if (edx & (1 << 15)) {
1357                         opts |= MONO_OPT_CMOV;
1358                         if (edx & 1)
1359                                 opts |= MONO_OPT_FCMOV;
1360                         else
1361                                 *exclude_mask |= MONO_OPT_FCMOV;
1362                 } else
1363                         *exclude_mask |= MONO_OPT_CMOV;
1364         }
1365
1366         return opts;
1367 }
1368
1369 /*
1370  * This function test for all SSE functions supported.
1371  *
1372  * Returns a bitmask corresponding to all supported versions.
1373  * 
1374  */
1375 guint32
1376 mono_arch_cpu_enumerate_simd_versions (void)
1377 {
1378         int eax, ebx, ecx, edx;
1379         guint32 sse_opts = 0;
1380
1381         if (cpuid (1, &eax, &ebx, &ecx, &edx)) {
1382                 if (edx & (1 << 25))
1383                         sse_opts |= SIMD_VERSION_SSE1;
1384                 if (edx & (1 << 26))
1385                         sse_opts |= SIMD_VERSION_SSE2;
1386                 if (ecx & (1 << 0))
1387                         sse_opts |= SIMD_VERSION_SSE3;
1388                 if (ecx & (1 << 9))
1389                         sse_opts |= SIMD_VERSION_SSSE3;
1390                 if (ecx & (1 << 19))
1391                         sse_opts |= SIMD_VERSION_SSE41;
1392                 if (ecx & (1 << 20))
1393                         sse_opts |= SIMD_VERSION_SSE42;
1394         }
1395
1396         /* Yes, all this needs to be done to check for sse4a.
1397            See: "Amd: CPUID Specification"
1398          */
1399         if (cpuid (0x80000000, &eax, &ebx, &ecx, &edx)) {
1400                 /* eax greater or equal than 0x80000001, ebx = 'htuA', ecx = DMAc', edx = 'itne'*/
1401                 if ((((unsigned int) eax) >= 0x80000001) && (ebx == 0x68747541) && (ecx == 0x444D4163) && (edx == 0x69746E65)) {
1402                         cpuid (0x80000001, &eax, &ebx, &ecx, &edx);
1403                         if (ecx & (1 << 6))
1404                                 sse_opts |= SIMD_VERSION_SSE4a;
1405                 }
1406         }
1407
1408         return sse_opts;        
1409 }
1410
1411 #ifndef DISABLE_JIT
1412
1413 GList *
1414 mono_arch_get_allocatable_int_vars (MonoCompile *cfg)
1415 {
1416         GList *vars = NULL;
1417         int i;
1418
1419         for (i = 0; i < cfg->num_varinfo; i++) {
1420                 MonoInst *ins = cfg->varinfo [i];
1421                 MonoMethodVar *vmv = MONO_VARINFO (cfg, i);
1422
1423                 /* unused vars */
1424                 if (vmv->range.first_use.abs_pos >= vmv->range.last_use.abs_pos)
1425                         continue;
1426
1427                 if ((ins->flags & (MONO_INST_IS_DEAD|MONO_INST_VOLATILE|MONO_INST_INDIRECT)) || 
1428                     (ins->opcode != OP_LOCAL && ins->opcode != OP_ARG))
1429                         continue;
1430
1431                 if (mono_is_regsize_var (ins->inst_vtype)) {
1432                         g_assert (MONO_VARINFO (cfg, i)->reg == -1);
1433                         g_assert (i == vmv->idx);
1434                         vars = g_list_prepend (vars, vmv);
1435                 }
1436         }
1437
1438         vars = mono_varlist_sort (cfg, vars, 0);
1439
1440         return vars;
1441 }
1442
1443 /**
1444  * mono_arch_compute_omit_fp:
1445  *
1446  *   Determine whenever the frame pointer can be eliminated.
1447  */
1448 static void
1449 mono_arch_compute_omit_fp (MonoCompile *cfg)
1450 {
1451         MonoMethodSignature *sig;
1452         MonoMethodHeader *header;
1453         int i, locals_size;
1454         CallInfo *cinfo;
1455
1456         if (cfg->arch.omit_fp_computed)
1457                 return;
1458
1459         header = cfg->header;
1460
1461         sig = mono_method_signature (cfg->method);
1462
1463         if (!cfg->arch.cinfo)
1464                 cfg->arch.cinfo = get_call_info (cfg->generic_sharing_context, cfg->mempool, sig);
1465         cinfo = cfg->arch.cinfo;
1466
1467         /*
1468          * FIXME: Remove some of the restrictions.
1469          */
1470         cfg->arch.omit_fp = TRUE;
1471         cfg->arch.omit_fp_computed = TRUE;
1472
1473 #ifdef __native_client_codegen__
1474         /* NaCl modules may not change the value of RBP, so it cannot be */
1475         /* used as a normal register, but it can be used as a frame pointer*/
1476         cfg->disable_omit_fp = TRUE;
1477         cfg->arch.omit_fp = FALSE;
1478 #endif
1479
1480         if (cfg->disable_omit_fp)
1481                 cfg->arch.omit_fp = FALSE;
1482
1483         if (!debug_omit_fp ())
1484                 cfg->arch.omit_fp = FALSE;
1485         /*
1486         if (cfg->method->save_lmf)
1487                 cfg->arch.omit_fp = FALSE;
1488         */
1489         if (cfg->flags & MONO_CFG_HAS_ALLOCA)
1490                 cfg->arch.omit_fp = FALSE;
1491         if (header->num_clauses)
1492                 cfg->arch.omit_fp = FALSE;
1493         if (cfg->param_area)
1494                 cfg->arch.omit_fp = FALSE;
1495         if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG))
1496                 cfg->arch.omit_fp = FALSE;
1497         if ((mono_jit_trace_calls != NULL && mono_trace_eval (cfg->method)) ||
1498                 (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE))
1499                 cfg->arch.omit_fp = FALSE;
1500         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
1501                 ArgInfo *ainfo = &cinfo->args [i];
1502
1503                 if (ainfo->storage == ArgOnStack) {
1504                         /* 
1505                          * The stack offset can only be determined when the frame
1506                          * size is known.
1507                          */
1508                         cfg->arch.omit_fp = FALSE;
1509                 }
1510         }
1511
1512         locals_size = 0;
1513         for (i = cfg->locals_start; i < cfg->num_varinfo; i++) {
1514                 MonoInst *ins = cfg->varinfo [i];
1515                 int ialign;
1516
1517                 locals_size += mono_type_size (ins->inst_vtype, &ialign);
1518         }
1519 }
1520
1521 GList *
1522 mono_arch_get_global_int_regs (MonoCompile *cfg)
1523 {
1524         GList *regs = NULL;
1525
1526         mono_arch_compute_omit_fp (cfg);
1527
1528         if (cfg->globalra) {
1529                 if (cfg->arch.omit_fp)
1530                         regs = g_list_prepend (regs, (gpointer)AMD64_RBP);
1531  
1532                 regs = g_list_prepend (regs, (gpointer)AMD64_RBX);
1533                 regs = g_list_prepend (regs, (gpointer)AMD64_R12);
1534                 regs = g_list_prepend (regs, (gpointer)AMD64_R13);
1535                 regs = g_list_prepend (regs, (gpointer)AMD64_R14);
1536 #ifndef __native_client_codegen__
1537                 regs = g_list_prepend (regs, (gpointer)AMD64_R15);
1538 #endif
1539  
1540                 regs = g_list_prepend (regs, (gpointer)AMD64_R10);
1541                 regs = g_list_prepend (regs, (gpointer)AMD64_R9);
1542                 regs = g_list_prepend (regs, (gpointer)AMD64_R8);
1543                 regs = g_list_prepend (regs, (gpointer)AMD64_RDI);
1544                 regs = g_list_prepend (regs, (gpointer)AMD64_RSI);
1545                 regs = g_list_prepend (regs, (gpointer)AMD64_RDX);
1546                 regs = g_list_prepend (regs, (gpointer)AMD64_RCX);
1547                 regs = g_list_prepend (regs, (gpointer)AMD64_RAX);
1548         } else {
1549                 if (cfg->arch.omit_fp)
1550                         regs = g_list_prepend (regs, (gpointer)AMD64_RBP);
1551
1552                 /* We use the callee saved registers for global allocation */
1553                 regs = g_list_prepend (regs, (gpointer)AMD64_RBX);
1554                 regs = g_list_prepend (regs, (gpointer)AMD64_R12);
1555                 regs = g_list_prepend (regs, (gpointer)AMD64_R13);
1556                 regs = g_list_prepend (regs, (gpointer)AMD64_R14);
1557 #ifndef __native_client_codegen__
1558                 regs = g_list_prepend (regs, (gpointer)AMD64_R15);
1559 #endif
1560 #ifdef HOST_WIN32
1561                 regs = g_list_prepend (regs, (gpointer)AMD64_RDI);
1562                 regs = g_list_prepend (regs, (gpointer)AMD64_RSI);
1563 #endif
1564         }
1565
1566         return regs;
1567 }
1568  
1569 GList*
1570 mono_arch_get_global_fp_regs (MonoCompile *cfg)
1571 {
1572         GList *regs = NULL;
1573         int i;
1574
1575         /* All XMM registers */
1576         for (i = 0; i < 16; ++i)
1577                 regs = g_list_prepend (regs, GINT_TO_POINTER (i));
1578
1579         return regs;
1580 }
1581
1582 GList*
1583 mono_arch_get_iregs_clobbered_by_call (MonoCallInst *call)
1584 {
1585         static GList *r = NULL;
1586
1587         if (r == NULL) {
1588                 GList *regs = NULL;
1589
1590                 regs = g_list_prepend (regs, (gpointer)AMD64_RBP);
1591                 regs = g_list_prepend (regs, (gpointer)AMD64_RBX);
1592                 regs = g_list_prepend (regs, (gpointer)AMD64_R12);
1593                 regs = g_list_prepend (regs, (gpointer)AMD64_R13);
1594                 regs = g_list_prepend (regs, (gpointer)AMD64_R14);
1595 #ifndef __native_client_codegen__
1596                 regs = g_list_prepend (regs, (gpointer)AMD64_R15);
1597 #endif
1598
1599                 regs = g_list_prepend (regs, (gpointer)AMD64_R10);
1600                 regs = g_list_prepend (regs, (gpointer)AMD64_R9);
1601                 regs = g_list_prepend (regs, (gpointer)AMD64_R8);
1602                 regs = g_list_prepend (regs, (gpointer)AMD64_RDI);
1603                 regs = g_list_prepend (regs, (gpointer)AMD64_RSI);
1604                 regs = g_list_prepend (regs, (gpointer)AMD64_RDX);
1605                 regs = g_list_prepend (regs, (gpointer)AMD64_RCX);
1606                 regs = g_list_prepend (regs, (gpointer)AMD64_RAX);
1607
1608                 InterlockedCompareExchangePointer ((gpointer*)&r, regs, NULL);
1609         }
1610
1611         return r;
1612 }
1613
1614 GList*
1615 mono_arch_get_fregs_clobbered_by_call (MonoCallInst *call)
1616 {
1617         int i;
1618         static GList *r = NULL;
1619
1620         if (r == NULL) {
1621                 GList *regs = NULL;
1622
1623                 for (i = 0; i < AMD64_XMM_NREG; ++i)
1624                         regs = g_list_prepend (regs, GINT_TO_POINTER (MONO_MAX_IREGS + i));
1625
1626                 InterlockedCompareExchangePointer ((gpointer*)&r, regs, NULL);
1627         }
1628
1629         return r;
1630 }
1631
1632 /*
1633  * mono_arch_regalloc_cost:
1634  *
1635  *  Return the cost, in number of memory references, of the action of 
1636  * allocating the variable VMV into a register during global register
1637  * allocation.
1638  */
1639 guint32
1640 mono_arch_regalloc_cost (MonoCompile *cfg, MonoMethodVar *vmv)
1641 {
1642         MonoInst *ins = cfg->varinfo [vmv->idx];
1643
1644         if (cfg->method->save_lmf)
1645                 /* The register is already saved */
1646                 /* substract 1 for the invisible store in the prolog */
1647                 return (ins->opcode == OP_ARG) ? 0 : 1;
1648         else
1649                 /* push+pop */
1650                 return (ins->opcode == OP_ARG) ? 1 : 2;
1651 }
1652
1653 /*
1654  * mono_arch_fill_argument_info:
1655  *
1656  *   Populate cfg->args, cfg->ret and cfg->vret_addr with information about the arguments
1657  * of the method.
1658  */
1659 void
1660 mono_arch_fill_argument_info (MonoCompile *cfg)
1661 {
1662         MonoMethodSignature *sig;
1663         MonoMethodHeader *header;
1664         MonoInst *ins;
1665         int i;
1666         CallInfo *cinfo;
1667
1668         header = cfg->header;
1669
1670         sig = mono_method_signature (cfg->method);
1671
1672         cinfo = cfg->arch.cinfo;
1673
1674         /*
1675          * Contrary to mono_arch_allocate_vars (), the information should describe
1676          * where the arguments are at the beginning of the method, not where they can be 
1677          * accessed during the execution of the method. The later makes no sense for the 
1678          * global register allocator, since a variable can be in more than one location.
1679          */
1680         if (sig->ret->type != MONO_TYPE_VOID) {
1681                 switch (cinfo->ret.storage) {
1682                 case ArgInIReg:
1683                 case ArgInFloatSSEReg:
1684                 case ArgInDoubleSSEReg:
1685                         if ((MONO_TYPE_ISSTRUCT (sig->ret) && !mono_class_from_mono_type (sig->ret)->enumtype) || (sig->ret->type == MONO_TYPE_TYPEDBYREF)) {
1686                                 cfg->vret_addr->opcode = OP_REGVAR;
1687                                 cfg->vret_addr->inst_c0 = cinfo->ret.reg;
1688                         }
1689                         else {
1690                                 cfg->ret->opcode = OP_REGVAR;
1691                                 cfg->ret->inst_c0 = cinfo->ret.reg;
1692                         }
1693                         break;
1694                 case ArgValuetypeInReg:
1695                         cfg->ret->opcode = OP_REGOFFSET;
1696                         cfg->ret->inst_basereg = -1;
1697                         cfg->ret->inst_offset = -1;
1698                         break;
1699                 default:
1700                         g_assert_not_reached ();
1701                 }
1702         }
1703
1704         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
1705                 ArgInfo *ainfo = &cinfo->args [i];
1706                 MonoType *arg_type;
1707
1708                 ins = cfg->args [i];
1709
1710                 if (sig->hasthis && (i == 0))
1711                         arg_type = &mono_defaults.object_class->byval_arg;
1712                 else
1713                         arg_type = sig->params [i - sig->hasthis];
1714
1715                 switch (ainfo->storage) {
1716                 case ArgInIReg:
1717                 case ArgInFloatSSEReg:
1718                 case ArgInDoubleSSEReg:
1719                         ins->opcode = OP_REGVAR;
1720                         ins->inst_c0 = ainfo->reg;
1721                         break;
1722                 case ArgOnStack:
1723                         ins->opcode = OP_REGOFFSET;
1724                         ins->inst_basereg = -1;
1725                         ins->inst_offset = -1;
1726                         break;
1727                 case ArgValuetypeInReg:
1728                         /* Dummy */
1729                         ins->opcode = OP_NOP;
1730                         break;
1731                 default:
1732                         g_assert_not_reached ();
1733                 }
1734         }
1735 }
1736  
1737 void
1738 mono_arch_allocate_vars (MonoCompile *cfg)
1739 {
1740         MonoMethodSignature *sig;
1741         MonoMethodHeader *header;
1742         MonoInst *ins;
1743         int i, offset;
1744         guint32 locals_stack_size, locals_stack_align;
1745         gint32 *offsets;
1746         CallInfo *cinfo;
1747
1748         header = cfg->header;
1749
1750         sig = mono_method_signature (cfg->method);
1751
1752         cinfo = cfg->arch.cinfo;
1753
1754         mono_arch_compute_omit_fp (cfg);
1755
1756         /*
1757          * We use the ABI calling conventions for managed code as well.
1758          * Exception: valuetypes are only sometimes passed or returned in registers.
1759          */
1760
1761         /*
1762          * The stack looks like this:
1763          * <incoming arguments passed on the stack>
1764          * <return value>
1765          * <lmf/caller saved registers>
1766          * <locals>
1767          * <spill area>
1768          * <localloc area>  -> grows dynamically
1769          * <params area>
1770          */
1771
1772         if (cfg->arch.omit_fp) {
1773                 cfg->flags |= MONO_CFG_HAS_SPILLUP;
1774                 cfg->frame_reg = AMD64_RSP;
1775                 offset = 0;
1776         } else {
1777                 /* Locals are allocated backwards from %fp */
1778                 cfg->frame_reg = AMD64_RBP;
1779                 offset = 0;
1780         }
1781
1782         if (cfg->method->save_lmf) {
1783                 /* The LMF var is allocated normally */
1784         } else {
1785                 if (cfg->arch.omit_fp)
1786                         cfg->arch.reg_save_area_offset = offset;
1787                 /* Reserve space for caller saved registers */
1788                 for (i = 0; i < AMD64_NREG; ++i)
1789                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
1790                                 offset += sizeof(mgreg_t);
1791                         }
1792         }
1793
1794         if (sig->ret->type != MONO_TYPE_VOID) {
1795                 switch (cinfo->ret.storage) {
1796                 case ArgInIReg:
1797                 case ArgInFloatSSEReg:
1798                 case ArgInDoubleSSEReg:
1799                         if ((MONO_TYPE_ISSTRUCT (sig->ret) && !mono_class_from_mono_type (sig->ret)->enumtype) || (sig->ret->type == MONO_TYPE_TYPEDBYREF)) {
1800                                 if (cfg->globalra) {
1801                                         cfg->vret_addr->opcode = OP_REGVAR;
1802                                         cfg->vret_addr->inst_c0 = cinfo->ret.reg;
1803                                 } else {
1804                                         /* The register is volatile */
1805                                         cfg->vret_addr->opcode = OP_REGOFFSET;
1806                                         cfg->vret_addr->inst_basereg = cfg->frame_reg;
1807                                         if (cfg->arch.omit_fp) {
1808                                                 cfg->vret_addr->inst_offset = offset;
1809                                                 offset += 8;
1810                                         } else {
1811                                                 offset += 8;
1812                                                 cfg->vret_addr->inst_offset = -offset;
1813                                         }
1814                                         if (G_UNLIKELY (cfg->verbose_level > 1)) {
1815                                                 printf ("vret_addr =");
1816                                                 mono_print_ins (cfg->vret_addr);
1817                                         }
1818                                 }
1819                         }
1820                         else {
1821                                 cfg->ret->opcode = OP_REGVAR;
1822                                 cfg->ret->inst_c0 = cinfo->ret.reg;
1823                         }
1824                         break;
1825                 case ArgValuetypeInReg:
1826                         /* Allocate a local to hold the result, the epilog will copy it to the correct place */
1827                         cfg->ret->opcode = OP_REGOFFSET;
1828                         cfg->ret->inst_basereg = cfg->frame_reg;
1829                         if (cfg->arch.omit_fp) {
1830                                 cfg->ret->inst_offset = offset;
1831                                 offset += cinfo->ret.pair_storage [1] == ArgNone ? 8 : 16;
1832                         } else {
1833                                 offset += cinfo->ret.pair_storage [1] == ArgNone ? 8 : 16;
1834                                 cfg->ret->inst_offset = - offset;
1835                         }
1836                         break;
1837                 default:
1838                         g_assert_not_reached ();
1839                 }
1840                 if (!cfg->globalra)
1841                         cfg->ret->dreg = cfg->ret->inst_c0;
1842         }
1843
1844         /* Allocate locals */
1845         if (!cfg->globalra) {
1846                 offsets = mono_allocate_stack_slots (cfg, cfg->arch.omit_fp ? FALSE: TRUE, &locals_stack_size, &locals_stack_align);
1847                 if (locals_stack_size > MONO_ARCH_MAX_FRAME_SIZE) {
1848                         char *mname = mono_method_full_name (cfg->method, TRUE);
1849                         cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
1850                         cfg->exception_message = g_strdup_printf ("Method %s stack is too big.", mname);
1851                         g_free (mname);
1852                         return;
1853                 }
1854                 
1855                 if (locals_stack_align) {
1856                         offset += (locals_stack_align - 1);
1857                         offset &= ~(locals_stack_align - 1);
1858                 }
1859                 if (cfg->arch.omit_fp) {
1860                         cfg->locals_min_stack_offset = offset;
1861                         cfg->locals_max_stack_offset = offset + locals_stack_size;
1862                 } else {
1863                         cfg->locals_min_stack_offset = - (offset + locals_stack_size);
1864                         cfg->locals_max_stack_offset = - offset;
1865                 }
1866                 
1867                 for (i = cfg->locals_start; i < cfg->num_varinfo; i++) {
1868                         if (offsets [i] != -1) {
1869                                 MonoInst *ins = cfg->varinfo [i];
1870                                 ins->opcode = OP_REGOFFSET;
1871                                 ins->inst_basereg = cfg->frame_reg;
1872                                 if (cfg->arch.omit_fp)
1873                                         ins->inst_offset = (offset + offsets [i]);
1874                                 else
1875                                         ins->inst_offset = - (offset + offsets [i]);
1876                                 //printf ("allocated local %d to ", i); mono_print_tree_nl (ins);
1877                         }
1878                 }
1879                 offset += locals_stack_size;
1880         }
1881
1882         if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG)) {
1883                 g_assert (!cfg->arch.omit_fp);
1884                 g_assert (cinfo->sig_cookie.storage == ArgOnStack);
1885                 cfg->sig_cookie = cinfo->sig_cookie.offset + ARGS_OFFSET;
1886         }
1887
1888         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
1889                 ins = cfg->args [i];
1890                 if (ins->opcode != OP_REGVAR) {
1891                         ArgInfo *ainfo = &cinfo->args [i];
1892                         gboolean inreg = TRUE;
1893                         MonoType *arg_type;
1894
1895                         if (sig->hasthis && (i == 0))
1896                                 arg_type = &mono_defaults.object_class->byval_arg;
1897                         else
1898                                 arg_type = sig->params [i - sig->hasthis];
1899
1900                         if (cfg->globalra) {
1901                                 /* The new allocator needs info about the original locations of the arguments */
1902                                 switch (ainfo->storage) {
1903                                 case ArgInIReg:
1904                                 case ArgInFloatSSEReg:
1905                                 case ArgInDoubleSSEReg:
1906                                         ins->opcode = OP_REGVAR;
1907                                         ins->inst_c0 = ainfo->reg;
1908                                         break;
1909                                 case ArgOnStack:
1910                                         g_assert (!cfg->arch.omit_fp);
1911                                         ins->opcode = OP_REGOFFSET;
1912                                         ins->inst_basereg = cfg->frame_reg;
1913                                         ins->inst_offset = ainfo->offset + ARGS_OFFSET;
1914                                         break;
1915                                 case ArgValuetypeInReg:
1916                                         ins->opcode = OP_REGOFFSET;
1917                                         ins->inst_basereg = cfg->frame_reg;
1918                                         /* These arguments are saved to the stack in the prolog */
1919                                         offset = ALIGN_TO (offset, sizeof(mgreg_t));
1920                                         if (cfg->arch.omit_fp) {
1921                                                 ins->inst_offset = offset;
1922                                                 offset += (ainfo->storage == ArgValuetypeInReg) ? ainfo->nregs * sizeof (mgreg_t) : sizeof (mgreg_t);
1923                                         } else {
1924                                                 offset += (ainfo->storage == ArgValuetypeInReg) ? ainfo->nregs * sizeof (mgreg_t) : sizeof (mgreg_t);
1925                                                 ins->inst_offset = - offset;
1926                                         }
1927                                         break;
1928                                 default:
1929                                         g_assert_not_reached ();
1930                                 }
1931
1932                                 continue;
1933                         }
1934
1935                         /* FIXME: Allocate volatile arguments to registers */
1936                         if (ins->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))
1937                                 inreg = FALSE;
1938
1939                         /* 
1940                          * Under AMD64, all registers used to pass arguments to functions
1941                          * are volatile across calls.
1942                          * FIXME: Optimize this.
1943                          */
1944                         if ((ainfo->storage == ArgInIReg) || (ainfo->storage == ArgInFloatSSEReg) || (ainfo->storage == ArgInDoubleSSEReg) || (ainfo->storage == ArgValuetypeInReg))
1945                                 inreg = FALSE;
1946
1947                         ins->opcode = OP_REGOFFSET;
1948
1949                         switch (ainfo->storage) {
1950                         case ArgInIReg:
1951                         case ArgInFloatSSEReg:
1952                         case ArgInDoubleSSEReg:
1953                                 if (inreg) {
1954                                         ins->opcode = OP_REGVAR;
1955                                         ins->dreg = ainfo->reg;
1956                                 }
1957                                 break;
1958                         case ArgOnStack:
1959                                 g_assert (!cfg->arch.omit_fp);
1960                                 ins->opcode = OP_REGOFFSET;
1961                                 ins->inst_basereg = cfg->frame_reg;
1962                                 ins->inst_offset = ainfo->offset + ARGS_OFFSET;
1963                                 break;
1964                         case ArgValuetypeInReg:
1965                                 break;
1966                         case ArgValuetypeAddrInIReg: {
1967                                 MonoInst *indir;
1968                                 g_assert (!cfg->arch.omit_fp);
1969                                 
1970                                 MONO_INST_NEW (cfg, indir, 0);
1971                                 indir->opcode = OP_REGOFFSET;
1972                                 if (ainfo->pair_storage [0] == ArgInIReg) {
1973                                         indir->inst_basereg = cfg->frame_reg;
1974                                         offset = ALIGN_TO (offset, sizeof (gpointer));
1975                                         offset += (sizeof (gpointer));
1976                                         indir->inst_offset = - offset;
1977                                 }
1978                                 else {
1979                                         indir->inst_basereg = cfg->frame_reg;
1980                                         indir->inst_offset = ainfo->offset + ARGS_OFFSET;
1981                                 }
1982                                 
1983                                 ins->opcode = OP_VTARG_ADDR;
1984                                 ins->inst_left = indir;
1985                                 
1986                                 break;
1987                         }
1988                         default:
1989                                 NOT_IMPLEMENTED;
1990                         }
1991
1992                         if (!inreg && (ainfo->storage != ArgOnStack) && (ainfo->storage != ArgValuetypeAddrInIReg)) {
1993                                 ins->opcode = OP_REGOFFSET;
1994                                 ins->inst_basereg = cfg->frame_reg;
1995                                 /* These arguments are saved to the stack in the prolog */
1996                                 offset = ALIGN_TO (offset, sizeof(mgreg_t));
1997                                 if (cfg->arch.omit_fp) {
1998                                         ins->inst_offset = offset;
1999                                         offset += (ainfo->storage == ArgValuetypeInReg) ? ainfo->nregs * sizeof (mgreg_t) : sizeof (mgreg_t);
2000                                         // Arguments are yet supported by the stack map creation code
2001                                         //cfg->locals_max_stack_offset = MAX (cfg->locals_max_stack_offset, offset);
2002                                 } else {
2003                                         offset += (ainfo->storage == ArgValuetypeInReg) ? ainfo->nregs * sizeof (mgreg_t) : sizeof (mgreg_t);
2004                                         ins->inst_offset = - offset;
2005                                         //cfg->locals_min_stack_offset = MIN (cfg->locals_min_stack_offset, offset);
2006                                 }
2007                         }
2008                 }
2009         }
2010
2011         cfg->stack_offset = offset;
2012 }
2013
2014 void
2015 mono_arch_create_vars (MonoCompile *cfg)
2016 {
2017         MonoMethodSignature *sig;
2018         CallInfo *cinfo;
2019
2020         sig = mono_method_signature (cfg->method);
2021
2022         if (!cfg->arch.cinfo)
2023                 cfg->arch.cinfo = get_call_info (cfg->generic_sharing_context, cfg->mempool, sig);
2024         cinfo = cfg->arch.cinfo;
2025
2026         if (cinfo->ret.storage == ArgValuetypeInReg)
2027                 cfg->ret_var_is_local = TRUE;
2028
2029         if ((cinfo->ret.storage != ArgValuetypeInReg) && MONO_TYPE_ISSTRUCT (sig->ret)) {
2030                 cfg->vret_addr = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_ARG);
2031                 if (G_UNLIKELY (cfg->verbose_level > 1)) {
2032                         printf ("vret_addr = ");
2033                         mono_print_ins (cfg->vret_addr);
2034                 }
2035         }
2036
2037         if (cfg->gen_seq_points) {
2038                 MonoInst *ins;
2039
2040                 if (cfg->compile_aot) {
2041                         MonoInst *ins = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
2042                         ins->flags |= MONO_INST_VOLATILE;
2043                         cfg->arch.seq_point_info_var = ins;
2044                 }
2045
2046             ins = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
2047                 ins->flags |= MONO_INST_VOLATILE;
2048                 cfg->arch.ss_trigger_page_var = ins;
2049         }
2050
2051 #ifdef MONO_AMD64_NO_PUSHES
2052         /*
2053          * When this is set, we pass arguments on the stack by moves, and by allocating 
2054          * a bigger stack frame, instead of pushes.
2055          * Pushes complicate exception handling because the arguments on the stack have
2056          * to be popped each time a frame is unwound. They also make fp elimination
2057          * impossible.
2058          * FIXME: This doesn't work inside filter/finally clauses, since those execute
2059          * on a new frame which doesn't include a param area.
2060          */
2061         cfg->arch.no_pushes = TRUE;
2062 #endif
2063
2064         if (cfg->method->save_lmf) {
2065                 MonoInst *lmf_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
2066                 lmf_var->flags |= MONO_INST_VOLATILE;
2067                 lmf_var->flags |= MONO_INST_LMF;
2068                 cfg->arch.lmf_var = lmf_var;
2069         }
2070
2071 #ifndef MONO_AMD64_NO_PUSHES
2072         cfg->arch_eh_jit_info = 1;
2073 #endif
2074 }
2075
2076 static void
2077 add_outarg_reg (MonoCompile *cfg, MonoCallInst *call, ArgStorage storage, int reg, MonoInst *tree)
2078 {
2079         MonoInst *ins;
2080
2081         switch (storage) {
2082         case ArgInIReg:
2083                 MONO_INST_NEW (cfg, ins, OP_MOVE);
2084                 ins->dreg = mono_alloc_ireg_copy (cfg, tree->dreg);
2085                 ins->sreg1 = tree->dreg;
2086                 MONO_ADD_INS (cfg->cbb, ins);
2087                 mono_call_inst_add_outarg_reg (cfg, call, ins->dreg, reg, FALSE);
2088                 break;
2089         case ArgInFloatSSEReg:
2090                 MONO_INST_NEW (cfg, ins, OP_AMD64_SET_XMMREG_R4);
2091                 ins->dreg = mono_alloc_freg (cfg);
2092                 ins->sreg1 = tree->dreg;
2093                 MONO_ADD_INS (cfg->cbb, ins);
2094
2095                 mono_call_inst_add_outarg_reg (cfg, call, ins->dreg, reg, TRUE);
2096                 break;
2097         case ArgInDoubleSSEReg:
2098                 MONO_INST_NEW (cfg, ins, OP_FMOVE);
2099                 ins->dreg = mono_alloc_freg (cfg);
2100                 ins->sreg1 = tree->dreg;
2101                 MONO_ADD_INS (cfg->cbb, ins);
2102
2103                 mono_call_inst_add_outarg_reg (cfg, call, ins->dreg, reg, TRUE);
2104
2105                 break;
2106         default:
2107                 g_assert_not_reached ();
2108         }
2109 }
2110
2111 static int
2112 arg_storage_to_load_membase (ArgStorage storage)
2113 {
2114         switch (storage) {
2115         case ArgInIReg:
2116 #if defined(__mono_ilp32__)
2117                 return OP_LOADI8_MEMBASE;
2118 #else
2119                 return OP_LOAD_MEMBASE;
2120 #endif
2121         case ArgInDoubleSSEReg:
2122                 return OP_LOADR8_MEMBASE;
2123         case ArgInFloatSSEReg:
2124                 return OP_LOADR4_MEMBASE;
2125         default:
2126                 g_assert_not_reached ();
2127         }
2128
2129         return -1;
2130 }
2131
2132 static void
2133 emit_sig_cookie (MonoCompile *cfg, MonoCallInst *call, CallInfo *cinfo)
2134 {
2135         MonoInst *arg;
2136         MonoMethodSignature *tmp_sig;
2137         int sig_reg;
2138
2139         if (call->tail_call)
2140                 NOT_IMPLEMENTED;
2141
2142         g_assert (cinfo->sig_cookie.storage == ArgOnStack);
2143                         
2144         /*
2145          * mono_ArgIterator_Setup assumes the signature cookie is 
2146          * passed first and all the arguments which were before it are
2147          * passed on the stack after the signature. So compensate by 
2148          * passing a different signature.
2149          */
2150         tmp_sig = mono_metadata_signature_dup_full (cfg->method->klass->image, call->signature);
2151         tmp_sig->param_count -= call->signature->sentinelpos;
2152         tmp_sig->sentinelpos = 0;
2153         memcpy (tmp_sig->params, call->signature->params + call->signature->sentinelpos, tmp_sig->param_count * sizeof (MonoType*));
2154
2155         sig_reg = mono_alloc_ireg (cfg);
2156         MONO_EMIT_NEW_SIGNATURECONST (cfg, sig_reg, tmp_sig);
2157
2158         if (cfg->arch.no_pushes) {
2159                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, AMD64_RSP, cinfo->sig_cookie.offset, sig_reg);
2160         } else {
2161                 MONO_INST_NEW (cfg, arg, OP_X86_PUSH);
2162                 arg->sreg1 = sig_reg;
2163                 MONO_ADD_INS (cfg->cbb, arg);
2164         }
2165 }
2166
2167 static inline LLVMArgStorage
2168 arg_storage_to_llvm_arg_storage (MonoCompile *cfg, ArgStorage storage)
2169 {
2170         switch (storage) {
2171         case ArgInIReg:
2172                 return LLVMArgInIReg;
2173         case ArgNone:
2174                 return LLVMArgNone;
2175         default:
2176                 g_assert_not_reached ();
2177                 return LLVMArgNone;
2178         }
2179 }
2180
2181 #ifdef ENABLE_LLVM
2182 LLVMCallInfo*
2183 mono_arch_get_llvm_call_info (MonoCompile *cfg, MonoMethodSignature *sig)
2184 {
2185         int i, n;
2186         CallInfo *cinfo;
2187         ArgInfo *ainfo;
2188         int j;
2189         LLVMCallInfo *linfo;
2190         MonoType *t;
2191
2192         n = sig->param_count + sig->hasthis;
2193
2194         cinfo = get_call_info (cfg->generic_sharing_context, cfg->mempool, sig);
2195
2196         linfo = mono_mempool_alloc0 (cfg->mempool, sizeof (LLVMCallInfo) + (sizeof (LLVMArgInfo) * n));
2197
2198         /*
2199          * LLVM always uses the native ABI while we use our own ABI, the
2200          * only difference is the handling of vtypes:
2201          * - we only pass/receive them in registers in some cases, and only 
2202          *   in 1 or 2 integer registers.
2203          */
2204         if (cinfo->ret.storage == ArgValuetypeInReg) {
2205                 if (sig->pinvoke) {
2206                         cfg->exception_message = g_strdup ("pinvoke + vtypes");
2207                         cfg->disable_llvm = TRUE;
2208                         return linfo;
2209                 }
2210
2211                 linfo->ret.storage = LLVMArgVtypeInReg;
2212                 for (j = 0; j < 2; ++j)
2213                         linfo->ret.pair_storage [j] = arg_storage_to_llvm_arg_storage (cfg, cinfo->ret.pair_storage [j]);
2214         }
2215
2216         if (MONO_TYPE_ISSTRUCT (sig->ret) && cinfo->ret.storage == ArgInIReg) {
2217                 /* Vtype returned using a hidden argument */
2218                 linfo->ret.storage = LLVMArgVtypeRetAddr;
2219                 linfo->vret_arg_index = cinfo->vret_arg_index;
2220         }
2221
2222         for (i = 0; i < n; ++i) {
2223                 ainfo = cinfo->args + i;
2224
2225                 if (i >= sig->hasthis)
2226                         t = sig->params [i - sig->hasthis];
2227                 else
2228                         t = &mono_defaults.int_class->byval_arg;
2229
2230                 linfo->args [i].storage = LLVMArgNone;
2231
2232                 switch (ainfo->storage) {
2233                 case ArgInIReg:
2234                         linfo->args [i].storage = LLVMArgInIReg;
2235                         break;
2236                 case ArgInDoubleSSEReg:
2237                 case ArgInFloatSSEReg:
2238                         linfo->args [i].storage = LLVMArgInFPReg;
2239                         break;
2240                 case ArgOnStack:
2241                         if (MONO_TYPE_ISSTRUCT (t)) {
2242                                 linfo->args [i].storage = LLVMArgVtypeByVal;
2243                         } else {
2244                                 linfo->args [i].storage = LLVMArgInIReg;
2245                                 if (!t->byref) {
2246                                         if (t->type == MONO_TYPE_R4)
2247                                                 linfo->args [i].storage = LLVMArgInFPReg;
2248                                         else if (t->type == MONO_TYPE_R8)
2249                                                 linfo->args [i].storage = LLVMArgInFPReg;
2250                                 }
2251                         }
2252                         break;
2253                 case ArgValuetypeInReg:
2254                         if (sig->pinvoke) {
2255                                 cfg->exception_message = g_strdup ("pinvoke + vtypes");
2256                                 cfg->disable_llvm = TRUE;
2257                                 return linfo;
2258                         }
2259
2260                         linfo->args [i].storage = LLVMArgVtypeInReg;
2261                         for (j = 0; j < 2; ++j)
2262                                 linfo->args [i].pair_storage [j] = arg_storage_to_llvm_arg_storage (cfg, ainfo->pair_storage [j]);
2263                         break;
2264                 default:
2265                         cfg->exception_message = g_strdup ("ainfo->storage");
2266                         cfg->disable_llvm = TRUE;
2267                         break;
2268                 }
2269         }
2270
2271         return linfo;
2272 }
2273 #endif
2274
2275 void
2276 mono_arch_emit_call (MonoCompile *cfg, MonoCallInst *call)
2277 {
2278         MonoInst *arg, *in;
2279         MonoMethodSignature *sig;
2280         int i, n, stack_size;
2281         CallInfo *cinfo;
2282         ArgInfo *ainfo;
2283
2284         stack_size = 0;
2285
2286         sig = call->signature;
2287         n = sig->param_count + sig->hasthis;
2288
2289         cinfo = get_call_info (cfg->generic_sharing_context, cfg->mempool, sig);
2290
2291         if (COMPILE_LLVM (cfg)) {
2292                 /* We shouldn't be called in the llvm case */
2293                 cfg->disable_llvm = TRUE;
2294                 return;
2295         }
2296
2297         if (cinfo->need_stack_align) {
2298                 if (!cfg->arch.no_pushes)
2299                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SUB_IMM, X86_ESP, X86_ESP, 8);
2300         }
2301
2302         /* 
2303          * Emit all arguments which are passed on the stack to prevent register
2304          * allocation problems.
2305          */
2306         if (cfg->arch.no_pushes) {
2307                 for (i = 0; i < n; ++i) {
2308                         MonoType *t;
2309                         ainfo = cinfo->args + i;
2310
2311                         in = call->args [i];
2312
2313                         if (sig->hasthis && i == 0)
2314                                 t = &mono_defaults.object_class->byval_arg;
2315                         else
2316                                 t = sig->params [i - sig->hasthis];
2317
2318                         if (ainfo->storage == ArgOnStack && !MONO_TYPE_ISSTRUCT (t) && !call->tail_call) {
2319                                 if (!t->byref) {
2320                                         if (t->type == MONO_TYPE_R4)
2321                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORER4_MEMBASE_REG, AMD64_RSP, ainfo->offset, in->dreg);
2322                                         else if (t->type == MONO_TYPE_R8)
2323                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORER8_MEMBASE_REG, AMD64_RSP, ainfo->offset, in->dreg);
2324                                         else
2325                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, AMD64_RSP, ainfo->offset, in->dreg);
2326                                 } else {
2327                                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, AMD64_RSP, ainfo->offset, in->dreg);
2328                                 }
2329                                 if (cfg->compute_gc_maps) {
2330                                         MonoInst *def;
2331
2332                                         EMIT_NEW_GC_PARAM_SLOT_LIVENESS_DEF (cfg, def, ainfo->offset, t);
2333                                 }
2334                         }
2335                 }
2336         }
2337
2338         /*
2339          * Emit all parameters passed in registers in non-reverse order for better readability
2340          * and to help the optimization in emit_prolog ().
2341          */
2342         for (i = 0; i < n; ++i) {
2343                 ainfo = cinfo->args + i;
2344
2345                 in = call->args [i];
2346
2347                 if (ainfo->storage == ArgInIReg)
2348                         add_outarg_reg (cfg, call, ainfo->storage, ainfo->reg, in);
2349         }
2350
2351         for (i = n - 1; i >= 0; --i) {
2352                 ainfo = cinfo->args + i;
2353
2354                 in = call->args [i];
2355
2356                 switch (ainfo->storage) {
2357                 case ArgInIReg:
2358                         /* Already done */
2359                         break;
2360                 case ArgInFloatSSEReg:
2361                 case ArgInDoubleSSEReg:
2362                         add_outarg_reg (cfg, call, ainfo->storage, ainfo->reg, in);
2363                         break;
2364                 case ArgOnStack:
2365                 case ArgValuetypeInReg:
2366                 case ArgValuetypeAddrInIReg:
2367                         if (ainfo->storage == ArgOnStack && call->tail_call) {
2368                                 MonoInst *call_inst = (MonoInst*)call;
2369                                 cfg->args [i]->flags |= MONO_INST_VOLATILE;
2370                                 EMIT_NEW_ARGSTORE (cfg, call_inst, i, in);
2371                         } else if ((i >= sig->hasthis) && (MONO_TYPE_ISSTRUCT(sig->params [i - sig->hasthis]))) {
2372                                 guint32 align;
2373                                 guint32 size;
2374
2375                                 if (sig->params [i - sig->hasthis]->type == MONO_TYPE_TYPEDBYREF) {
2376                                         size = sizeof (MonoTypedRef);
2377                                         align = sizeof (gpointer);
2378                                 }
2379                                 else {
2380                                         if (sig->pinvoke)
2381                                                 size = mono_type_native_stack_size (&in->klass->byval_arg, &align);
2382                                         else {
2383                                                 /* 
2384                                                  * Other backends use mono_type_stack_size (), but that
2385                                                  * aligns the size to 8, which is larger than the size of
2386                                                  * the source, leading to reads of invalid memory if the
2387                                                  * source is at the end of address space.
2388                                                  */
2389                                                 size = mono_class_value_size (in->klass, &align);
2390                                         }
2391                                 }
2392                                 g_assert (in->klass);
2393
2394                                 if (ainfo->storage == ArgOnStack && size >= 10000) {
2395                                         /* Avoid asserts in emit_memcpy () */
2396                                         cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
2397                                         cfg->exception_message = g_strdup_printf ("Passing an argument of size '%d'.", size);
2398                                         /* Continue normally */
2399                                 }
2400
2401                                 if (size > 0) {
2402                                         MONO_INST_NEW (cfg, arg, OP_OUTARG_VT);
2403                                         arg->sreg1 = in->dreg;
2404                                         arg->klass = in->klass;
2405                                         arg->backend.size = size;
2406                                         arg->inst_p0 = call;
2407                                         arg->inst_p1 = mono_mempool_alloc (cfg->mempool, sizeof (ArgInfo));
2408                                         memcpy (arg->inst_p1, ainfo, sizeof (ArgInfo));
2409
2410                                         MONO_ADD_INS (cfg->cbb, arg);
2411                                 }
2412                         } else {
2413                                 if (cfg->arch.no_pushes) {
2414                                         /* Already done */
2415                                 } else {
2416                                         MONO_INST_NEW (cfg, arg, OP_X86_PUSH);
2417                                         arg->sreg1 = in->dreg;
2418                                         if (!sig->params [i - sig->hasthis]->byref) {
2419                                                 if (sig->params [i - sig->hasthis]->type == MONO_TYPE_R4) {
2420                                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SUB_IMM, X86_ESP, X86_ESP, 8);
2421                                                         arg->opcode = OP_STORER4_MEMBASE_REG;
2422                                                         arg->inst_destbasereg = X86_ESP;
2423                                                         arg->inst_offset = 0;
2424                                                 } else if (sig->params [i - sig->hasthis]->type == MONO_TYPE_R8) {
2425                                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SUB_IMM, X86_ESP, X86_ESP, 8);
2426                                                         arg->opcode = OP_STORER8_MEMBASE_REG;
2427                                                         arg->inst_destbasereg = X86_ESP;
2428                                                         arg->inst_offset = 0;
2429                                                 }
2430                                         }
2431                                         MONO_ADD_INS (cfg->cbb, arg);
2432                                 }
2433                         }
2434                         break;
2435                 default:
2436                         g_assert_not_reached ();
2437                 }
2438
2439                 if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG) && (i == sig->sentinelpos))
2440                         /* Emit the signature cookie just before the implicit arguments */
2441                         emit_sig_cookie (cfg, call, cinfo);
2442         }
2443
2444         /* Handle the case where there are no implicit arguments */
2445         if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG) && (n == sig->sentinelpos))
2446                 emit_sig_cookie (cfg, call, cinfo);
2447
2448         if (sig->ret && MONO_TYPE_ISSTRUCT (sig->ret)) {
2449                 MonoInst *vtarg;
2450
2451                 if (cinfo->ret.storage == ArgValuetypeInReg) {
2452                         if (cinfo->ret.pair_storage [0] == ArgInIReg && cinfo->ret.pair_storage [1] == ArgNone) {
2453                                 /*
2454                                  * Tell the JIT to use a more efficient calling convention: call using
2455                                  * OP_CALL, compute the result location after the call, and save the 
2456                                  * result there.
2457                                  */
2458                                 call->vret_in_reg = TRUE;
2459                                 /* 
2460                                  * Nullify the instruction computing the vret addr to enable 
2461                                  * future optimizations.
2462                                  */
2463                                 if (call->vret_var)
2464                                         NULLIFY_INS (call->vret_var);
2465                         } else {
2466                                 if (call->tail_call)
2467                                         NOT_IMPLEMENTED;
2468                                 /*
2469                                  * The valuetype is in RAX:RDX after the call, need to be copied to
2470                                  * the stack. Push the address here, so the call instruction can
2471                                  * access it.
2472                                  */
2473                                 if (!cfg->arch.vret_addr_loc) {
2474                                         cfg->arch.vret_addr_loc = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
2475                                         /* Prevent it from being register allocated or optimized away */
2476                                         ((MonoInst*)cfg->arch.vret_addr_loc)->flags |= MONO_INST_VOLATILE;
2477                                 }
2478
2479                                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, ((MonoInst*)cfg->arch.vret_addr_loc)->dreg, call->vret_var->dreg);
2480                         }
2481                 }
2482                 else {
2483                         MONO_INST_NEW (cfg, vtarg, OP_MOVE);
2484                         vtarg->sreg1 = call->vret_var->dreg;
2485                         vtarg->dreg = mono_alloc_preg (cfg);
2486                         MONO_ADD_INS (cfg->cbb, vtarg);
2487
2488                         mono_call_inst_add_outarg_reg (cfg, call, vtarg->dreg, cinfo->ret.reg, FALSE);
2489                 }
2490         }
2491
2492 #ifdef HOST_WIN32
2493         if (call->inst.opcode != OP_JMP && OP_TAILCALL != call->inst.opcode) {
2494                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SUB_IMM, X86_ESP, X86_ESP, 0x20);
2495         }
2496 #endif
2497
2498         if (cfg->method->save_lmf) {
2499                 MONO_INST_NEW (cfg, arg, OP_AMD64_SAVE_SP_TO_LMF);
2500                 MONO_ADD_INS (cfg->cbb, arg);
2501         }
2502
2503         call->stack_usage = cinfo->stack_usage;
2504 }
2505
2506 void
2507 mono_arch_emit_outarg_vt (MonoCompile *cfg, MonoInst *ins, MonoInst *src)
2508 {
2509         MonoInst *arg;
2510         MonoCallInst *call = (MonoCallInst*)ins->inst_p0;
2511         ArgInfo *ainfo = (ArgInfo*)ins->inst_p1;
2512         int size = ins->backend.size;
2513
2514         if (ainfo->storage == ArgValuetypeInReg) {
2515                 MonoInst *load;
2516                 int part;
2517
2518                 for (part = 0; part < 2; ++part) {
2519                         if (ainfo->pair_storage [part] == ArgNone)
2520                                 continue;
2521
2522                         MONO_INST_NEW (cfg, load, arg_storage_to_load_membase (ainfo->pair_storage [part]));
2523                         load->inst_basereg = src->dreg;
2524                         load->inst_offset = part * sizeof(mgreg_t);
2525
2526                         switch (ainfo->pair_storage [part]) {
2527                         case ArgInIReg:
2528                                 load->dreg = mono_alloc_ireg (cfg);
2529                                 break;
2530                         case ArgInDoubleSSEReg:
2531                         case ArgInFloatSSEReg:
2532                                 load->dreg = mono_alloc_freg (cfg);
2533                                 break;
2534                         default:
2535                                 g_assert_not_reached ();
2536                         }
2537                         MONO_ADD_INS (cfg->cbb, load);
2538
2539                         add_outarg_reg (cfg, call, ainfo->pair_storage [part], ainfo->pair_regs [part], load);
2540                 }
2541         } else if (ainfo->storage == ArgValuetypeAddrInIReg) {
2542                 MonoInst *vtaddr, *load;
2543                 vtaddr = mono_compile_create_var (cfg, &ins->klass->byval_arg, OP_LOCAL);
2544                 
2545                 g_assert (!cfg->arch.no_pushes);
2546
2547                 MONO_INST_NEW (cfg, load, OP_LDADDR);
2548                 load->inst_p0 = vtaddr;
2549                 vtaddr->flags |= MONO_INST_INDIRECT;
2550                 load->type = STACK_MP;
2551                 load->klass = vtaddr->klass;
2552                 load->dreg = mono_alloc_ireg (cfg);
2553                 MONO_ADD_INS (cfg->cbb, load);
2554                 mini_emit_memcpy (cfg, load->dreg, 0, src->dreg, 0, size, 4);
2555
2556                 if (ainfo->pair_storage [0] == ArgInIReg) {
2557                         MONO_INST_NEW (cfg, arg, OP_X86_LEA_MEMBASE);
2558                         arg->dreg = mono_alloc_ireg (cfg);
2559                         arg->sreg1 = load->dreg;
2560                         arg->inst_imm = 0;
2561                         MONO_ADD_INS (cfg->cbb, arg);
2562                         mono_call_inst_add_outarg_reg (cfg, call, arg->dreg, ainfo->pair_regs [0], FALSE);
2563                 } else {
2564                         MONO_INST_NEW (cfg, arg, OP_X86_PUSH);
2565                         arg->sreg1 = load->dreg;
2566                         MONO_ADD_INS (cfg->cbb, arg);
2567                 }
2568         } else {
2569                 if (size == 8) {
2570                         if (cfg->arch.no_pushes) {
2571                                 int dreg = mono_alloc_ireg (cfg);
2572
2573                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, src->dreg, 0);
2574                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, AMD64_RSP, ainfo->offset, dreg);
2575                         } else {
2576                                 /* Can't use this for < 8 since it does an 8 byte memory load */
2577                                 MONO_INST_NEW (cfg, arg, OP_X86_PUSH_MEMBASE);
2578                                 arg->inst_basereg = src->dreg;
2579                                 arg->inst_offset = 0;
2580                                 MONO_ADD_INS (cfg->cbb, arg);
2581                         }
2582                 } else if (size <= 40) {
2583                         if (cfg->arch.no_pushes) {
2584                                 mini_emit_memcpy (cfg, AMD64_RSP, ainfo->offset, src->dreg, 0, size, 4);
2585                         } else {
2586                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SUB_IMM, X86_ESP, X86_ESP, ALIGN_TO (size, 8));
2587                                 mini_emit_memcpy (cfg, X86_ESP, 0, src->dreg, 0, size, 4);
2588                         }
2589                 } else {
2590                         if (cfg->arch.no_pushes) {
2591                                 // FIXME: Code growth
2592                                 mini_emit_memcpy (cfg, AMD64_RSP, ainfo->offset, src->dreg, 0, size, 4);
2593                         } else {
2594                                 MONO_INST_NEW (cfg, arg, OP_X86_PUSH_OBJ);
2595                                 arg->inst_basereg = src->dreg;
2596                                 arg->inst_offset = 0;
2597                                 arg->inst_imm = size;
2598                                 MONO_ADD_INS (cfg->cbb, arg);
2599                         }
2600                 }
2601
2602                 if (cfg->compute_gc_maps) {
2603                         MonoInst *def;
2604                         EMIT_NEW_GC_PARAM_SLOT_LIVENESS_DEF (cfg, def, ainfo->offset, &ins->klass->byval_arg);
2605                 }
2606         }
2607 }
2608
2609 void
2610 mono_arch_emit_setret (MonoCompile *cfg, MonoMethod *method, MonoInst *val)
2611 {
2612         MonoType *ret = mini_type_get_underlying_type (NULL, mono_method_signature (method)->ret);
2613
2614         if (ret->type == MONO_TYPE_R4) {
2615                 if (COMPILE_LLVM (cfg))
2616                         MONO_EMIT_NEW_UNALU (cfg, OP_FMOVE, cfg->ret->dreg, val->dreg);
2617                 else
2618                         MONO_EMIT_NEW_UNALU (cfg, OP_AMD64_SET_XMMREG_R4, cfg->ret->dreg, val->dreg);
2619                 return;
2620         } else if (ret->type == MONO_TYPE_R8) {
2621                 MONO_EMIT_NEW_UNALU (cfg, OP_FMOVE, cfg->ret->dreg, val->dreg);
2622                 return;
2623         }
2624                         
2625         MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->ret->dreg, val->dreg);
2626 }
2627
2628 #endif /* DISABLE_JIT */
2629
2630 #define EMIT_COND_BRANCH(ins,cond,sign) \
2631         if (ins->inst_true_bb->native_offset) { \
2632                 x86_branch (code, cond, cfg->native_code + ins->inst_true_bb->native_offset, sign); \
2633         } else { \
2634                 mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_BB, ins->inst_true_bb); \
2635                 if ((cfg->opt & MONO_OPT_BRANCH) && \
2636             x86_is_imm8 (ins->inst_true_bb->max_offset - offset)) \
2637                         x86_branch8 (code, cond, 0, sign); \
2638                 else \
2639                         x86_branch32 (code, cond, 0, sign); \
2640 }
2641
2642 typedef struct {
2643         MonoMethodSignature *sig;
2644         CallInfo *cinfo;
2645 } ArchDynCallInfo;
2646
2647 typedef struct {
2648         mgreg_t regs [PARAM_REGS];
2649         mgreg_t res;
2650         guint8 *ret;
2651 } DynCallArgs;
2652
2653 static gboolean
2654 dyn_call_supported (MonoMethodSignature *sig, CallInfo *cinfo)
2655 {
2656         int i;
2657
2658 #ifdef HOST_WIN32
2659         return FALSE;
2660 #endif
2661
2662         switch (cinfo->ret.storage) {
2663         case ArgNone:
2664         case ArgInIReg:
2665                 break;
2666         case ArgValuetypeInReg: {
2667                 ArgInfo *ainfo = &cinfo->ret;
2668
2669                 if (ainfo->pair_storage [0] != ArgNone && ainfo->pair_storage [0] != ArgInIReg)
2670                         return FALSE;
2671                 if (ainfo->pair_storage [1] != ArgNone && ainfo->pair_storage [1] != ArgInIReg)
2672                         return FALSE;
2673                 break;
2674         }
2675         default:
2676                 return FALSE;
2677         }
2678
2679         for (i = 0; i < cinfo->nargs; ++i) {
2680                 ArgInfo *ainfo = &cinfo->args [i];
2681                 switch (ainfo->storage) {
2682                 case ArgInIReg:
2683                         break;
2684                 case ArgValuetypeInReg:
2685                         if (ainfo->pair_storage [0] != ArgNone && ainfo->pair_storage [0] != ArgInIReg)
2686                                 return FALSE;
2687                         if (ainfo->pair_storage [1] != ArgNone && ainfo->pair_storage [1] != ArgInIReg)
2688                                 return FALSE;
2689                         break;
2690                 default:
2691                         return FALSE;
2692                 }
2693         }
2694
2695         return TRUE;
2696 }
2697
2698 /*
2699  * mono_arch_dyn_call_prepare:
2700  *
2701  *   Return a pointer to an arch-specific structure which contains information 
2702  * needed by mono_arch_get_dyn_call_args (). Return NULL if OP_DYN_CALL is not
2703  * supported for SIG.
2704  * This function is equivalent to ffi_prep_cif in libffi.
2705  */
2706 MonoDynCallInfo*
2707 mono_arch_dyn_call_prepare (MonoMethodSignature *sig)
2708 {
2709         ArchDynCallInfo *info;
2710         CallInfo *cinfo;
2711
2712         cinfo = get_call_info (NULL, NULL, sig);
2713
2714         if (!dyn_call_supported (sig, cinfo)) {
2715                 g_free (cinfo);
2716                 return NULL;
2717         }
2718
2719         info = g_new0 (ArchDynCallInfo, 1);
2720         // FIXME: Preprocess the info to speed up get_dyn_call_args ().
2721         info->sig = sig;
2722         info->cinfo = cinfo;
2723         
2724         return (MonoDynCallInfo*)info;
2725 }
2726
2727 /*
2728  * mono_arch_dyn_call_free:
2729  *
2730  *   Free a MonoDynCallInfo structure.
2731  */
2732 void
2733 mono_arch_dyn_call_free (MonoDynCallInfo *info)
2734 {
2735         ArchDynCallInfo *ainfo = (ArchDynCallInfo*)info;
2736
2737         g_free (ainfo->cinfo);
2738         g_free (ainfo);
2739 }
2740
2741 #if !defined(__native_client__)
2742 #define PTR_TO_GREG(ptr) (mgreg_t)(ptr)
2743 #define GREG_TO_PTR(greg) (gpointer)(greg)
2744 #else
2745 /* Correctly handle casts to/from 32-bit pointers without compiler warnings */
2746 #define PTR_TO_GREG(ptr) (mgreg_t)(uintptr_t)(ptr)
2747 #define GREG_TO_PTR(greg) (gpointer)(guint32)(greg)
2748 #endif
2749
2750 /*
2751  * mono_arch_get_start_dyn_call:
2752  *
2753  *   Convert the arguments ARGS to a format which can be passed to OP_DYN_CALL, and
2754  * store the result into BUF.
2755  * ARGS should be an array of pointers pointing to the arguments.
2756  * RET should point to a memory buffer large enought to hold the result of the
2757  * call.
2758  * This function should be as fast as possible, any work which does not depend
2759  * on the actual values of the arguments should be done in 
2760  * mono_arch_dyn_call_prepare ().
2761  * start_dyn_call + OP_DYN_CALL + finish_dyn_call is equivalent to ffi_call in
2762  * libffi.
2763  */
2764 void
2765 mono_arch_start_dyn_call (MonoDynCallInfo *info, gpointer **args, guint8 *ret, guint8 *buf, int buf_len)
2766 {
2767         ArchDynCallInfo *dinfo = (ArchDynCallInfo*)info;
2768         DynCallArgs *p = (DynCallArgs*)buf;
2769         int arg_index, greg, i, pindex;
2770         MonoMethodSignature *sig = dinfo->sig;
2771
2772         g_assert (buf_len >= sizeof (DynCallArgs));
2773
2774         p->res = 0;
2775         p->ret = ret;
2776
2777         arg_index = 0;
2778         greg = 0;
2779         pindex = 0;
2780
2781         if (sig->hasthis || dinfo->cinfo->vret_arg_index == 1) {
2782                 p->regs [greg ++] = PTR_TO_GREG(*(args [arg_index ++]));
2783                 if (!sig->hasthis)
2784                         pindex = 1;
2785         }
2786
2787         if (dinfo->cinfo->vtype_retaddr)
2788                 p->regs [greg ++] = PTR_TO_GREG(ret);
2789
2790         for (i = pindex; i < sig->param_count; i++) {
2791                 MonoType *t = mono_type_get_underlying_type (sig->params [i]);
2792                 gpointer *arg = args [arg_index ++];
2793
2794                 if (t->byref) {
2795                         p->regs [greg ++] = PTR_TO_GREG(*(arg));
2796                         continue;
2797                 }
2798
2799                 switch (t->type) {
2800                 case MONO_TYPE_STRING:
2801                 case MONO_TYPE_CLASS:  
2802                 case MONO_TYPE_ARRAY:
2803                 case MONO_TYPE_SZARRAY:
2804                 case MONO_TYPE_OBJECT:
2805                 case MONO_TYPE_PTR:
2806                 case MONO_TYPE_I:
2807                 case MONO_TYPE_U:
2808 #if !defined(__mono_ilp32__)
2809                 case MONO_TYPE_I8:
2810                 case MONO_TYPE_U8:
2811 #endif
2812                         g_assert (dinfo->cinfo->args [i + sig->hasthis].reg == param_regs [greg]);
2813                         p->regs [greg ++] = PTR_TO_GREG(*(arg));
2814                         break;
2815 #if defined(__mono_ilp32__)
2816                 case MONO_TYPE_I8:
2817                 case MONO_TYPE_U8:
2818                         g_assert (dinfo->cinfo->args [i + sig->hasthis].reg == param_regs [greg]);
2819                         p->regs [greg ++] = *(guint64*)(arg);
2820                         break;
2821 #endif
2822                 case MONO_TYPE_BOOLEAN:
2823                 case MONO_TYPE_U1:
2824                         p->regs [greg ++] = *(guint8*)(arg);
2825                         break;
2826                 case MONO_TYPE_I1:
2827                         p->regs [greg ++] = *(gint8*)(arg);
2828                         break;
2829                 case MONO_TYPE_I2:
2830                         p->regs [greg ++] = *(gint16*)(arg);
2831                         break;
2832                 case MONO_TYPE_U2:
2833                 case MONO_TYPE_CHAR:
2834                         p->regs [greg ++] = *(guint16*)(arg);
2835                         break;
2836                 case MONO_TYPE_I4:
2837                         p->regs [greg ++] = *(gint32*)(arg);
2838                         break;
2839                 case MONO_TYPE_U4:
2840                         p->regs [greg ++] = *(guint32*)(arg);
2841                         break;
2842                 case MONO_TYPE_GENERICINST:
2843                     if (MONO_TYPE_IS_REFERENCE (t)) {
2844                                 p->regs [greg ++] = PTR_TO_GREG(*(arg));
2845                                 break;
2846                         } else {
2847                                 /* Fall through */
2848                         }
2849                 case MONO_TYPE_VALUETYPE: {
2850                         ArgInfo *ainfo = &dinfo->cinfo->args [i + sig->hasthis];
2851
2852                         g_assert (ainfo->storage == ArgValuetypeInReg);
2853                         if (ainfo->pair_storage [0] != ArgNone) {
2854                                 g_assert (ainfo->pair_storage [0] == ArgInIReg);
2855                                 p->regs [greg ++] = ((mgreg_t*)(arg))[0];
2856                         }
2857                         if (ainfo->pair_storage [1] != ArgNone) {
2858                                 g_assert (ainfo->pair_storage [1] == ArgInIReg);
2859                                 p->regs [greg ++] = ((mgreg_t*)(arg))[1];
2860                         }
2861                         break;
2862                 }
2863                 default:
2864                         g_assert_not_reached ();
2865                 }
2866         }
2867
2868         g_assert (greg <= PARAM_REGS);
2869 }
2870
2871 /*
2872  * mono_arch_finish_dyn_call:
2873  *
2874  *   Store the result of a dyn call into the return value buffer passed to
2875  * start_dyn_call ().
2876  * This function should be as fast as possible, any work which does not depend
2877  * on the actual values of the arguments should be done in 
2878  * mono_arch_dyn_call_prepare ().
2879  */
2880 void
2881 mono_arch_finish_dyn_call (MonoDynCallInfo *info, guint8 *buf)
2882 {
2883         ArchDynCallInfo *dinfo = (ArchDynCallInfo*)info;
2884         MonoMethodSignature *sig = dinfo->sig;
2885         guint8 *ret = ((DynCallArgs*)buf)->ret;
2886         mgreg_t res = ((DynCallArgs*)buf)->res;
2887
2888         switch (mono_type_get_underlying_type (sig->ret)->type) {
2889         case MONO_TYPE_VOID:
2890                 *(gpointer*)ret = NULL;
2891                 break;
2892         case MONO_TYPE_STRING:
2893         case MONO_TYPE_CLASS:  
2894         case MONO_TYPE_ARRAY:
2895         case MONO_TYPE_SZARRAY:
2896         case MONO_TYPE_OBJECT:
2897         case MONO_TYPE_I:
2898         case MONO_TYPE_U:
2899         case MONO_TYPE_PTR:
2900                 *(gpointer*)ret = GREG_TO_PTR(res);
2901                 break;
2902         case MONO_TYPE_I1:
2903                 *(gint8*)ret = res;
2904                 break;
2905         case MONO_TYPE_U1:
2906         case MONO_TYPE_BOOLEAN:
2907                 *(guint8*)ret = res;
2908                 break;
2909         case MONO_TYPE_I2:
2910                 *(gint16*)ret = res;
2911                 break;
2912         case MONO_TYPE_U2:
2913         case MONO_TYPE_CHAR:
2914                 *(guint16*)ret = res;
2915                 break;
2916         case MONO_TYPE_I4:
2917                 *(gint32*)ret = res;
2918                 break;
2919         case MONO_TYPE_U4:
2920                 *(guint32*)ret = res;
2921                 break;
2922         case MONO_TYPE_I8:
2923                 *(gint64*)ret = res;
2924                 break;
2925         case MONO_TYPE_U8:
2926                 *(guint64*)ret = res;
2927                 break;
2928         case MONO_TYPE_GENERICINST:
2929                 if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
2930                         *(gpointer*)ret = GREG_TO_PTR(res);
2931                         break;
2932                 } else {
2933                         /* Fall through */
2934                 }
2935         case MONO_TYPE_VALUETYPE:
2936                 if (dinfo->cinfo->vtype_retaddr) {
2937                         /* Nothing to do */
2938                 } else {
2939                         ArgInfo *ainfo = &dinfo->cinfo->ret;
2940
2941                         g_assert (ainfo->storage == ArgValuetypeInReg);
2942
2943                         if (ainfo->pair_storage [0] != ArgNone) {
2944                                 g_assert (ainfo->pair_storage [0] == ArgInIReg);
2945                                 ((mgreg_t*)ret)[0] = res;
2946                         }
2947
2948                         g_assert (ainfo->pair_storage [1] == ArgNone);
2949                 }
2950                 break;
2951         default:
2952                 g_assert_not_reached ();
2953         }
2954 }
2955
2956 /* emit an exception if condition is fail */
2957 #define EMIT_COND_SYSTEM_EXCEPTION(cond,signed,exc_name)            \
2958         do {                                                        \
2959                 MonoInst *tins = mono_branch_optimize_exception_target (cfg, bb, exc_name); \
2960                 if (tins == NULL) {                                                                             \
2961                         mono_add_patch_info (cfg, code - cfg->native_code,   \
2962                                         MONO_PATCH_INFO_EXC, exc_name);  \
2963                         x86_branch32 (code, cond, 0, signed);               \
2964                 } else {        \
2965                         EMIT_COND_BRANCH (tins, cond, signed);  \
2966                 }                       \
2967         } while (0); 
2968
2969 #define EMIT_FPCOMPARE(code) do { \
2970         amd64_fcompp (code); \
2971         amd64_fnstsw (code); \
2972 } while (0); 
2973
2974 #define EMIT_SSE2_FPFUNC(code, op, dreg, sreg1) do { \
2975     amd64_movsd_membase_reg (code, AMD64_RSP, -8, (sreg1)); \
2976         amd64_fld_membase (code, AMD64_RSP, -8, TRUE); \
2977         amd64_ ##op (code); \
2978         amd64_fst_membase (code, AMD64_RSP, -8, TRUE, TRUE); \
2979         amd64_movsd_reg_membase (code, (dreg), AMD64_RSP, -8); \
2980 } while (0);
2981
2982 static guint8*
2983 emit_call_body (MonoCompile *cfg, guint8 *code, guint32 patch_type, gconstpointer data)
2984 {
2985         gboolean no_patch = FALSE;
2986
2987         /* 
2988          * FIXME: Add support for thunks
2989          */
2990         {
2991                 gboolean near_call = FALSE;
2992
2993                 /*
2994                  * Indirect calls are expensive so try to make a near call if possible.
2995                  * The caller memory is allocated by the code manager so it is 
2996                  * guaranteed to be at a 32 bit offset.
2997                  */
2998
2999                 if (patch_type != MONO_PATCH_INFO_ABS) {
3000                         /* The target is in memory allocated using the code manager */
3001                         near_call = TRUE;
3002
3003                         if ((patch_type == MONO_PATCH_INFO_METHOD) || (patch_type == MONO_PATCH_INFO_METHOD_JUMP)) {
3004                                 if (((MonoMethod*)data)->klass->image->aot_module)
3005                                         /* The callee might be an AOT method */
3006                                         near_call = FALSE;
3007                                 if (((MonoMethod*)data)->dynamic)
3008                                         /* The target is in malloc-ed memory */
3009                                         near_call = FALSE;
3010                         }
3011
3012                         if (patch_type == MONO_PATCH_INFO_INTERNAL_METHOD) {
3013                                 /* 
3014                                  * The call might go directly to a native function without
3015                                  * the wrapper.
3016                                  */
3017                                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (data);
3018                                 if (mi) {
3019                                         gconstpointer target = mono_icall_get_wrapper (mi);
3020                                         if ((((guint64)target) >> 32) != 0)
3021                                                 near_call = FALSE;
3022                                 }
3023                         }
3024                 }
3025                 else {
3026                         if (cfg->abs_patches && g_hash_table_lookup (cfg->abs_patches, data)) {
3027                                 /* 
3028                                  * This is not really an optimization, but required because the
3029                                  * generic class init trampolines use R11 to pass the vtable.
3030                                  */
3031                                 near_call = TRUE;
3032                         } else {
3033                                 MonoJitICallInfo *info = mono_find_jit_icall_by_addr (data);
3034                                 if (info) {
3035                                         if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && 
3036                                                 strstr (cfg->method->name, info->name)) {
3037                                                 /* A call to the wrapped function */
3038                                                 if ((((guint64)data) >> 32) == 0)
3039                                                         near_call = TRUE;
3040                                                 no_patch = TRUE;
3041                                         }
3042                                         else if (info->func == info->wrapper) {
3043                                                 /* No wrapper */
3044                                                 if ((((guint64)info->func) >> 32) == 0)
3045                                                         near_call = TRUE;
3046                                         }
3047                                         else {
3048                                                 /* See the comment in mono_codegen () */
3049                                                 if ((info->name [0] != 'v') || (strstr (info->name, "ves_array_new_va_") == NULL && strstr (info->name, "ves_array_element_address_") == NULL))
3050                                                         near_call = TRUE;
3051                                         }
3052                                 }
3053                                 else if ((((guint64)data) >> 32) == 0) {
3054                                         near_call = TRUE;
3055                                         no_patch = TRUE;
3056                                 }
3057                         }
3058                 }
3059
3060                 if (cfg->method->dynamic)
3061                         /* These methods are allocated using malloc */
3062                         near_call = FALSE;
3063
3064 #ifdef MONO_ARCH_NOMAP32BIT
3065                 near_call = FALSE;
3066 #endif
3067
3068                 /* The 64bit XEN kernel does not honour the MAP_32BIT flag. (#522894) */
3069                 if (optimize_for_xen)
3070                         near_call = FALSE;
3071
3072                 if (cfg->compile_aot) {
3073                         near_call = TRUE;
3074                         no_patch = TRUE;
3075                 }
3076
3077                 if (near_call) {
3078                         /* 
3079                          * Align the call displacement to an address divisible by 4 so it does
3080                          * not span cache lines. This is required for code patching to work on SMP
3081                          * systems.
3082                          */
3083                         if (!no_patch && ((guint32)(code + 1 - cfg->native_code) % 4) != 0) {
3084                                 guint32 pad_size = 4 - ((guint32)(code + 1 - cfg->native_code) % 4);
3085                                 amd64_padding (code, pad_size);
3086                         }
3087                         mono_add_patch_info (cfg, code - cfg->native_code, patch_type, data);
3088                         amd64_call_code (code, 0);
3089                 }
3090                 else {
3091                         mono_add_patch_info (cfg, code - cfg->native_code, patch_type, data);
3092                         amd64_set_reg_template (code, GP_SCRATCH_REG);
3093                         amd64_call_reg (code, GP_SCRATCH_REG);
3094                 }
3095         }
3096
3097         return code;
3098 }
3099
3100 static inline guint8*
3101 emit_call (MonoCompile *cfg, guint8 *code, guint32 patch_type, gconstpointer data, gboolean win64_adjust_stack)
3102 {
3103 #ifdef HOST_WIN32
3104         if (win64_adjust_stack)
3105                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 32);
3106 #endif
3107         code = emit_call_body (cfg, code, patch_type, data);
3108 #ifdef HOST_WIN32
3109         if (win64_adjust_stack)
3110                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 32);
3111 #endif  
3112         
3113         return code;
3114 }
3115
3116 static inline int
3117 store_membase_imm_to_store_membase_reg (int opcode)
3118 {
3119         switch (opcode) {
3120         case OP_STORE_MEMBASE_IMM:
3121                 return OP_STORE_MEMBASE_REG;
3122         case OP_STOREI4_MEMBASE_IMM:
3123                 return OP_STOREI4_MEMBASE_REG;
3124         case OP_STOREI8_MEMBASE_IMM:
3125                 return OP_STOREI8_MEMBASE_REG;
3126         }
3127
3128         return -1;
3129 }
3130
3131 #ifndef DISABLE_JIT
3132
3133 #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)))
3134
3135 /*
3136  * mono_arch_peephole_pass_1:
3137  *
3138  *   Perform peephole opts which should/can be performed before local regalloc
3139  */
3140 void
3141 mono_arch_peephole_pass_1 (MonoCompile *cfg, MonoBasicBlock *bb)
3142 {
3143         MonoInst *ins, *n;
3144
3145         MONO_BB_FOR_EACH_INS_SAFE (bb, n, ins) {
3146                 MonoInst *last_ins = ins->prev;
3147
3148                 switch (ins->opcode) {
3149                 case OP_ADD_IMM:
3150                 case OP_IADD_IMM:
3151                 case OP_LADD_IMM:
3152                         if ((ins->sreg1 < MONO_MAX_IREGS) && (ins->dreg >= MONO_MAX_IREGS) && (ins->inst_imm > 0)) {
3153                                 /* 
3154                                  * X86_LEA is like ADD, but doesn't have the
3155                                  * sreg1==dreg restriction. inst_imm > 0 is needed since LEA sign-extends 
3156                                  * its operand to 64 bit.
3157                                  */
3158                                 ins->opcode = OP_X86_LEA_MEMBASE;
3159                                 ins->inst_basereg = ins->sreg1;
3160                         }
3161                         break;
3162                 case OP_LXOR:
3163                 case OP_IXOR:
3164                         if ((ins->sreg1 == ins->sreg2) && (ins->sreg1 == ins->dreg)) {
3165                                 MonoInst *ins2;
3166
3167                                 /* 
3168                                  * Replace STORE_MEMBASE_IMM 0 with STORE_MEMBASE_REG since 
3169                                  * the latter has length 2-3 instead of 6 (reverse constant
3170                                  * propagation). These instruction sequences are very common
3171                                  * in the initlocals bblock.
3172                                  */
3173                                 for (ins2 = ins->next; ins2; ins2 = ins2->next) {
3174                                         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)) {
3175                                                 ins2->opcode = store_membase_imm_to_store_membase_reg (ins2->opcode);
3176                                                 ins2->sreg1 = ins->dreg;
3177                                         } 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)) {
3178                                                 /* Continue */
3179                                         } else if (((ins2->opcode == OP_ICONST) || (ins2->opcode == OP_I8CONST)) && (ins2->dreg == ins->dreg) && (ins2->inst_c0 == 0)) {
3180                                                 NULLIFY_INS (ins2);
3181                                                 /* Continue */
3182                                         } else {
3183                                                 break;
3184                                         }
3185                                 }
3186                         }
3187                         break;
3188                 case OP_COMPARE_IMM:
3189                 case OP_LCOMPARE_IMM:
3190                         /* OP_COMPARE_IMM (reg, 0) 
3191                          * --> 
3192                          * OP_AMD64_TEST_NULL (reg) 
3193                          */
3194                         if (!ins->inst_imm)
3195                                 ins->opcode = OP_AMD64_TEST_NULL;
3196                         break;
3197                 case OP_ICOMPARE_IMM:
3198                         if (!ins->inst_imm)
3199                                 ins->opcode = OP_X86_TEST_NULL;
3200                         break;
3201                 case OP_AMD64_ICOMPARE_MEMBASE_IMM:
3202                         /* 
3203                          * OP_STORE_MEMBASE_REG reg, offset(basereg)
3204                          * OP_X86_COMPARE_MEMBASE_IMM offset(basereg), imm
3205                          * -->
3206                          * OP_STORE_MEMBASE_REG reg, offset(basereg)
3207                          * OP_COMPARE_IMM reg, imm
3208                          *
3209                          * Note: if imm = 0 then OP_COMPARE_IMM replaced with OP_X86_TEST_NULL
3210                          */
3211                         if (last_ins && (last_ins->opcode == OP_STOREI4_MEMBASE_REG) &&
3212                             ins->inst_basereg == last_ins->inst_destbasereg &&
3213                             ins->inst_offset == last_ins->inst_offset) {
3214                                         ins->opcode = OP_ICOMPARE_IMM;
3215                                         ins->sreg1 = last_ins->sreg1;
3216
3217                                         /* check if we can remove cmp reg,0 with test null */
3218                                         if (!ins->inst_imm)
3219                                                 ins->opcode = OP_X86_TEST_NULL;
3220                                 }
3221
3222                         break;
3223                 }
3224
3225                 mono_peephole_ins (bb, ins);
3226         }
3227 }
3228
3229 void
3230 mono_arch_peephole_pass_2 (MonoCompile *cfg, MonoBasicBlock *bb)
3231 {
3232         MonoInst *ins, *n;
3233
3234         MONO_BB_FOR_EACH_INS_SAFE (bb, n, ins) {
3235                 switch (ins->opcode) {
3236                 case OP_ICONST:
3237                 case OP_I8CONST: {
3238                         /* reg = 0 -> XOR (reg, reg) */
3239                         /* XOR sets cflags on x86, so we cant do it always */
3240                         if (ins->inst_c0 == 0 && (!ins->next || (ins->next && INST_IGNORES_CFLAGS (ins->next->opcode)))) {
3241                                 ins->opcode = OP_LXOR;
3242                                 ins->sreg1 = ins->dreg;
3243                                 ins->sreg2 = ins->dreg;
3244                                 /* Fall through */
3245                         } else {
3246                                 break;
3247                         }
3248                 }
3249                 case OP_LXOR:
3250                         /*
3251                          * Use IXOR to avoid a rex prefix if possible. The cpu will sign extend the 
3252                          * 0 result into 64 bits.
3253                          */
3254                         if ((ins->sreg1 == ins->sreg2) && (ins->sreg1 == ins->dreg)) {
3255                                 ins->opcode = OP_IXOR;
3256                         }
3257                         /* Fall through */
3258                 case OP_IXOR:
3259                         if ((ins->sreg1 == ins->sreg2) && (ins->sreg1 == ins->dreg)) {
3260                                 MonoInst *ins2;
3261
3262                                 /* 
3263                                  * Replace STORE_MEMBASE_IMM 0 with STORE_MEMBASE_REG since 
3264                                  * the latter has length 2-3 instead of 6 (reverse constant
3265                                  * propagation). These instruction sequences are very common
3266                                  * in the initlocals bblock.
3267                                  */
3268                                 for (ins2 = ins->next; ins2; ins2 = ins2->next) {
3269                                         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)) {
3270                                                 ins2->opcode = store_membase_imm_to_store_membase_reg (ins2->opcode);
3271                                                 ins2->sreg1 = ins->dreg;
3272                                         } else if ((ins2->opcode == OP_STOREI1_MEMBASE_IMM) || (ins2->opcode == OP_STOREI2_MEMBASE_IMM) || (ins2->opcode == OP_STOREI4_MEMBASE_REG) || (ins2->opcode == OP_STOREI8_MEMBASE_REG) || (ins2->opcode == OP_STORE_MEMBASE_REG) || (ins2->opcode == OP_LIVERANGE_START) || (ins2->opcode == OP_GC_LIVENESS_DEF) || (ins2->opcode == OP_GC_LIVENESS_USE)) {
3273                                                 /* Continue */
3274                                         } else if (((ins2->opcode == OP_ICONST) || (ins2->opcode == OP_I8CONST)) && (ins2->dreg == ins->dreg) && (ins2->inst_c0 == 0)) {
3275                                                 NULLIFY_INS (ins2);
3276                                                 /* Continue */
3277                                         } else {
3278                                                 break;
3279                                         }
3280                                 }
3281                         }
3282                         break;
3283                 case OP_IADD_IMM:
3284                         if ((ins->inst_imm == 1) && (ins->dreg == ins->sreg1))
3285                                 ins->opcode = OP_X86_INC_REG;
3286                         break;
3287                 case OP_ISUB_IMM:
3288                         if ((ins->inst_imm == 1) && (ins->dreg == ins->sreg1))
3289                                 ins->opcode = OP_X86_DEC_REG;
3290                         break;
3291                 }
3292
3293                 mono_peephole_ins (bb, ins);
3294         }
3295 }
3296
3297 #define NEW_INS(cfg,ins,dest,op) do {   \
3298                 MONO_INST_NEW ((cfg), (dest), (op)); \
3299         (dest)->cil_code = (ins)->cil_code; \
3300         mono_bblock_insert_before_ins (bb, ins, (dest)); \
3301         } while (0)
3302
3303 /*
3304  * mono_arch_lowering_pass:
3305  *
3306  *  Converts complex opcodes into simpler ones so that each IR instruction
3307  * corresponds to one machine instruction.
3308  */
3309 void
3310 mono_arch_lowering_pass (MonoCompile *cfg, MonoBasicBlock *bb)
3311 {
3312         MonoInst *ins, *n, *temp;
3313
3314         /*
3315          * FIXME: Need to add more instructions, but the current machine 
3316          * description can't model some parts of the composite instructions like
3317          * cdq.
3318          */
3319         MONO_BB_FOR_EACH_INS_SAFE (bb, n, ins) {
3320                 switch (ins->opcode) {
3321                 case OP_DIV_IMM:
3322                 case OP_REM_IMM:
3323                 case OP_IDIV_IMM:
3324                 case OP_IDIV_UN_IMM:
3325                 case OP_IREM_UN_IMM:
3326                         mono_decompose_op_imm (cfg, bb, ins);
3327                         break;
3328                 case OP_IREM_IMM:
3329                         /* Keep the opcode if we can implement it efficiently */
3330                         if (!((ins->inst_imm > 0) && (mono_is_power_of_two (ins->inst_imm) != -1)))
3331                                 mono_decompose_op_imm (cfg, bb, ins);
3332                         break;
3333                 case OP_COMPARE_IMM:
3334                 case OP_LCOMPARE_IMM:
3335                         if (!amd64_is_imm32 (ins->inst_imm)) {
3336                                 NEW_INS (cfg, ins, temp, OP_I8CONST);
3337                                 temp->inst_c0 = ins->inst_imm;
3338                                 temp->dreg = mono_alloc_ireg (cfg);
3339                                 ins->opcode = OP_COMPARE;
3340                                 ins->sreg2 = temp->dreg;
3341                         }
3342                         break;
3343 #ifndef __mono_ilp32__
3344                 case OP_LOAD_MEMBASE:
3345 #endif
3346                 case OP_LOADI8_MEMBASE:
3347 #ifndef __native_client_codegen__
3348                 /*  Don't generate memindex opcodes (to simplify */
3349                 /*  read sandboxing) */
3350                         if (!amd64_is_imm32 (ins->inst_offset)) {
3351                                 NEW_INS (cfg, ins, temp, OP_I8CONST);
3352                                 temp->inst_c0 = ins->inst_offset;
3353                                 temp->dreg = mono_alloc_ireg (cfg);
3354                                 ins->opcode = OP_AMD64_LOADI8_MEMINDEX;
3355                                 ins->inst_indexreg = temp->dreg;
3356                         }
3357 #endif
3358                         break;
3359 #ifndef __mono_ilp32__
3360                 case OP_STORE_MEMBASE_IMM:
3361 #endif
3362                 case OP_STOREI8_MEMBASE_IMM:
3363                         if (!amd64_is_imm32 (ins->inst_imm)) {
3364                                 NEW_INS (cfg, ins, temp, OP_I8CONST);
3365                                 temp->inst_c0 = ins->inst_imm;
3366                                 temp->dreg = mono_alloc_ireg (cfg);
3367                                 ins->opcode = OP_STOREI8_MEMBASE_REG;
3368                                 ins->sreg1 = temp->dreg;
3369                         }
3370                         break;
3371 #ifdef MONO_ARCH_SIMD_INTRINSICS
3372                 case OP_EXPAND_I1: {
3373                                 int temp_reg1 = mono_alloc_ireg (cfg);
3374                                 int temp_reg2 = mono_alloc_ireg (cfg);
3375                                 int original_reg = ins->sreg1;
3376
3377                                 NEW_INS (cfg, ins, temp, OP_ICONV_TO_U1);
3378                                 temp->sreg1 = original_reg;
3379                                 temp->dreg = temp_reg1;
3380
3381                                 NEW_INS (cfg, ins, temp, OP_SHL_IMM);
3382                                 temp->sreg1 = temp_reg1;
3383                                 temp->dreg = temp_reg2;
3384                                 temp->inst_imm = 8;
3385
3386                                 NEW_INS (cfg, ins, temp, OP_LOR);
3387                                 temp->sreg1 = temp->dreg = temp_reg2;
3388                                 temp->sreg2 = temp_reg1;
3389
3390                                 ins->opcode = OP_EXPAND_I2;
3391                                 ins->sreg1 = temp_reg2;
3392                         }
3393                         break;
3394 #endif
3395                 default:
3396                         break;
3397                 }
3398         }
3399
3400         bb->max_vreg = cfg->next_vreg;
3401 }
3402
3403 static const int 
3404 branch_cc_table [] = {
3405         X86_CC_EQ, X86_CC_GE, X86_CC_GT, X86_CC_LE, X86_CC_LT,
3406         X86_CC_NE, X86_CC_GE, X86_CC_GT, X86_CC_LE, X86_CC_LT,
3407         X86_CC_O, X86_CC_NO, X86_CC_C, X86_CC_NC
3408 };
3409
3410 /* Maps CMP_... constants to X86_CC_... constants */
3411 static const int
3412 cc_table [] = {
3413         X86_CC_EQ, X86_CC_NE, X86_CC_LE, X86_CC_GE, X86_CC_LT, X86_CC_GT,
3414         X86_CC_LE, X86_CC_GE, X86_CC_LT, X86_CC_GT
3415 };
3416
3417 static const int
3418 cc_signed_table [] = {
3419         TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
3420         FALSE, FALSE, FALSE, FALSE
3421 };
3422
3423 /*#include "cprop.c"*/
3424
3425 static unsigned char*
3426 emit_float_to_int (MonoCompile *cfg, guchar *code, int dreg, int sreg, int size, gboolean is_signed)
3427 {
3428         amd64_sse_cvttsd2si_reg_reg (code, dreg, sreg);
3429
3430         if (size == 1)
3431                 amd64_widen_reg (code, dreg, dreg, is_signed, FALSE);
3432         else if (size == 2)
3433                 amd64_widen_reg (code, dreg, dreg, is_signed, TRUE);
3434         return code;
3435 }
3436
3437 static unsigned char*
3438 mono_emit_stack_alloc (MonoCompile *cfg, guchar *code, MonoInst* tree)
3439 {
3440         int sreg = tree->sreg1;
3441         int need_touch = FALSE;
3442
3443 #if defined(HOST_WIN32) || defined(MONO_ARCH_SIGSEGV_ON_ALTSTACK)
3444         if (!tree->flags & MONO_INST_INIT)
3445                 need_touch = TRUE;
3446 #endif
3447
3448         if (need_touch) {
3449                 guint8* br[5];
3450
3451                 /*
3452                  * Under Windows:
3453                  * If requested stack size is larger than one page,
3454                  * perform stack-touch operation
3455                  */
3456                 /*
3457                  * Generate stack probe code.
3458                  * Under Windows, it is necessary to allocate one page at a time,
3459                  * "touching" stack after each successful sub-allocation. This is
3460                  * because of the way stack growth is implemented - there is a
3461                  * guard page before the lowest stack page that is currently commited.
3462                  * Stack normally grows sequentially so OS traps access to the
3463                  * guard page and commits more pages when needed.
3464                  */
3465                 amd64_test_reg_imm (code, sreg, ~0xFFF);
3466                 br[0] = code; x86_branch8 (code, X86_CC_Z, 0, FALSE);
3467
3468                 br[2] = code; /* loop */
3469                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 0x1000);
3470                 amd64_test_membase_reg (code, AMD64_RSP, 0, AMD64_RSP);
3471                 amd64_alu_reg_imm (code, X86_SUB, sreg, 0x1000);
3472                 amd64_alu_reg_imm (code, X86_CMP, sreg, 0x1000);
3473                 br[3] = code; x86_branch8 (code, X86_CC_AE, 0, FALSE);
3474                 amd64_patch (br[3], br[2]);
3475                 amd64_test_reg_reg (code, sreg, sreg);
3476                 br[4] = code; x86_branch8 (code, X86_CC_Z, 0, FALSE);
3477                 amd64_alu_reg_reg (code, X86_SUB, AMD64_RSP, sreg);
3478
3479                 br[1] = code; x86_jump8 (code, 0);
3480
3481                 amd64_patch (br[0], code);
3482                 amd64_alu_reg_reg (code, X86_SUB, AMD64_RSP, sreg);
3483                 amd64_patch (br[1], code);
3484                 amd64_patch (br[4], code);
3485         }
3486         else
3487                 amd64_alu_reg_reg (code, X86_SUB, AMD64_RSP, tree->sreg1);
3488
3489         if (tree->flags & MONO_INST_INIT) {
3490                 int offset = 0;
3491                 if (tree->dreg != AMD64_RAX && sreg != AMD64_RAX) {
3492                         amd64_push_reg (code, AMD64_RAX);
3493                         offset += 8;
3494                 }
3495                 if (tree->dreg != AMD64_RCX && sreg != AMD64_RCX) {
3496                         amd64_push_reg (code, AMD64_RCX);
3497                         offset += 8;
3498                 }
3499                 if (tree->dreg != AMD64_RDI && sreg != AMD64_RDI) {
3500                         amd64_push_reg (code, AMD64_RDI);
3501                         offset += 8;
3502                 }
3503                 
3504                 amd64_shift_reg_imm (code, X86_SHR, sreg, 3);
3505                 if (sreg != AMD64_RCX)
3506                         amd64_mov_reg_reg (code, AMD64_RCX, sreg, 8);
3507                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
3508                                 
3509                 amd64_lea_membase (code, AMD64_RDI, AMD64_RSP, offset);
3510                 if (cfg->param_area && cfg->arch.no_pushes)
3511                         amd64_alu_reg_imm (code, X86_ADD, AMD64_RDI, cfg->param_area);
3512                 amd64_cld (code);
3513 #if defined(__default_codegen__)
3514                 amd64_prefix (code, X86_REP_PREFIX);
3515                 amd64_stosl (code);
3516 #elif defined(__native_client_codegen__)
3517                 /* NaCl stos pseudo-instruction */
3518                 amd64_codegen_pre(code);
3519                 /* First, clear the upper 32 bits of RDI (mov %edi, %edi)  */
3520                 amd64_mov_reg_reg (code, AMD64_RDI, AMD64_RDI, 4);
3521                 /* Add %r15 to %rdi using lea, condition flags unaffected. */
3522                 amd64_lea_memindex_size (code, AMD64_RDI, AMD64_R15, 0, AMD64_RDI, 0, 8);
3523                 amd64_prefix (code, X86_REP_PREFIX);
3524                 amd64_stosl (code);
3525                 amd64_codegen_post(code);
3526 #endif /* __native_client_codegen__ */
3527                 
3528                 if (tree->dreg != AMD64_RDI && sreg != AMD64_RDI)
3529                         amd64_pop_reg (code, AMD64_RDI);
3530                 if (tree->dreg != AMD64_RCX && sreg != AMD64_RCX)
3531                         amd64_pop_reg (code, AMD64_RCX);
3532                 if (tree->dreg != AMD64_RAX && sreg != AMD64_RAX)
3533                         amd64_pop_reg (code, AMD64_RAX);
3534         }
3535         return code;
3536 }
3537
3538 static guint8*
3539 emit_move_return_value (MonoCompile *cfg, MonoInst *ins, guint8 *code)
3540 {
3541         CallInfo *cinfo;
3542         guint32 quad;
3543
3544         /* Move return value to the target register */
3545         /* FIXME: do this in the local reg allocator */
3546         switch (ins->opcode) {
3547         case OP_CALL:
3548         case OP_CALL_REG:
3549         case OP_CALL_MEMBASE:
3550         case OP_LCALL:
3551         case OP_LCALL_REG:
3552         case OP_LCALL_MEMBASE:
3553                 g_assert (ins->dreg == AMD64_RAX);
3554                 break;
3555         case OP_FCALL:
3556         case OP_FCALL_REG:
3557         case OP_FCALL_MEMBASE:
3558                 if (((MonoCallInst*)ins)->signature->ret->type == MONO_TYPE_R4) {
3559                         amd64_sse_cvtss2sd_reg_reg (code, ins->dreg, AMD64_XMM0);
3560                 }
3561                 else {
3562                         if (ins->dreg != AMD64_XMM0)
3563                                 amd64_sse_movsd_reg_reg (code, ins->dreg, AMD64_XMM0);
3564                 }
3565                 break;
3566         case OP_VCALL:
3567         case OP_VCALL_REG:
3568         case OP_VCALL_MEMBASE:
3569         case OP_VCALL2:
3570         case OP_VCALL2_REG:
3571         case OP_VCALL2_MEMBASE:
3572                 cinfo = get_call_info (cfg->generic_sharing_context, cfg->mempool, ((MonoCallInst*)ins)->signature);
3573                 if (cinfo->ret.storage == ArgValuetypeInReg) {
3574                         MonoInst *loc = cfg->arch.vret_addr_loc;
3575
3576                         /* Load the destination address */
3577                         g_assert (loc->opcode == OP_REGOFFSET);
3578                         amd64_mov_reg_membase (code, AMD64_RCX, loc->inst_basereg, loc->inst_offset, sizeof(gpointer));
3579
3580                         for (quad = 0; quad < 2; quad ++) {
3581                                 switch (cinfo->ret.pair_storage [quad]) {
3582                                 case ArgInIReg:
3583                                         amd64_mov_membase_reg (code, AMD64_RCX, (quad * sizeof(mgreg_t)), cinfo->ret.pair_regs [quad], sizeof(mgreg_t));
3584                                         break;
3585                                 case ArgInFloatSSEReg:
3586                                         amd64_movss_membase_reg (code, AMD64_RCX, (quad * 8), cinfo->ret.pair_regs [quad]);
3587                                         break;
3588                                 case ArgInDoubleSSEReg:
3589                                         amd64_movsd_membase_reg (code, AMD64_RCX, (quad * 8), cinfo->ret.pair_regs [quad]);
3590                                         break;
3591                                 case ArgNone:
3592                                         break;
3593                                 default:
3594                                         NOT_IMPLEMENTED;
3595                                 }
3596                         }
3597                 }
3598                 break;
3599         }
3600
3601         return code;
3602 }
3603
3604 #endif /* DISABLE_JIT */
3605
3606 #ifdef __APPLE__
3607 static int tls_gs_offset;
3608 #endif
3609
3610 gboolean
3611 mono_amd64_have_tls_get (void)
3612 {
3613 #ifdef __APPLE__
3614         static gboolean have_tls_get = FALSE;
3615         static gboolean inited = FALSE;
3616
3617         if (inited)
3618                 return have_tls_get;
3619
3620         guint8 *ins = (guint8*)pthread_getspecific;
3621
3622         /*
3623          * We're looking for these two instructions:
3624          *
3625          * mov    %gs:[offset](,%rdi,8),%rax
3626          * retq
3627          */
3628         have_tls_get = ins [0] == 0x65 &&
3629                        ins [1] == 0x48 &&
3630                        ins [2] == 0x8b &&
3631                        ins [3] == 0x04 &&
3632                        ins [4] == 0xfd &&
3633                        ins [6] == 0x00 &&
3634                        ins [7] == 0x00 &&
3635                        ins [8] == 0x00 &&
3636                        ins [9] == 0xc3;
3637
3638         inited = TRUE;
3639
3640         tls_gs_offset = ins[5];
3641
3642         return have_tls_get;
3643 #else
3644         return TRUE;
3645 #endif
3646 }
3647
3648 /*
3649  * mono_amd64_emit_tls_get:
3650  * @code: buffer to store code to
3651  * @dreg: hard register where to place the result
3652  * @tls_offset: offset info
3653  *
3654  * mono_amd64_emit_tls_get emits in @code the native code that puts in
3655  * the dreg register the item in the thread local storage identified
3656  * by tls_offset.
3657  *
3658  * Returns: a pointer to the end of the stored code
3659  */
3660 guint8*
3661 mono_amd64_emit_tls_get (guint8* code, int dreg, int tls_offset)
3662 {
3663 #ifdef HOST_WIN32
3664         g_assert (tls_offset < 64);
3665         x86_prefix (code, X86_GS_PREFIX);
3666         amd64_mov_reg_mem (code, dreg, (tls_offset * 8) + 0x1480, 8);
3667 #elif defined(__APPLE__)
3668         x86_prefix (code, X86_GS_PREFIX);
3669         amd64_mov_reg_mem (code, dreg, tls_gs_offset + (tls_offset * 8), 8);
3670 #else
3671         if (optimize_for_xen) {
3672                 x86_prefix (code, X86_FS_PREFIX);
3673                 amd64_mov_reg_mem (code, dreg, 0, 8);
3674                 amd64_mov_reg_membase (code, dreg, dreg, tls_offset, 8);
3675         } else {
3676                 x86_prefix (code, X86_FS_PREFIX);
3677                 amd64_mov_reg_mem (code, dreg, tls_offset, 8);
3678         }
3679 #endif
3680         return code;
3681 }
3682
3683 /*
3684  * emit_setup_lmf:
3685  *
3686  *   Emit code to initialize an LMF structure at LMF_OFFSET.
3687  */
3688 static guint8*
3689 emit_setup_lmf (MonoCompile *cfg, guint8 *code, gint32 lmf_offset, int cfa_offset)
3690 {
3691         int i;
3692
3693         /* 
3694          * The ip field is not set, the exception handling code will obtain it from the stack location pointed to by the sp field.
3695          */
3696         /* 
3697          * sp is saved right before calls but we need to save it here too so
3698          * async stack walks would work.
3699          */
3700         amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rsp), AMD64_RSP, 8);
3701         /* Skip method (only needed for trampoline LMF frames) */
3702         /* Save callee saved regs */
3703         for (i = 0; i < MONO_MAX_IREGS; ++i) {
3704                 int offset;
3705
3706                 switch (i) {
3707                 case AMD64_RBX: offset = G_STRUCT_OFFSET (MonoLMF, rbx); break;
3708                 case AMD64_RBP: offset = G_STRUCT_OFFSET (MonoLMF, rbp); break;
3709                 case AMD64_R12: offset = G_STRUCT_OFFSET (MonoLMF, r12); break;
3710                 case AMD64_R13: offset = G_STRUCT_OFFSET (MonoLMF, r13); break;
3711                 case AMD64_R14: offset = G_STRUCT_OFFSET (MonoLMF, r14); break;
3712 #ifndef __native_client_codegen__
3713                 case AMD64_R15: offset = G_STRUCT_OFFSET (MonoLMF, r15); break;
3714 #endif
3715 #ifdef HOST_WIN32
3716                 case AMD64_RDI: offset = G_STRUCT_OFFSET (MonoLMF, rdi); break;
3717                 case AMD64_RSI: offset = G_STRUCT_OFFSET (MonoLMF, rsi); break;
3718 #endif
3719                 default:
3720                         offset = -1;
3721                         break;
3722                 }
3723
3724                 if (offset != -1) {
3725                         amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + offset, i, 8);
3726                         if ((cfg->arch.omit_fp || (i != AMD64_RBP)) && cfa_offset != -1)
3727                                 mono_emit_unwind_op_offset (cfg, code, i, - (cfa_offset - (lmf_offset + offset)));
3728                 }
3729         }
3730
3731         /* These can't contain refs */
3732         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), SLOT_NOREF);
3733         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, lmf_addr), SLOT_NOREF);
3734         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, method), SLOT_NOREF);
3735         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rip), SLOT_NOREF);
3736         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rsp), SLOT_NOREF);
3737
3738         /* These are handled automatically by the stack marking code */
3739         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbx), SLOT_NOREF);
3740         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbp), SLOT_NOREF);
3741         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r12), SLOT_NOREF);
3742         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r13), SLOT_NOREF);
3743         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r14), SLOT_NOREF);
3744         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r15), SLOT_NOREF);
3745 #ifdef HOST_WIN32
3746         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rdi), SLOT_NOREF);
3747         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rsi), SLOT_NOREF);
3748 #endif
3749
3750         return code;
3751 }
3752
3753 /*
3754  * emit_save_lmf:
3755  *
3756  *   Emit code to push an LMF structure on the LMF stack.
3757  */
3758 static guint8*
3759 emit_save_lmf (MonoCompile *cfg, guint8 *code, gint32 lmf_offset, gboolean *args_clobbered)
3760 {
3761         if ((lmf_tls_offset != -1) && !optimize_for_xen) {
3762                 /*
3763                  * Optimized version which uses the mono_lmf TLS variable instead of 
3764                  * indirection through the mono_lmf_addr TLS variable.
3765                  */
3766                 /* %rax = previous_lmf */
3767                 x86_prefix (code, X86_FS_PREFIX);
3768                 amd64_mov_reg_mem (code, AMD64_RAX, lmf_tls_offset, 8);
3769
3770                 /* Save previous_lmf */
3771                 amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), AMD64_RAX, 8);
3772                 /* Set new lmf */
3773                 if (lmf_offset == 0) {
3774                         x86_prefix (code, X86_FS_PREFIX);
3775                         amd64_mov_mem_reg (code, lmf_tls_offset, cfg->frame_reg, 8);
3776                 } else {
3777                         amd64_lea_membase (code, AMD64_R11, cfg->frame_reg, lmf_offset);
3778                         x86_prefix (code, X86_FS_PREFIX);
3779                         amd64_mov_mem_reg (code, lmf_tls_offset, AMD64_R11, 8);
3780                 }
3781         } else {
3782                 if (lmf_addr_tls_offset != -1) {
3783                         /* Load lmf quicky using the FS register */
3784                         code = mono_amd64_emit_tls_get (code, AMD64_RAX, lmf_addr_tls_offset);
3785 #ifdef HOST_WIN32
3786                         /* The TLS key actually contains a pointer to the MonoJitTlsData structure */
3787                         /* FIXME: Add a separate key for LMF to avoid this */
3788                         amd64_alu_reg_imm (code, X86_ADD, AMD64_RAX, G_STRUCT_OFFSET (MonoJitTlsData, lmf));
3789 #endif
3790                 }
3791                 else {
3792                         /* 
3793                          * The call might clobber argument registers, but they are already
3794                          * saved to the stack/global regs.
3795                          */
3796                         if (args_clobbered)
3797                                 *args_clobbered = TRUE;
3798                         code = emit_call (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD, 
3799                                                           (gpointer)"mono_get_lmf_addr", TRUE);         
3800                 }
3801
3802                 /* Save lmf_addr */
3803                 amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, lmf_addr), AMD64_RAX, sizeof(gpointer));
3804                 /* Save previous_lmf */
3805                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RAX, 0, sizeof(gpointer));
3806                 amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), AMD64_R11, sizeof(gpointer));
3807                 /* Set new lmf */
3808                 amd64_lea_membase (code, AMD64_R11, cfg->frame_reg, lmf_offset);
3809                 amd64_mov_membase_reg (code, AMD64_RAX, 0, AMD64_R11, sizeof(gpointer));
3810         }
3811
3812         return code;
3813 }
3814
3815 /*
3816  * emit_save_lmf:
3817  *
3818  *   Emit code to pop an LMF structure from the LMF stack.
3819  */
3820 static guint8*
3821 emit_restore_lmf (MonoCompile *cfg, guint8 *code, gint32 lmf_offset)
3822 {
3823         if ((lmf_tls_offset != -1) && !optimize_for_xen) {
3824                 /*
3825                  * Optimized version which uses the mono_lmf TLS variable instead of indirection
3826                  * through the mono_lmf_addr TLS variable.
3827                  */
3828                 /* reg = previous_lmf */
3829                 amd64_mov_reg_membase (code, AMD64_R11, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), sizeof(gpointer));
3830                 x86_prefix (code, X86_FS_PREFIX);
3831                 amd64_mov_mem_reg (code, lmf_tls_offset, AMD64_R11, 8);
3832         } else {
3833                 /* Restore previous lmf */
3834                 amd64_mov_reg_membase (code, AMD64_RCX, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), sizeof(gpointer));
3835                 amd64_mov_reg_membase (code, AMD64_R11, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, lmf_addr), sizeof(gpointer));
3836                 amd64_mov_membase_reg (code, AMD64_R11, 0, AMD64_RCX, sizeof(gpointer));
3837         }
3838
3839         return code;
3840 }
3841
3842 #define REAL_PRINT_REG(text,reg) \
3843 mono_assert (reg >= 0); \
3844 amd64_push_reg (code, AMD64_RAX); \
3845 amd64_push_reg (code, AMD64_RDX); \
3846 amd64_push_reg (code, AMD64_RCX); \
3847 amd64_push_reg (code, reg); \
3848 amd64_push_imm (code, reg); \
3849 amd64_push_imm (code, text " %d %p\n"); \
3850 amd64_mov_reg_imm (code, AMD64_RAX, printf); \
3851 amd64_call_reg (code, AMD64_RAX); \
3852 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 3*4); \
3853 amd64_pop_reg (code, AMD64_RCX); \
3854 amd64_pop_reg (code, AMD64_RDX); \
3855 amd64_pop_reg (code, AMD64_RAX);
3856
3857 /* benchmark and set based on cpu */
3858 #define LOOP_ALIGNMENT 8
3859 #define bb_is_loop_start(bb) ((bb)->loop_body_start && (bb)->nesting)
3860
3861 #ifndef DISABLE_JIT
3862
3863 #if defined(__native_client__) || defined(__native_client_codegen__)
3864 void mono_nacl_gc()
3865 {
3866 #ifdef __native_client_gc__
3867         __nacl_suspend_thread_if_needed();
3868 #endif
3869 }
3870 #endif
3871
3872 void
3873 mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb)
3874 {
3875         MonoInst *ins;
3876         MonoCallInst *call;
3877         guint offset;
3878         guint8 *code = cfg->native_code + cfg->code_len;
3879         MonoInst *last_ins = NULL;
3880         guint last_offset = 0;
3881         int max_len;
3882
3883         /* Fix max_offset estimate for each successor bb */
3884         if (cfg->opt & MONO_OPT_BRANCH) {
3885                 int current_offset = cfg->code_len;
3886                 MonoBasicBlock *current_bb;
3887                 for (current_bb = bb; current_bb != NULL; current_bb = current_bb->next_bb) {
3888                         current_bb->max_offset = current_offset;
3889                         current_offset += current_bb->max_length;
3890                 }
3891         }
3892
3893         if (cfg->opt & MONO_OPT_LOOP) {
3894                 int pad, align = LOOP_ALIGNMENT;
3895                 /* set alignment depending on cpu */
3896                 if (bb_is_loop_start (bb) && (pad = (cfg->code_len & (align - 1)))) {
3897                         pad = align - pad;
3898                         /*g_print ("adding %d pad at %x to loop in %s\n", pad, cfg->code_len, cfg->method->name);*/
3899                         amd64_padding (code, pad);
3900                         cfg->code_len += pad;
3901                         bb->native_offset = cfg->code_len;
3902                 }
3903         }
3904
3905 #if defined(__native_client_codegen__)
3906         /* For Native Client, all indirect call/jump targets must be */
3907         /* 32-byte aligned.  Exception handler blocks are jumped to  */
3908         /* indirectly as well.                                       */
3909         gboolean bb_needs_alignment = (bb->flags & BB_INDIRECT_JUMP_TARGET) ||
3910                                       (bb->flags & BB_EXCEPTION_HANDLER);
3911
3912         if ( bb_needs_alignment && ((cfg->code_len & kNaClAlignmentMask) != 0)) {
3913                 int pad = kNaClAlignment - (cfg->code_len & kNaClAlignmentMask);
3914                 if (pad != kNaClAlignment) code = mono_arch_nacl_pad(code, pad);
3915                 cfg->code_len += pad;
3916                 bb->native_offset = cfg->code_len;
3917         }
3918 #endif  /*__native_client_codegen__*/
3919
3920         if (cfg->verbose_level > 2)
3921                 g_print ("Basic block %d starting at offset 0x%x\n", bb->block_num, bb->native_offset);
3922
3923         if (cfg->prof_options & MONO_PROFILE_COVERAGE) {
3924                 MonoProfileCoverageInfo *cov = cfg->coverage_info;
3925                 g_assert (!cfg->compile_aot);
3926
3927                 cov->data [bb->dfn].cil_code = bb->cil_code;
3928                 amd64_mov_reg_imm (code, AMD64_R11, (guint64)&cov->data [bb->dfn].count);
3929                 /* this is not thread save, but good enough */
3930                 amd64_inc_membase (code, AMD64_R11, 0);
3931         }
3932
3933         offset = code - cfg->native_code;
3934
3935         mono_debug_open_block (cfg, bb, offset);
3936
3937     if (mono_break_at_bb_method && mono_method_desc_full_match (mono_break_at_bb_method, cfg->method) && bb->block_num == mono_break_at_bb_bb_num)
3938                 x86_breakpoint (code);
3939
3940         MONO_BB_FOR_EACH_INS (bb, ins) {
3941                 offset = code - cfg->native_code;
3942
3943                 max_len = ((guint8 *)ins_get_spec (ins->opcode))[MONO_INST_LEN];
3944
3945 #define EXTRA_CODE_SPACE (NACL_SIZE (16, 16 + kNaClAlignment))
3946
3947                 if (G_UNLIKELY (offset > (cfg->code_size - max_len - EXTRA_CODE_SPACE))) {
3948                         cfg->code_size *= 2;
3949                         cfg->native_code = mono_realloc_native_code(cfg);
3950                         code = cfg->native_code + offset;
3951                         cfg->stat_code_reallocs++;
3952                 }
3953
3954                 if (cfg->debug_info)
3955                         mono_debug_record_line_number (cfg, ins, offset);
3956
3957                 switch (ins->opcode) {
3958                 case OP_BIGMUL:
3959                         amd64_mul_reg (code, ins->sreg2, TRUE);
3960                         break;
3961                 case OP_BIGMUL_UN:
3962                         amd64_mul_reg (code, ins->sreg2, FALSE);
3963                         break;
3964                 case OP_X86_SETEQ_MEMBASE:
3965                         amd64_set_membase (code, X86_CC_EQ, ins->inst_basereg, ins->inst_offset, TRUE);
3966                         break;
3967                 case OP_STOREI1_MEMBASE_IMM:
3968                         amd64_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 1);
3969                         break;
3970                 case OP_STOREI2_MEMBASE_IMM:
3971                         amd64_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 2);
3972                         break;
3973                 case OP_STOREI4_MEMBASE_IMM:
3974                         amd64_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 4);
3975                         break;
3976                 case OP_STOREI1_MEMBASE_REG:
3977                         amd64_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 1);
3978                         break;
3979                 case OP_STOREI2_MEMBASE_REG:
3980                         amd64_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 2);
3981                         break;
3982                 /* In AMD64 NaCl, pointers are 4 bytes, */
3983                 /*  so STORE_* != STOREI8_*. Likewise below. */
3984                 case OP_STORE_MEMBASE_REG:
3985                         amd64_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, sizeof(gpointer));
3986                         break;
3987                 case OP_STOREI8_MEMBASE_REG:
3988                         amd64_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 8);
3989                         break;
3990                 case OP_STOREI4_MEMBASE_REG:
3991                         amd64_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 4);
3992                         break;
3993                 case OP_STORE_MEMBASE_IMM:
3994 #ifndef __native_client_codegen__
3995                         /* In NaCl, this could be a PCONST type, which could */
3996                         /* mean a pointer type was copied directly into the  */
3997                         /* lower 32-bits of inst_imm, so for InvalidPtr==-1  */
3998                         /* the value would be 0x00000000FFFFFFFF which is    */
3999                         /* not proper for an imm32 unless you cast it.       */
4000                         g_assert (amd64_is_imm32 (ins->inst_imm));
4001 #endif
4002                         amd64_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, (gint32)ins->inst_imm, sizeof(gpointer));
4003                         break;
4004                 case OP_STOREI8_MEMBASE_IMM:
4005                         g_assert (amd64_is_imm32 (ins->inst_imm));
4006                         amd64_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 8);
4007                         break;
4008                 case OP_LOAD_MEM:
4009 #ifdef __mono_ilp32__
4010                         /* In ILP32, pointers are 4 bytes, so separate these */
4011                         /* cases, use literal 8 below where we really want 8 */
4012                         amd64_mov_reg_imm (code, ins->dreg, ins->inst_imm);
4013                         amd64_mov_reg_membase (code, ins->dreg, ins->dreg, 0, sizeof(gpointer));
4014                         break;
4015 #endif
4016                 case OP_LOADI8_MEM:
4017                         // FIXME: Decompose this earlier
4018                         if (amd64_is_imm32 (ins->inst_imm))
4019                                 amd64_mov_reg_mem (code, ins->dreg, ins->inst_imm, 8);
4020                         else {
4021                                 amd64_mov_reg_imm (code, ins->dreg, ins->inst_imm);
4022                                 amd64_mov_reg_membase (code, ins->dreg, ins->dreg, 0, 8);
4023                         }
4024                         break;
4025                 case OP_LOADI4_MEM:
4026                         amd64_mov_reg_imm (code, ins->dreg, ins->inst_imm);
4027                         amd64_movsxd_reg_membase (code, ins->dreg, ins->dreg, 0);
4028                         break;
4029                 case OP_LOADU4_MEM:
4030                         // FIXME: Decompose this earlier
4031                         if (amd64_is_imm32 (ins->inst_imm))
4032                                 amd64_mov_reg_mem (code, ins->dreg, ins->inst_imm, 4);
4033                         else {
4034                                 amd64_mov_reg_imm (code, ins->dreg, ins->inst_imm);
4035                                 amd64_mov_reg_membase (code, ins->dreg, ins->dreg, 0, 4);
4036                         }
4037                         break;
4038                 case OP_LOADU1_MEM:
4039                         amd64_mov_reg_imm (code, ins->dreg, ins->inst_imm);
4040                         amd64_widen_membase (code, ins->dreg, ins->dreg, 0, FALSE, FALSE);
4041                         break;
4042                 case OP_LOADU2_MEM:
4043                         /* For NaCl, pointers are 4 bytes, so separate these */
4044                         /* cases, use literal 8 below where we really want 8 */
4045                         amd64_mov_reg_imm (code, ins->dreg, ins->inst_imm);
4046                         amd64_widen_membase (code, ins->dreg, ins->dreg, 0, FALSE, TRUE);
4047                         break;
4048                 case OP_LOAD_MEMBASE:
4049                         g_assert (amd64_is_imm32 (ins->inst_offset));
4050                         amd64_mov_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, sizeof(gpointer));
4051                         break;
4052                 case OP_LOADI8_MEMBASE:
4053                         /* Use literal 8 instead of sizeof pointer or */
4054                         /* register, we really want 8 for this opcode */
4055                         g_assert (amd64_is_imm32 (ins->inst_offset));
4056                         amd64_mov_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, 8);
4057                         break;
4058                 case OP_LOADI4_MEMBASE:
4059                         amd64_movsxd_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset);
4060                         break;
4061                 case OP_LOADU4_MEMBASE:
4062                         amd64_mov_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, 4);
4063                         break;
4064                 case OP_LOADU1_MEMBASE:
4065                         /* The cpu zero extends the result into 64 bits */
4066                         amd64_widen_membase_size (code, ins->dreg, ins->inst_basereg, ins->inst_offset, FALSE, FALSE, 4);
4067                         break;
4068                 case OP_LOADI1_MEMBASE:
4069                         amd64_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, TRUE, FALSE);
4070                         break;
4071                 case OP_LOADU2_MEMBASE:
4072                         /* The cpu zero extends the result into 64 bits */
4073                         amd64_widen_membase_size (code, ins->dreg, ins->inst_basereg, ins->inst_offset, FALSE, TRUE, 4);
4074                         break;
4075                 case OP_LOADI2_MEMBASE:
4076                         amd64_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, TRUE, TRUE);
4077                         break;
4078                 case OP_AMD64_LOADI8_MEMINDEX:
4079                         amd64_mov_reg_memindex_size (code, ins->dreg, ins->inst_basereg, 0, ins->inst_indexreg, 0, 8);
4080                         break;
4081                 case OP_LCONV_TO_I1:
4082                 case OP_ICONV_TO_I1:
4083                 case OP_SEXT_I1:
4084                         amd64_widen_reg (code, ins->dreg, ins->sreg1, TRUE, FALSE);
4085                         break;
4086                 case OP_LCONV_TO_I2:
4087                 case OP_ICONV_TO_I2:
4088                 case OP_SEXT_I2:
4089                         amd64_widen_reg (code, ins->dreg, ins->sreg1, TRUE, TRUE);
4090                         break;
4091                 case OP_LCONV_TO_U1:
4092                 case OP_ICONV_TO_U1:
4093                         amd64_widen_reg (code, ins->dreg, ins->sreg1, FALSE, FALSE);
4094                         break;
4095                 case OP_LCONV_TO_U2:
4096                 case OP_ICONV_TO_U2:
4097                         amd64_widen_reg (code, ins->dreg, ins->sreg1, FALSE, TRUE);
4098                         break;
4099                 case OP_ZEXT_I4:
4100                         /* Clean out the upper word */
4101                         amd64_mov_reg_reg_size (code, ins->dreg, ins->sreg1, 4);
4102                         break;
4103                 case OP_SEXT_I4:
4104                         amd64_movsxd_reg_reg (code, ins->dreg, ins->sreg1);
4105                         break;
4106                 case OP_COMPARE:
4107                 case OP_LCOMPARE:
4108                         amd64_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2);
4109                         break;
4110                 case OP_COMPARE_IMM:
4111                 case OP_LCOMPARE_IMM:
4112                         g_assert (amd64_is_imm32 (ins->inst_imm));
4113                         amd64_alu_reg_imm (code, X86_CMP, ins->sreg1, ins->inst_imm);
4114                         break;
4115                 case OP_X86_COMPARE_REG_MEMBASE:
4116                         amd64_alu_reg_membase (code, X86_CMP, ins->sreg1, ins->sreg2, ins->inst_offset);
4117                         break;
4118                 case OP_X86_TEST_NULL:
4119                         amd64_test_reg_reg_size (code, ins->sreg1, ins->sreg1, 4);
4120                         break;
4121                 case OP_AMD64_TEST_NULL:
4122                         amd64_test_reg_reg (code, ins->sreg1, ins->sreg1);
4123                         break;
4124
4125                 case OP_X86_ADD_REG_MEMBASE:
4126                         amd64_alu_reg_membase_size (code, X86_ADD, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
4127                         break;
4128                 case OP_X86_SUB_REG_MEMBASE:
4129                         amd64_alu_reg_membase_size (code, X86_SUB, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
4130                         break;
4131                 case OP_X86_AND_REG_MEMBASE:
4132                         amd64_alu_reg_membase_size (code, X86_AND, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
4133                         break;
4134                 case OP_X86_OR_REG_MEMBASE:
4135                         amd64_alu_reg_membase_size (code, X86_OR, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
4136                         break;
4137                 case OP_X86_XOR_REG_MEMBASE:
4138                         amd64_alu_reg_membase_size (code, X86_XOR, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
4139                         break;
4140
4141                 case OP_X86_ADD_MEMBASE_IMM:
4142                         /* FIXME: Make a 64 version too */
4143                         amd64_alu_membase_imm_size (code, X86_ADD, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
4144                         break;
4145                 case OP_X86_SUB_MEMBASE_IMM:
4146                         g_assert (amd64_is_imm32 (ins->inst_imm));
4147                         amd64_alu_membase_imm_size (code, X86_SUB, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
4148                         break;
4149                 case OP_X86_AND_MEMBASE_IMM:
4150                         g_assert (amd64_is_imm32 (ins->inst_imm));
4151                         amd64_alu_membase_imm_size (code, X86_AND, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
4152                         break;
4153                 case OP_X86_OR_MEMBASE_IMM:
4154                         g_assert (amd64_is_imm32 (ins->inst_imm));
4155                         amd64_alu_membase_imm_size (code, X86_OR, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
4156                         break;
4157                 case OP_X86_XOR_MEMBASE_IMM:
4158                         g_assert (amd64_is_imm32 (ins->inst_imm));
4159                         amd64_alu_membase_imm_size (code, X86_XOR, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
4160                         break;
4161                 case OP_X86_ADD_MEMBASE_REG:
4162                         amd64_alu_membase_reg_size (code, X86_ADD, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
4163                         break;
4164                 case OP_X86_SUB_MEMBASE_REG:
4165                         amd64_alu_membase_reg_size (code, X86_SUB, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
4166                         break;
4167                 case OP_X86_AND_MEMBASE_REG:
4168                         amd64_alu_membase_reg_size (code, X86_AND, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
4169                         break;
4170                 case OP_X86_OR_MEMBASE_REG:
4171                         amd64_alu_membase_reg_size (code, X86_OR, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
4172                         break;
4173                 case OP_X86_XOR_MEMBASE_REG:
4174                         amd64_alu_membase_reg_size (code, X86_XOR, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
4175                         break;
4176                 case OP_X86_INC_MEMBASE:
4177                         amd64_inc_membase_size (code, ins->inst_basereg, ins->inst_offset, 4);
4178                         break;
4179                 case OP_X86_INC_REG:
4180                         amd64_inc_reg_size (code, ins->dreg, 4);
4181                         break;
4182                 case OP_X86_DEC_MEMBASE:
4183                         amd64_dec_membase_size (code, ins->inst_basereg, ins->inst_offset, 4);
4184                         break;
4185                 case OP_X86_DEC_REG:
4186                         amd64_dec_reg_size (code, ins->dreg, 4);
4187                         break;
4188                 case OP_X86_MUL_REG_MEMBASE:
4189                 case OP_X86_MUL_MEMBASE_REG:
4190                         amd64_imul_reg_membase_size (code, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
4191                         break;
4192                 case OP_AMD64_ICOMPARE_MEMBASE_REG:
4193                         amd64_alu_membase_reg_size (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
4194                         break;
4195                 case OP_AMD64_ICOMPARE_MEMBASE_IMM:
4196                         amd64_alu_membase_imm_size (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
4197                         break;
4198                 case OP_AMD64_COMPARE_MEMBASE_REG:
4199                         amd64_alu_membase_reg_size (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
4200                         break;
4201                 case OP_AMD64_COMPARE_MEMBASE_IMM:
4202                         g_assert (amd64_is_imm32 (ins->inst_imm));
4203                         amd64_alu_membase_imm_size (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
4204                         break;
4205                 case OP_X86_COMPARE_MEMBASE8_IMM:
4206                         amd64_alu_membase8_imm_size (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
4207                         break;
4208                 case OP_AMD64_ICOMPARE_REG_MEMBASE:
4209                         amd64_alu_reg_membase_size (code, X86_CMP, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
4210                         break;
4211                 case OP_AMD64_COMPARE_REG_MEMBASE:
4212                         amd64_alu_reg_membase_size (code, X86_CMP, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
4213                         break;
4214
4215                 case OP_AMD64_ADD_REG_MEMBASE:
4216                         amd64_alu_reg_membase_size (code, X86_ADD, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
4217                         break;
4218                 case OP_AMD64_SUB_REG_MEMBASE:
4219                         amd64_alu_reg_membase_size (code, X86_SUB, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
4220                         break;
4221                 case OP_AMD64_AND_REG_MEMBASE:
4222                         amd64_alu_reg_membase_size (code, X86_AND, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
4223                         break;
4224                 case OP_AMD64_OR_REG_MEMBASE:
4225                         amd64_alu_reg_membase_size (code, X86_OR, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
4226                         break;
4227                 case OP_AMD64_XOR_REG_MEMBASE:
4228                         amd64_alu_reg_membase_size (code, X86_XOR, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
4229                         break;
4230
4231                 case OP_AMD64_ADD_MEMBASE_REG:
4232                         amd64_alu_membase_reg_size (code, X86_ADD, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
4233                         break;
4234                 case OP_AMD64_SUB_MEMBASE_REG:
4235                         amd64_alu_membase_reg_size (code, X86_SUB, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
4236                         break;
4237                 case OP_AMD64_AND_MEMBASE_REG:
4238                         amd64_alu_membase_reg_size (code, X86_AND, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
4239                         break;
4240                 case OP_AMD64_OR_MEMBASE_REG:
4241                         amd64_alu_membase_reg_size (code, X86_OR, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
4242                         break;
4243                 case OP_AMD64_XOR_MEMBASE_REG:
4244                         amd64_alu_membase_reg_size (code, X86_XOR, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
4245                         break;
4246
4247                 case OP_AMD64_ADD_MEMBASE_IMM:
4248                         g_assert (amd64_is_imm32 (ins->inst_imm));
4249                         amd64_alu_membase_imm_size (code, X86_ADD, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
4250                         break;
4251                 case OP_AMD64_SUB_MEMBASE_IMM:
4252                         g_assert (amd64_is_imm32 (ins->inst_imm));
4253                         amd64_alu_membase_imm_size (code, X86_SUB, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
4254                         break;
4255                 case OP_AMD64_AND_MEMBASE_IMM:
4256                         g_assert (amd64_is_imm32 (ins->inst_imm));
4257                         amd64_alu_membase_imm_size (code, X86_AND, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
4258                         break;
4259                 case OP_AMD64_OR_MEMBASE_IMM:
4260                         g_assert (amd64_is_imm32 (ins->inst_imm));
4261                         amd64_alu_membase_imm_size (code, X86_OR, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
4262                         break;
4263                 case OP_AMD64_XOR_MEMBASE_IMM:
4264                         g_assert (amd64_is_imm32 (ins->inst_imm));
4265                         amd64_alu_membase_imm_size (code, X86_XOR, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
4266                         break;
4267
4268                 case OP_BREAK:
4269                         amd64_breakpoint (code);
4270                         break;
4271                 case OP_RELAXED_NOP:
4272                         x86_prefix (code, X86_REP_PREFIX);
4273                         x86_nop (code);
4274                         break;
4275                 case OP_HARD_NOP:
4276                         x86_nop (code);
4277                         break;
4278                 case OP_NOP:
4279                 case OP_DUMMY_USE:
4280                 case OP_DUMMY_STORE:
4281                 case OP_NOT_REACHED:
4282                 case OP_NOT_NULL:
4283                         break;
4284                 case OP_SEQ_POINT: {
4285                         int i;
4286
4287                         /* 
4288                          * Read from the single stepping trigger page. This will cause a
4289                          * SIGSEGV when single stepping is enabled.
4290                          * We do this _before_ the breakpoint, so single stepping after
4291                          * a breakpoint is hit will step to the next IL offset.
4292                          */
4293                         if (ins->flags & MONO_INST_SINGLE_STEP_LOC) {
4294                                 MonoInst *var = cfg->arch.ss_trigger_page_var;
4295
4296                                 amd64_mov_reg_membase (code, AMD64_R11, var->inst_basereg, var->inst_offset, 8);
4297                                 amd64_alu_membase_imm_size (code, X86_CMP, AMD64_R11, 0, 0, 4);
4298                         }
4299
4300                         /* 
4301                          * This is the address which is saved in seq points, 
4302                          */
4303                         mono_add_seq_point (cfg, bb, ins, code - cfg->native_code);
4304
4305                         if (cfg->compile_aot) {
4306                                 guint32 offset = code - cfg->native_code;
4307                                 guint32 val;
4308                                 MonoInst *info_var = cfg->arch.seq_point_info_var;
4309
4310                                 /* Load info var */
4311                                 amd64_mov_reg_membase (code, AMD64_R11, info_var->inst_basereg, info_var->inst_offset, 8);
4312                                 val = ((offset) * sizeof (guint8*)) + G_STRUCT_OFFSET (SeqPointInfo, bp_addrs);
4313                                 /* Load the info->bp_addrs [offset], which is either a valid address or the address of a trigger page */
4314                                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, val, 8);
4315                                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 0, 8);
4316                         } else {
4317                                 /* 
4318                                  * A placeholder for a possible breakpoint inserted by
4319                                  * mono_arch_set_breakpoint ().
4320                                  */
4321                                 for (i = 0; i < breakpoint_size; ++i)
4322                                         x86_nop (code);
4323                         }
4324                         /*
4325                          * Add an additional nop so skipping the bp doesn't cause the ip to point
4326                          * to another IL offset.
4327                          */
4328                         x86_nop (code);
4329                         break;
4330                 }
4331                 case OP_ADDCC:
4332                 case OP_LADD:
4333                         amd64_alu_reg_reg (code, X86_ADD, ins->sreg1, ins->sreg2);
4334                         break;
4335                 case OP_ADC:
4336                         amd64_alu_reg_reg (code, X86_ADC, ins->sreg1, ins->sreg2);
4337                         break;
4338                 case OP_ADD_IMM:
4339                 case OP_LADD_IMM:
4340                         g_assert (amd64_is_imm32 (ins->inst_imm));
4341                         amd64_alu_reg_imm (code, X86_ADD, ins->dreg, ins->inst_imm);
4342                         break;
4343                 case OP_ADC_IMM:
4344                         g_assert (amd64_is_imm32 (ins->inst_imm));
4345                         amd64_alu_reg_imm (code, X86_ADC, ins->dreg, ins->inst_imm);
4346                         break;
4347                 case OP_SUBCC:
4348                 case OP_LSUB:
4349                         amd64_alu_reg_reg (code, X86_SUB, ins->sreg1, ins->sreg2);
4350                         break;
4351                 case OP_SBB:
4352                         amd64_alu_reg_reg (code, X86_SBB, ins->sreg1, ins->sreg2);
4353                         break;
4354                 case OP_SUB_IMM:
4355                 case OP_LSUB_IMM:
4356                         g_assert (amd64_is_imm32 (ins->inst_imm));
4357                         amd64_alu_reg_imm (code, X86_SUB, ins->dreg, ins->inst_imm);
4358                         break;
4359                 case OP_SBB_IMM:
4360                         g_assert (amd64_is_imm32 (ins->inst_imm));
4361                         amd64_alu_reg_imm (code, X86_SBB, ins->dreg, ins->inst_imm);
4362                         break;
4363                 case OP_LAND:
4364                         amd64_alu_reg_reg (code, X86_AND, ins->sreg1, ins->sreg2);
4365                         break;
4366                 case OP_AND_IMM:
4367                 case OP_LAND_IMM:
4368                         g_assert (amd64_is_imm32 (ins->inst_imm));
4369                         amd64_alu_reg_imm (code, X86_AND, ins->sreg1, ins->inst_imm);
4370                         break;
4371                 case OP_LMUL:
4372                         amd64_imul_reg_reg (code, ins->sreg1, ins->sreg2);
4373                         break;
4374                 case OP_MUL_IMM:
4375                 case OP_LMUL_IMM:
4376                 case OP_IMUL_IMM: {
4377                         guint32 size = (ins->opcode == OP_IMUL_IMM) ? 4 : 8;
4378                         
4379                         switch (ins->inst_imm) {
4380                         case 2:
4381                                 /* MOV r1, r2 */
4382                                 /* ADD r1, r1 */
4383                                 if (ins->dreg != ins->sreg1)
4384                                         amd64_mov_reg_reg (code, ins->dreg, ins->sreg1, size);
4385                                 amd64_alu_reg_reg (code, X86_ADD, ins->dreg, ins->dreg);
4386                                 break;
4387                         case 3:
4388                                 /* LEA r1, [r2 + r2*2] */
4389                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 1);
4390                                 break;
4391                         case 5:
4392                                 /* LEA r1, [r2 + r2*4] */
4393                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 2);
4394                                 break;
4395                         case 6:
4396                                 /* LEA r1, [r2 + r2*2] */
4397                                 /* ADD r1, r1          */
4398                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 1);
4399                                 amd64_alu_reg_reg (code, X86_ADD, ins->dreg, ins->dreg);
4400                                 break;
4401                         case 9:
4402                                 /* LEA r1, [r2 + r2*8] */
4403                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 3);
4404                                 break;
4405                         case 10:
4406                                 /* LEA r1, [r2 + r2*4] */
4407                                 /* ADD r1, r1          */
4408                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 2);
4409                                 amd64_alu_reg_reg (code, X86_ADD, ins->dreg, ins->dreg);
4410                                 break;
4411                         case 12:
4412                                 /* LEA r1, [r2 + r2*2] */
4413                                 /* SHL r1, 2           */
4414                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 1);
4415                                 amd64_shift_reg_imm (code, X86_SHL, ins->dreg, 2);
4416                                 break;
4417                         case 25:
4418                                 /* LEA r1, [r2 + r2*4] */
4419                                 /* LEA r1, [r1 + r1*4] */
4420                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 2);
4421                                 amd64_lea_memindex (code, ins->dreg, ins->dreg, 0, ins->dreg, 2);
4422                                 break;
4423                         case 100:
4424                                 /* LEA r1, [r2 + r2*4] */
4425                                 /* SHL r1, 2           */
4426                                 /* LEA r1, [r1 + r1*4] */
4427                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 2);
4428                                 amd64_shift_reg_imm (code, X86_SHL, ins->dreg, 2);
4429                                 amd64_lea_memindex (code, ins->dreg, ins->dreg, 0, ins->dreg, 2);
4430                                 break;
4431                         default:
4432                                 amd64_imul_reg_reg_imm_size (code, ins->dreg, ins->sreg1, ins->inst_imm, size);
4433                                 break;
4434                         }
4435                         break;
4436                 }
4437                 case OP_LDIV:
4438                 case OP_LREM:
4439                         /* Regalloc magic makes the div/rem cases the same */
4440                         if (ins->sreg2 == AMD64_RDX) {
4441                                 amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RDX, 8);
4442                                 amd64_cdq (code);
4443                                 amd64_div_membase (code, AMD64_RSP, -8, TRUE);
4444                         } else {
4445                                 amd64_cdq (code);
4446                                 amd64_div_reg (code, ins->sreg2, TRUE);
4447                         }
4448                         break;
4449                 case OP_LDIV_UN:
4450                 case OP_LREM_UN:
4451                         if (ins->sreg2 == AMD64_RDX) {
4452                                 amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RDX, 8);
4453                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RDX, AMD64_RDX);
4454                                 amd64_div_membase (code, AMD64_RSP, -8, FALSE);
4455                         } else {
4456                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RDX, AMD64_RDX);
4457                                 amd64_div_reg (code, ins->sreg2, FALSE);
4458                         }
4459                         break;
4460                 case OP_IDIV:
4461                 case OP_IREM:
4462                         if (ins->sreg2 == AMD64_RDX) {
4463                                 amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RDX, 8);
4464                                 amd64_cdq_size (code, 4);
4465                                 amd64_div_membase_size (code, AMD64_RSP, -8, TRUE, 4);
4466                         } else {
4467                                 amd64_cdq_size (code, 4);
4468                                 amd64_div_reg_size (code, ins->sreg2, TRUE, 4);
4469                         }
4470                         break;
4471                 case OP_IDIV_UN:
4472                 case OP_IREM_UN:
4473                         if (ins->sreg2 == AMD64_RDX) {
4474                                 amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RDX, 8);
4475                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RDX, AMD64_RDX);
4476                                 amd64_div_membase_size (code, AMD64_RSP, -8, FALSE, 4);
4477                         } else {
4478                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RDX, AMD64_RDX);
4479                                 amd64_div_reg_size (code, ins->sreg2, FALSE, 4);
4480                         }
4481                         break;
4482                 case OP_IREM_IMM: {
4483                         int power = mono_is_power_of_two (ins->inst_imm);
4484
4485                         g_assert (ins->sreg1 == X86_EAX);
4486                         g_assert (ins->dreg == X86_EAX);
4487                         g_assert (power >= 0);
4488
4489                         if (power == 0) {
4490                                 amd64_mov_reg_imm (code, ins->dreg, 0);
4491                                 break;
4492                         }
4493
4494                         /* Based on gcc code */
4495
4496                         /* Add compensation for negative dividents */
4497                         amd64_mov_reg_reg_size (code, AMD64_RDX, AMD64_RAX, 4);
4498                         if (power > 1)
4499                                 amd64_shift_reg_imm_size (code, X86_SAR, AMD64_RDX, 31, 4);
4500                         amd64_shift_reg_imm_size (code, X86_SHR, AMD64_RDX, 32 - power, 4);
4501                         amd64_alu_reg_reg_size (code, X86_ADD, AMD64_RAX, AMD64_RDX, 4);
4502                         /* Compute remainder */
4503                         amd64_alu_reg_imm_size (code, X86_AND, AMD64_RAX, (1 << power) - 1, 4);
4504                         /* Remove compensation */
4505                         amd64_alu_reg_reg_size (code, X86_SUB, AMD64_RAX, AMD64_RDX, 4);
4506                         break;
4507                 }
4508                 case OP_LMUL_OVF:
4509                         amd64_imul_reg_reg (code, ins->sreg1, ins->sreg2);
4510                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_O, FALSE, "OverflowException");
4511                         break;
4512                 case OP_LOR:
4513                         amd64_alu_reg_reg (code, X86_OR, ins->sreg1, ins->sreg2);
4514                         break;
4515                 case OP_OR_IMM:
4516                 case OP_LOR_IMM:
4517                         g_assert (amd64_is_imm32 (ins->inst_imm));
4518                         amd64_alu_reg_imm (code, X86_OR, ins->sreg1, ins->inst_imm);
4519                         break;
4520                 case OP_LXOR:
4521                         amd64_alu_reg_reg (code, X86_XOR, ins->sreg1, ins->sreg2);
4522                         break;
4523                 case OP_XOR_IMM:
4524                 case OP_LXOR_IMM:
4525                         g_assert (amd64_is_imm32 (ins->inst_imm));
4526                         amd64_alu_reg_imm (code, X86_XOR, ins->sreg1, ins->inst_imm);
4527                         break;
4528                 case OP_LSHL:
4529                         g_assert (ins->sreg2 == AMD64_RCX);
4530                         amd64_shift_reg (code, X86_SHL, ins->dreg);
4531                         break;
4532                 case OP_LSHR:
4533                         g_assert (ins->sreg2 == AMD64_RCX);
4534                         amd64_shift_reg (code, X86_SAR, ins->dreg);
4535                         break;
4536                 case OP_SHR_IMM:
4537                         g_assert (amd64_is_imm32 (ins->inst_imm));
4538                         amd64_shift_reg_imm_size (code, X86_SAR, ins->dreg, ins->inst_imm, 4);
4539                         break;
4540                 case OP_LSHR_IMM:
4541                         g_assert (amd64_is_imm32 (ins->inst_imm));
4542                         amd64_shift_reg_imm (code, X86_SAR, ins->dreg, ins->inst_imm);
4543                         break;
4544                 case OP_SHR_UN_IMM:
4545                         g_assert (amd64_is_imm32 (ins->inst_imm));
4546                         amd64_shift_reg_imm_size (code, X86_SHR, ins->dreg, ins->inst_imm, 4);
4547                         break;
4548                 case OP_LSHR_UN_IMM:
4549                         g_assert (amd64_is_imm32 (ins->inst_imm));
4550                         amd64_shift_reg_imm (code, X86_SHR, ins->dreg, ins->inst_imm);
4551                         break;
4552                 case OP_LSHR_UN:
4553                         g_assert (ins->sreg2 == AMD64_RCX);
4554                         amd64_shift_reg (code, X86_SHR, ins->dreg);
4555                         break;
4556                 case OP_SHL_IMM:
4557                         g_assert (amd64_is_imm32 (ins->inst_imm));
4558                         amd64_shift_reg_imm_size (code, X86_SHL, ins->dreg, ins->inst_imm, 4);
4559                         break;
4560                 case OP_LSHL_IMM:
4561                         g_assert (amd64_is_imm32 (ins->inst_imm));
4562                         amd64_shift_reg_imm (code, X86_SHL, ins->dreg, ins->inst_imm);
4563                         break;
4564
4565                 case OP_IADDCC:
4566                 case OP_IADD:
4567                         amd64_alu_reg_reg_size (code, X86_ADD, ins->sreg1, ins->sreg2, 4);
4568                         break;
4569                 case OP_IADC:
4570                         amd64_alu_reg_reg_size (code, X86_ADC, ins->sreg1, ins->sreg2, 4);
4571                         break;
4572                 case OP_IADD_IMM:
4573                         amd64_alu_reg_imm_size (code, X86_ADD, ins->dreg, ins->inst_imm, 4);
4574                         break;
4575                 case OP_IADC_IMM:
4576                         amd64_alu_reg_imm_size (code, X86_ADC, ins->dreg, ins->inst_imm, 4);
4577                         break;
4578                 case OP_ISUBCC:
4579                 case OP_ISUB:
4580                         amd64_alu_reg_reg_size (code, X86_SUB, ins->sreg1, ins->sreg2, 4);
4581                         break;
4582                 case OP_ISBB:
4583                         amd64_alu_reg_reg_size (code, X86_SBB, ins->sreg1, ins->sreg2, 4);
4584                         break;
4585                 case OP_ISUB_IMM:
4586                         amd64_alu_reg_imm_size (code, X86_SUB, ins->dreg, ins->inst_imm, 4);
4587                         break;
4588                 case OP_ISBB_IMM:
4589                         amd64_alu_reg_imm_size (code, X86_SBB, ins->dreg, ins->inst_imm, 4);
4590                         break;
4591                 case OP_IAND:
4592                         amd64_alu_reg_reg_size (code, X86_AND, ins->sreg1, ins->sreg2, 4);
4593                         break;
4594                 case OP_IAND_IMM:
4595                         amd64_alu_reg_imm_size (code, X86_AND, ins->sreg1, ins->inst_imm, 4);
4596                         break;
4597                 case OP_IOR:
4598                         amd64_alu_reg_reg_size (code, X86_OR, ins->sreg1, ins->sreg2, 4);
4599                         break;
4600                 case OP_IOR_IMM:
4601                         amd64_alu_reg_imm_size (code, X86_OR, ins->sreg1, ins->inst_imm, 4);
4602                         break;
4603                 case OP_IXOR:
4604                         amd64_alu_reg_reg_size (code, X86_XOR, ins->sreg1, ins->sreg2, 4);
4605                         break;
4606                 case OP_IXOR_IMM:
4607                         amd64_alu_reg_imm_size (code, X86_XOR, ins->sreg1, ins->inst_imm, 4);
4608                         break;
4609                 case OP_INEG:
4610                         amd64_neg_reg_size (code, ins->sreg1, 4);
4611                         break;
4612                 case OP_INOT:
4613                         amd64_not_reg_size (code, ins->sreg1, 4);
4614                         break;
4615                 case OP_ISHL:
4616                         g_assert (ins->sreg2 == AMD64_RCX);
4617                         amd64_shift_reg_size (code, X86_SHL, ins->dreg, 4);
4618                         break;
4619                 case OP_ISHR:
4620                         g_assert (ins->sreg2 == AMD64_RCX);
4621                         amd64_shift_reg_size (code, X86_SAR, ins->dreg, 4);
4622                         break;
4623                 case OP_ISHR_IMM:
4624                         amd64_shift_reg_imm_size (code, X86_SAR, ins->dreg, ins->inst_imm, 4);
4625                         break;
4626                 case OP_ISHR_UN_IMM:
4627                         amd64_shift_reg_imm_size (code, X86_SHR, ins->dreg, ins->inst_imm, 4);
4628                         break;
4629                 case OP_ISHR_UN:
4630                         g_assert (ins->sreg2 == AMD64_RCX);
4631                         amd64_shift_reg_size (code, X86_SHR, ins->dreg, 4);
4632                         break;
4633                 case OP_ISHL_IMM:
4634                         amd64_shift_reg_imm_size (code, X86_SHL, ins->dreg, ins->inst_imm, 4);
4635                         break;
4636                 case OP_IMUL:
4637                         amd64_imul_reg_reg_size (code, ins->sreg1, ins->sreg2, 4);
4638                         break;
4639                 case OP_IMUL_OVF:
4640                         amd64_imul_reg_reg_size (code, ins->sreg1, ins->sreg2, 4);
4641                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_O, FALSE, "OverflowException");
4642                         break;
4643                 case OP_IMUL_OVF_UN:
4644                 case OP_LMUL_OVF_UN: {
4645                         /* the mul operation and the exception check should most likely be split */
4646                         int non_eax_reg, saved_eax = FALSE, saved_edx = FALSE;
4647                         int size = (ins->opcode == OP_IMUL_OVF_UN) ? 4 : 8;
4648                         /*g_assert (ins->sreg2 == X86_EAX);
4649                         g_assert (ins->dreg == X86_EAX);*/
4650                         if (ins->sreg2 == X86_EAX) {
4651                                 non_eax_reg = ins->sreg1;
4652                         } else if (ins->sreg1 == X86_EAX) {
4653                                 non_eax_reg = ins->sreg2;
4654                         } else {
4655                                 /* no need to save since we're going to store to it anyway */
4656                                 if (ins->dreg != X86_EAX) {
4657                                         saved_eax = TRUE;
4658                                         amd64_push_reg (code, X86_EAX);
4659                                 }
4660                                 amd64_mov_reg_reg (code, X86_EAX, ins->sreg1, size);
4661                                 non_eax_reg = ins->sreg2;
4662                         }
4663                         if (ins->dreg == X86_EDX) {
4664                                 if (!saved_eax) {
4665                                         saved_eax = TRUE;
4666                                         amd64_push_reg (code, X86_EAX);
4667                                 }
4668                         } else {
4669                                 saved_edx = TRUE;
4670                                 amd64_push_reg (code, X86_EDX);
4671                         }
4672                         amd64_mul_reg_size (code, non_eax_reg, FALSE, size);
4673                         /* save before the check since pop and mov don't change the flags */
4674                         if (ins->dreg != X86_EAX)
4675                                 amd64_mov_reg_reg (code, ins->dreg, X86_EAX, size);
4676                         if (saved_edx)
4677                                 amd64_pop_reg (code, X86_EDX);
4678                         if (saved_eax)
4679                                 amd64_pop_reg (code, X86_EAX);
4680                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_O, FALSE, "OverflowException");
4681                         break;
4682                 }
4683                 case OP_ICOMPARE:
4684                         amd64_alu_reg_reg_size (code, X86_CMP, ins->sreg1, ins->sreg2, 4);
4685                         break;
4686                 case OP_ICOMPARE_IMM:
4687                         amd64_alu_reg_imm_size (code, X86_CMP, ins->sreg1, ins->inst_imm, 4);
4688                         break;
4689                 case OP_IBEQ:
4690                 case OP_IBLT:
4691                 case OP_IBGT:
4692                 case OP_IBGE:
4693                 case OP_IBLE:
4694                 case OP_LBEQ:
4695                 case OP_LBLT:
4696                 case OP_LBGT:
4697                 case OP_LBGE:
4698                 case OP_LBLE:
4699                 case OP_IBNE_UN:
4700                 case OP_IBLT_UN:
4701                 case OP_IBGT_UN:
4702                 case OP_IBGE_UN:
4703                 case OP_IBLE_UN:
4704                 case OP_LBNE_UN:
4705                 case OP_LBLT_UN:
4706                 case OP_LBGT_UN:
4707                 case OP_LBGE_UN:
4708                 case OP_LBLE_UN:
4709                         EMIT_COND_BRANCH (ins, cc_table [mono_opcode_to_cond (ins->opcode)], cc_signed_table [mono_opcode_to_cond (ins->opcode)]);
4710                         break;
4711
4712                 case OP_CMOV_IEQ:
4713                 case OP_CMOV_IGE:
4714                 case OP_CMOV_IGT:
4715                 case OP_CMOV_ILE:
4716                 case OP_CMOV_ILT:
4717                 case OP_CMOV_INE_UN:
4718                 case OP_CMOV_IGE_UN:
4719                 case OP_CMOV_IGT_UN:
4720                 case OP_CMOV_ILE_UN:
4721                 case OP_CMOV_ILT_UN:
4722                 case OP_CMOV_LEQ:
4723                 case OP_CMOV_LGE:
4724                 case OP_CMOV_LGT:
4725                 case OP_CMOV_LLE:
4726                 case OP_CMOV_LLT:
4727                 case OP_CMOV_LNE_UN:
4728                 case OP_CMOV_LGE_UN:
4729                 case OP_CMOV_LGT_UN:
4730                 case OP_CMOV_LLE_UN:
4731                 case OP_CMOV_LLT_UN:
4732                         g_assert (ins->dreg == ins->sreg1);
4733                         /* This needs to operate on 64 bit values */
4734                         amd64_cmov_reg (code, cc_table [mono_opcode_to_cond (ins->opcode)], cc_signed_table [mono_opcode_to_cond (ins->opcode)], ins->dreg, ins->sreg2);
4735                         break;
4736
4737                 case OP_LNOT:
4738                         amd64_not_reg (code, ins->sreg1);
4739                         break;
4740                 case OP_LNEG:
4741                         amd64_neg_reg (code, ins->sreg1);
4742                         break;
4743
4744                 case OP_ICONST:
4745                 case OP_I8CONST:
4746                         if ((((guint64)ins->inst_c0) >> 32) == 0)
4747                                 amd64_mov_reg_imm_size (code, ins->dreg, ins->inst_c0, 4);
4748                         else
4749                                 amd64_mov_reg_imm_size (code, ins->dreg, ins->inst_c0, 8);
4750                         break;
4751                 case OP_AOTCONST:
4752                         mono_add_patch_info (cfg, offset, (MonoJumpInfoType)ins->inst_i1, ins->inst_p0);
4753                         amd64_mov_reg_membase (code, ins->dreg, AMD64_RIP, 0, sizeof(gpointer));
4754                         break;
4755                 case OP_JUMP_TABLE:
4756                         mono_add_patch_info (cfg, offset, (MonoJumpInfoType)ins->inst_i1, ins->inst_p0);
4757                         amd64_mov_reg_imm_size (code, ins->dreg, 0, 8);
4758                         break;
4759                 case OP_MOVE:
4760                         amd64_mov_reg_reg (code, ins->dreg, ins->sreg1, sizeof(mgreg_t));
4761                         break;
4762                 case OP_AMD64_SET_XMMREG_R4: {
4763                         amd64_sse_cvtsd2ss_reg_reg (code, ins->dreg, ins->sreg1);
4764                         break;
4765                 }
4766                 case OP_AMD64_SET_XMMREG_R8: {
4767                         if (ins->dreg != ins->sreg1)
4768                                 amd64_sse_movsd_reg_reg (code, ins->dreg, ins->sreg1);
4769                         break;
4770                 }
4771                 case OP_TAILCALL: {
4772                         MonoCallInst *call = (MonoCallInst*)ins;
4773                         int pos = 0, i;
4774
4775                         /* FIXME: no tracing support... */
4776                         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
4777                                 code = mono_arch_instrument_epilog_full (cfg, mono_profiler_method_leave, code, FALSE, TRUE);
4778
4779                         g_assert (!cfg->method->save_lmf);
4780
4781                         if (cfg->arch.omit_fp) {
4782                                 guint32 save_offset = 0;
4783                                 /* Pop callee-saved registers */
4784                                 for (i = 0; i < AMD64_NREG; ++i)
4785                                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
4786                                                 amd64_mov_reg_membase (code, i, AMD64_RSP, save_offset, 8);
4787                                                 save_offset += 8;
4788                                         }
4789                                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, cfg->arch.stack_alloc_size);
4790
4791                                 // FIXME:
4792                                 if (call->stack_usage)
4793                                         NOT_IMPLEMENTED;
4794                         }
4795                         else {
4796                                 for (i = 0; i < AMD64_NREG; ++i)
4797                                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i)))
4798                                                 pos -= sizeof(mgreg_t);
4799
4800                                 /* Restore callee-saved registers */
4801                                 for (i = AMD64_NREG - 1; i > 0; --i) {
4802                                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
4803                                                 amd64_mov_reg_membase (code, i, AMD64_RBP, pos, sizeof(mgreg_t));
4804                                                 pos += sizeof(mgreg_t);
4805                                         }
4806                                 }
4807
4808                                 /* Copy arguments on the stack to our argument area */
4809                                 for (i = 0; i < call->stack_usage; i += sizeof(mgreg_t)) {
4810                                         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RSP, i, sizeof(mgreg_t));
4811                                         amd64_mov_membase_reg (code, AMD64_RBP, 16 + i, AMD64_RAX, sizeof(mgreg_t));
4812                                 }
4813                         
4814                                 if (pos)
4815                                         amd64_lea_membase (code, AMD64_RSP, AMD64_RBP, pos);
4816
4817                                 amd64_leave (code);
4818                         }
4819
4820                         offset = code - cfg->native_code;
4821                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_METHOD_JUMP, ins->inst_p0);
4822                         if (cfg->compile_aot)
4823                                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, 8);
4824                         else
4825                                 amd64_set_reg_template (code, AMD64_R11);
4826                         amd64_jump_reg (code, AMD64_R11);
4827                         ins->flags |= MONO_INST_GC_CALLSITE;
4828                         ins->backend.pc_offset = code - cfg->native_code;
4829                         break;
4830                 }
4831                 case OP_CHECK_THIS:
4832                         /* ensure ins->sreg1 is not NULL */
4833                         amd64_alu_membase_imm_size (code, X86_CMP, ins->sreg1, 0, 0, 4);
4834                         break;
4835                 case OP_ARGLIST: {
4836                         amd64_lea_membase (code, AMD64_R11, cfg->frame_reg, cfg->sig_cookie);
4837                         amd64_mov_membase_reg (code, ins->sreg1, 0, AMD64_R11, sizeof(gpointer));
4838                         break;
4839                 }
4840                 case OP_CALL:
4841                 case OP_FCALL:
4842                 case OP_LCALL:
4843                 case OP_VCALL:
4844                 case OP_VCALL2:
4845                 case OP_VOIDCALL:
4846                         call = (MonoCallInst*)ins;
4847                         /*
4848                          * The AMD64 ABI forces callers to know about varargs.
4849                          */
4850                         if ((call->signature->call_convention == MONO_CALL_VARARG) && (call->signature->pinvoke))
4851                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
4852                         else if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && (cfg->method->klass->image != mono_defaults.corlib)) {
4853                                 /* 
4854                                  * Since the unmanaged calling convention doesn't contain a 
4855                                  * 'vararg' entry, we have to treat every pinvoke call as a
4856                                  * potential vararg call.
4857                                  */
4858                                 guint32 nregs, i;
4859                                 nregs = 0;
4860                                 for (i = 0; i < AMD64_XMM_NREG; ++i)
4861                                         if (call->used_fregs & (1 << i))
4862                                                 nregs ++;
4863                                 if (!nregs)
4864                                         amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
4865                                 else
4866                                         amd64_mov_reg_imm (code, AMD64_RAX, nregs);
4867                         }
4868
4869                         if (ins->flags & MONO_INST_HAS_METHOD)
4870                                 code = emit_call (cfg, code, MONO_PATCH_INFO_METHOD, call->method, FALSE);
4871                         else
4872                                 code = emit_call (cfg, code, MONO_PATCH_INFO_ABS, call->fptr, FALSE);
4873                         ins->flags |= MONO_INST_GC_CALLSITE;
4874                         ins->backend.pc_offset = code - cfg->native_code;
4875                         if (call->stack_usage && !CALLCONV_IS_STDCALL (call->signature->call_convention) && !cfg->arch.no_pushes)
4876                                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, call->stack_usage);
4877                         code = emit_move_return_value (cfg, ins, code);
4878                         break;
4879                 case OP_FCALL_REG:
4880                 case OP_LCALL_REG:
4881                 case OP_VCALL_REG:
4882                 case OP_VCALL2_REG:
4883                 case OP_VOIDCALL_REG:
4884                 case OP_CALL_REG:
4885                         call = (MonoCallInst*)ins;
4886
4887                         if (AMD64_IS_ARGUMENT_REG (ins->sreg1)) {
4888                                 amd64_mov_reg_reg (code, AMD64_R11, ins->sreg1, 8);
4889                                 ins->sreg1 = AMD64_R11;
4890                         }
4891
4892                         /*
4893                          * The AMD64 ABI forces callers to know about varargs.
4894                          */
4895                         if ((call->signature->call_convention == MONO_CALL_VARARG) && (call->signature->pinvoke)) {
4896                                 if (ins->sreg1 == AMD64_RAX) {
4897                                         amd64_mov_reg_reg (code, AMD64_R11, AMD64_RAX, 8);
4898                                         ins->sreg1 = AMD64_R11;
4899                                 }
4900                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
4901                         } else if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && (cfg->method->klass->image != mono_defaults.corlib)) {
4902                                 /* 
4903                                  * Since the unmanaged calling convention doesn't contain a 
4904                                  * 'vararg' entry, we have to treat every pinvoke call as a
4905                                  * potential vararg call.
4906                                  */
4907                                 guint32 nregs, i;
4908                                 nregs = 0;
4909                                 for (i = 0; i < AMD64_XMM_NREG; ++i)
4910                                         if (call->used_fregs & (1 << i))
4911                                                 nregs ++;
4912                                 if (ins->sreg1 == AMD64_RAX) {
4913                                         amd64_mov_reg_reg (code, AMD64_R11, AMD64_RAX, 8);
4914                                         ins->sreg1 = AMD64_R11;
4915                                 }
4916                                 if (!nregs)
4917                                         amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
4918                                 else
4919                                         amd64_mov_reg_imm (code, AMD64_RAX, nregs);
4920                         }
4921
4922                         amd64_call_reg (code, ins->sreg1);
4923                         ins->flags |= MONO_INST_GC_CALLSITE;
4924                         ins->backend.pc_offset = code - cfg->native_code;
4925                         if (call->stack_usage && !CALLCONV_IS_STDCALL (call->signature->call_convention) && !cfg->arch.no_pushes)
4926                                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, call->stack_usage);
4927                         code = emit_move_return_value (cfg, ins, code);
4928                         break;
4929                 case OP_FCALL_MEMBASE:
4930                 case OP_LCALL_MEMBASE:
4931                 case OP_VCALL_MEMBASE:
4932                 case OP_VCALL2_MEMBASE:
4933                 case OP_VOIDCALL_MEMBASE:
4934                 case OP_CALL_MEMBASE:
4935                         call = (MonoCallInst*)ins;
4936
4937                         amd64_call_membase (code, ins->sreg1, ins->inst_offset);
4938                         ins->flags |= MONO_INST_GC_CALLSITE;
4939                         ins->backend.pc_offset = code - cfg->native_code;
4940                         if (call->stack_usage && !CALLCONV_IS_STDCALL (call->signature->call_convention) && !cfg->arch.no_pushes)
4941                                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, call->stack_usage);
4942                         code = emit_move_return_value (cfg, ins, code);
4943                         break;
4944                 case OP_DYN_CALL: {
4945                         int i;
4946                         MonoInst *var = cfg->dyn_call_var;
4947
4948                         g_assert (var->opcode == OP_REGOFFSET);
4949
4950                         /* r11 = args buffer filled by mono_arch_get_dyn_call_args () */
4951                         amd64_mov_reg_reg (code, AMD64_R11, ins->sreg1, 8);
4952                         /* r10 = ftn */
4953                         amd64_mov_reg_reg (code, AMD64_R10, ins->sreg2, 8);
4954
4955                         /* Save args buffer */
4956                         amd64_mov_membase_reg (code, var->inst_basereg, var->inst_offset, AMD64_R11, 8);
4957
4958                         /* Set argument registers */
4959                         for (i = 0; i < PARAM_REGS; ++i)
4960                                 amd64_mov_reg_membase (code, param_regs [i], AMD64_R11, i * sizeof(mgreg_t), sizeof(mgreg_t));
4961                         
4962                         /* Make the call */
4963                         amd64_call_reg (code, AMD64_R10);
4964
4965                         ins->flags |= MONO_INST_GC_CALLSITE;
4966                         ins->backend.pc_offset = code - cfg->native_code;
4967
4968                         /* Save result */
4969                         amd64_mov_reg_membase (code, AMD64_R11, var->inst_basereg, var->inst_offset, 8);
4970                         amd64_mov_membase_reg (code, AMD64_R11, G_STRUCT_OFFSET (DynCallArgs, res), AMD64_RAX, 8);
4971                         break;
4972                 }
4973                 case OP_AMD64_SAVE_SP_TO_LMF: {
4974                         MonoInst *lmf_var = cfg->arch.lmf_var;
4975                         amd64_mov_membase_reg (code, cfg->frame_reg, lmf_var->inst_offset + G_STRUCT_OFFSET (MonoLMF, rsp), AMD64_RSP, 8);
4976                         break;
4977                 }
4978                 case OP_X86_PUSH:
4979                         g_assert (!cfg->arch.no_pushes);
4980                         amd64_push_reg (code, ins->sreg1);
4981                         break;
4982                 case OP_X86_PUSH_IMM:
4983                         g_assert (!cfg->arch.no_pushes);
4984                         g_assert (amd64_is_imm32 (ins->inst_imm));
4985                         amd64_push_imm (code, ins->inst_imm);
4986                         break;
4987                 case OP_X86_PUSH_MEMBASE:
4988                         g_assert (!cfg->arch.no_pushes);
4989                         amd64_push_membase (code, ins->inst_basereg, ins->inst_offset);
4990                         break;
4991                 case OP_X86_PUSH_OBJ: {
4992                         int size = ALIGN_TO (ins->inst_imm, 8);
4993
4994                         g_assert (!cfg->arch.no_pushes);
4995
4996                         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, size);
4997                         amd64_push_reg (code, AMD64_RDI);
4998                         amd64_push_reg (code, AMD64_RSI);
4999                         amd64_push_reg (code, AMD64_RCX);
5000                         if (ins->inst_offset)
5001                                 amd64_lea_membase (code, AMD64_RSI, ins->inst_basereg, ins->inst_offset);
5002                         else
5003                                 amd64_mov_reg_reg (code, AMD64_RSI, ins->inst_basereg, 8);
5004                         amd64_lea_membase (code, AMD64_RDI, AMD64_RSP, (3 * 8));
5005                         amd64_mov_reg_imm (code, AMD64_RCX, (size >> 3));
5006                         amd64_cld (code);
5007                         amd64_prefix (code, X86_REP_PREFIX);
5008                         amd64_movsd (code);
5009                         amd64_pop_reg (code, AMD64_RCX);
5010                         amd64_pop_reg (code, AMD64_RSI);
5011                         amd64_pop_reg (code, AMD64_RDI);
5012                         break;
5013                 }
5014                 case OP_X86_LEA:
5015                         amd64_lea_memindex (code, ins->dreg, ins->sreg1, ins->inst_imm, ins->sreg2, ins->backend.shift_amount);
5016                         break;
5017                 case OP_X86_LEA_MEMBASE:
5018                         amd64_lea_membase (code, ins->dreg, ins->sreg1, ins->inst_imm);
5019                         break;
5020                 case OP_X86_XCHG:
5021                         amd64_xchg_reg_reg (code, ins->sreg1, ins->sreg2, 4);
5022                         break;
5023                 case OP_LOCALLOC:
5024                         /* keep alignment */
5025                         amd64_alu_reg_imm (code, X86_ADD, ins->sreg1, MONO_ARCH_FRAME_ALIGNMENT - 1);
5026                         amd64_alu_reg_imm (code, X86_AND, ins->sreg1, ~(MONO_ARCH_FRAME_ALIGNMENT - 1));
5027                         code = mono_emit_stack_alloc (cfg, code, ins);
5028                         amd64_mov_reg_reg (code, ins->dreg, AMD64_RSP, 8);
5029                         if (cfg->param_area && cfg->arch.no_pushes)
5030                                 amd64_alu_reg_imm (code, X86_ADD, ins->dreg, cfg->param_area);
5031                         break;
5032                 case OP_LOCALLOC_IMM: {
5033                         guint32 size = ins->inst_imm;
5034                         size = (size + (MONO_ARCH_FRAME_ALIGNMENT - 1)) & ~ (MONO_ARCH_FRAME_ALIGNMENT - 1);
5035
5036                         if (ins->flags & MONO_INST_INIT) {
5037                                 if (size < 64) {
5038                                         int i;
5039
5040                                         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, size);
5041                                         amd64_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
5042
5043                                         for (i = 0; i < size; i += 8)
5044                                                 amd64_mov_membase_reg (code, AMD64_RSP, i, ins->dreg, 8);
5045                                         amd64_mov_reg_reg (code, ins->dreg, AMD64_RSP, 8);                                      
5046                                 } else {
5047                                         amd64_mov_reg_imm (code, ins->dreg, size);
5048                                         ins->sreg1 = ins->dreg;
5049
5050                                         code = mono_emit_stack_alloc (cfg, code, ins);
5051                                         amd64_mov_reg_reg (code, ins->dreg, AMD64_RSP, 8);
5052                                 }
5053                         } else {
5054                                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, size);
5055                                 amd64_mov_reg_reg (code, ins->dreg, AMD64_RSP, 8);
5056                         }
5057                         if (cfg->param_area && cfg->arch.no_pushes)
5058                                 amd64_alu_reg_imm (code, X86_ADD, ins->dreg, cfg->param_area);
5059                         break;
5060                 }
5061                 case OP_THROW: {
5062                         amd64_mov_reg_reg (code, AMD64_ARG_REG1, ins->sreg1, 8);
5063                         code = emit_call (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD, 
5064                                              (gpointer)"mono_arch_throw_exception", FALSE);
5065                         ins->flags |= MONO_INST_GC_CALLSITE;
5066                         ins->backend.pc_offset = code - cfg->native_code;
5067                         break;
5068                 }
5069                 case OP_RETHROW: {
5070                         amd64_mov_reg_reg (code, AMD64_ARG_REG1, ins->sreg1, 8);
5071                         code = emit_call (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD, 
5072                                              (gpointer)"mono_arch_rethrow_exception", FALSE);
5073                         ins->flags |= MONO_INST_GC_CALLSITE;
5074                         ins->backend.pc_offset = code - cfg->native_code;
5075                         break;
5076                 }
5077                 case OP_CALL_HANDLER: 
5078                         /* Align stack */
5079                         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
5080                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_BB, ins->inst_target_bb);
5081                         amd64_call_imm (code, 0);
5082                         mono_cfg_add_try_hole (cfg, ins->inst_eh_block, code, bb);
5083                         /* Restore stack alignment */
5084                         amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
5085                         break;
5086                 case OP_START_HANDLER: {
5087                         /* Even though we're saving RSP, use sizeof */
5088                         /* gpointer because spvar is of type IntPtr */
5089                         /* see: mono_create_spvar_for_region */
5090                         MonoInst *spvar = mono_find_spvar_for_region (cfg, bb->region);
5091                         amd64_mov_membase_reg (code, spvar->inst_basereg, spvar->inst_offset, AMD64_RSP, sizeof(gpointer));
5092
5093                         if ((MONO_BBLOCK_IS_IN_REGION (bb, MONO_REGION_FINALLY) ||
5094                                  MONO_BBLOCK_IS_IN_REGION (bb, MONO_REGION_FINALLY)) &&
5095                                 cfg->param_area && cfg->arch.no_pushes) {
5096                                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, ALIGN_TO (cfg->param_area, MONO_ARCH_FRAME_ALIGNMENT));
5097                         }
5098                         break;
5099                 }
5100                 case OP_ENDFINALLY: {
5101                         MonoInst *spvar = mono_find_spvar_for_region (cfg, bb->region);
5102                         amd64_mov_reg_membase (code, AMD64_RSP, spvar->inst_basereg, spvar->inst_offset, sizeof(gpointer));
5103                         amd64_ret (code);
5104                         break;
5105                 }
5106                 case OP_ENDFILTER: {
5107                         MonoInst *spvar = mono_find_spvar_for_region (cfg, bb->region);
5108                         amd64_mov_reg_membase (code, AMD64_RSP, spvar->inst_basereg, spvar->inst_offset, sizeof(gpointer));
5109                         /* The local allocator will put the result into RAX */
5110                         amd64_ret (code);
5111                         break;
5112                 }
5113
5114                 case OP_LABEL:
5115                         ins->inst_c0 = code - cfg->native_code;
5116                         break;
5117                 case OP_BR:
5118                         //g_print ("target: %p, next: %p, curr: %p, last: %p\n", ins->inst_target_bb, bb->next_bb, ins, bb->last_ins);
5119                         //if ((ins->inst_target_bb == bb->next_bb) && ins == bb->last_ins)
5120                         //break;
5121                                 if (ins->inst_target_bb->native_offset) {
5122                                         amd64_jump_code (code, cfg->native_code + ins->inst_target_bb->native_offset); 
5123                                 } else {
5124                                         mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_BB, ins->inst_target_bb);
5125                                         if ((cfg->opt & MONO_OPT_BRANCH) &&
5126                                             x86_is_imm8 (ins->inst_target_bb->max_offset - offset))
5127                                                 x86_jump8 (code, 0);
5128                                         else 
5129                                                 x86_jump32 (code, 0);
5130                         }
5131                         break;
5132                 case OP_BR_REG:
5133                         amd64_jump_reg (code, ins->sreg1);
5134                         break;
5135                 case OP_CEQ:
5136                 case OP_LCEQ:
5137                 case OP_ICEQ:
5138                 case OP_CLT:
5139                 case OP_LCLT:
5140                 case OP_ICLT:
5141                 case OP_CGT:
5142                 case OP_ICGT:
5143                 case OP_LCGT:
5144                 case OP_CLT_UN:
5145                 case OP_LCLT_UN:
5146                 case OP_ICLT_UN:
5147                 case OP_CGT_UN:
5148                 case OP_LCGT_UN:
5149                 case OP_ICGT_UN:
5150                         amd64_set_reg (code, cc_table [mono_opcode_to_cond (ins->opcode)], ins->dreg, cc_signed_table [mono_opcode_to_cond (ins->opcode)]);
5151                         amd64_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
5152                         break;
5153                 case OP_COND_EXC_EQ:
5154                 case OP_COND_EXC_NE_UN:
5155                 case OP_COND_EXC_LT:
5156                 case OP_COND_EXC_LT_UN:
5157                 case OP_COND_EXC_GT:
5158                 case OP_COND_EXC_GT_UN:
5159                 case OP_COND_EXC_GE:
5160                 case OP_COND_EXC_GE_UN:
5161                 case OP_COND_EXC_LE:
5162                 case OP_COND_EXC_LE_UN:
5163                 case OP_COND_EXC_IEQ:
5164                 case OP_COND_EXC_INE_UN:
5165                 case OP_COND_EXC_ILT:
5166                 case OP_COND_EXC_ILT_UN:
5167                 case OP_COND_EXC_IGT:
5168                 case OP_COND_EXC_IGT_UN:
5169                 case OP_COND_EXC_IGE:
5170                 case OP_COND_EXC_IGE_UN:
5171                 case OP_COND_EXC_ILE:
5172                 case OP_COND_EXC_ILE_UN:
5173                         EMIT_COND_SYSTEM_EXCEPTION (cc_table [mono_opcode_to_cond (ins->opcode)], cc_signed_table [mono_opcode_to_cond (ins->opcode)], ins->inst_p1);
5174                         break;
5175                 case OP_COND_EXC_OV:
5176                 case OP_COND_EXC_NO:
5177                 case OP_COND_EXC_C:
5178                 case OP_COND_EXC_NC:
5179                         EMIT_COND_SYSTEM_EXCEPTION (branch_cc_table [ins->opcode - OP_COND_EXC_EQ], 
5180                                                     (ins->opcode < OP_COND_EXC_NE_UN), ins->inst_p1);
5181                         break;
5182                 case OP_COND_EXC_IOV:
5183                 case OP_COND_EXC_INO:
5184                 case OP_COND_EXC_IC:
5185                 case OP_COND_EXC_INC:
5186                         EMIT_COND_SYSTEM_EXCEPTION (branch_cc_table [ins->opcode - OP_COND_EXC_IEQ], 
5187                                                     (ins->opcode < OP_COND_EXC_INE_UN), ins->inst_p1);
5188                         break;
5189
5190                 /* floating point opcodes */
5191                 case OP_R8CONST: {
5192                         double d = *(double *)ins->inst_p0;
5193
5194                         if ((d == 0.0) && (mono_signbit (d) == 0)) {
5195                                 amd64_sse_xorpd_reg_reg (code, ins->dreg, ins->dreg);
5196                         }
5197                         else {
5198                                 mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_R8, ins->inst_p0);
5199                                 amd64_sse_movsd_reg_membase (code, ins->dreg, AMD64_RIP, 0);
5200                         }
5201                         break;
5202                 }
5203                 case OP_R4CONST: {
5204                         float f = *(float *)ins->inst_p0;
5205
5206                         if ((f == 0.0) && (mono_signbit (f) == 0)) {
5207                                 amd64_sse_xorpd_reg_reg (code, ins->dreg, ins->dreg);
5208                         }
5209                         else {
5210                                 mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_R4, ins->inst_p0);
5211                                 amd64_sse_movss_reg_membase (code, ins->dreg, AMD64_RIP, 0);
5212                                 amd64_sse_cvtss2sd_reg_reg (code, ins->dreg, ins->dreg);
5213                         }
5214                         break;
5215                 }
5216                 case OP_STORER8_MEMBASE_REG:
5217                         amd64_sse_movsd_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1);
5218                         break;
5219                 case OP_LOADR8_MEMBASE:
5220                         amd64_sse_movsd_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset);
5221                         break;
5222                 case OP_STORER4_MEMBASE_REG:
5223                         /* This requires a double->single conversion */
5224                         amd64_sse_cvtsd2ss_reg_reg (code, AMD64_XMM15, ins->sreg1);
5225                         amd64_sse_movss_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, AMD64_XMM15);
5226                         break;
5227                 case OP_LOADR4_MEMBASE:
5228                         amd64_sse_movss_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset);
5229                         amd64_sse_cvtss2sd_reg_reg (code, ins->dreg, ins->dreg);
5230                         break;
5231                 case OP_ICONV_TO_R4: /* FIXME: change precision */
5232                 case OP_ICONV_TO_R8:
5233                         amd64_sse_cvtsi2sd_reg_reg_size (code, ins->dreg, ins->sreg1, 4);
5234                         break;
5235                 case OP_LCONV_TO_R4: /* FIXME: change precision */
5236                 case OP_LCONV_TO_R8:
5237                         amd64_sse_cvtsi2sd_reg_reg (code, ins->dreg, ins->sreg1);
5238                         break;
5239                 case OP_FCONV_TO_R4:
5240                         /* FIXME: nothing to do ?? */
5241                         break;
5242                 case OP_FCONV_TO_I1:
5243                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 1, TRUE);
5244                         break;
5245                 case OP_FCONV_TO_U1:
5246                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 1, FALSE);
5247                         break;
5248                 case OP_FCONV_TO_I2:
5249                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 2, TRUE);
5250                         break;
5251                 case OP_FCONV_TO_U2:
5252                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 2, FALSE);
5253                         break;
5254                 case OP_FCONV_TO_U4:
5255                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 4, FALSE);                  
5256                         break;
5257                 case OP_FCONV_TO_I4:
5258                 case OP_FCONV_TO_I:
5259                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 4, TRUE);
5260                         break;
5261                 case OP_FCONV_TO_I8:
5262                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 8, TRUE);
5263                         break;
5264                 case OP_LCONV_TO_R_UN: { 
5265                         guint8 *br [2];
5266
5267                         /* Based on gcc code */
5268                         amd64_test_reg_reg (code, ins->sreg1, ins->sreg1);
5269                         br [0] = code; x86_branch8 (code, X86_CC_S, 0, TRUE);
5270
5271                         /* Positive case */
5272                         amd64_sse_cvtsi2sd_reg_reg (code, ins->dreg, ins->sreg1);
5273                         br [1] = code; x86_jump8 (code, 0);
5274                         amd64_patch (br [0], code);
5275
5276                         /* Negative case */
5277                         /* Save to the red zone */
5278                         amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RAX, 8);
5279                         amd64_mov_membase_reg (code, AMD64_RSP, -16, AMD64_RCX, 8);
5280                         amd64_mov_reg_reg (code, AMD64_RCX, ins->sreg1, 8);
5281                         amd64_mov_reg_reg (code, AMD64_RAX, ins->sreg1, 8);
5282                         amd64_alu_reg_imm (code, X86_AND, AMD64_RCX, 1);
5283                         amd64_shift_reg_imm (code, X86_SHR, AMD64_RAX, 1);
5284                         amd64_alu_reg_imm (code, X86_OR, AMD64_RAX, AMD64_RCX);
5285                         amd64_sse_cvtsi2sd_reg_reg (code, ins->dreg, AMD64_RAX);
5286                         amd64_sse_addsd_reg_reg (code, ins->dreg, ins->dreg);
5287                         /* Restore */
5288                         amd64_mov_reg_membase (code, AMD64_RCX, AMD64_RSP, -16, 8);
5289                         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RSP, -8, 8);
5290                         amd64_patch (br [1], code);
5291                         break;
5292                 }
5293                 case OP_LCONV_TO_OVF_U4:
5294                         amd64_alu_reg_imm (code, X86_CMP, ins->sreg1, 0);
5295                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_LT, TRUE, "OverflowException");
5296                         amd64_mov_reg_reg (code, ins->dreg, ins->sreg1, 8);
5297                         break;
5298                 case OP_LCONV_TO_OVF_I4_UN:
5299                         amd64_alu_reg_imm (code, X86_CMP, ins->sreg1, 0x7fffffff);
5300                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_GT, FALSE, "OverflowException");
5301                         amd64_mov_reg_reg (code, ins->dreg, ins->sreg1, 8);
5302                         break;
5303                 case OP_FMOVE:
5304                         if (ins->dreg != ins->sreg1)
5305                                 amd64_sse_movsd_reg_reg (code, ins->dreg, ins->sreg1);
5306                         break;
5307                 case OP_FADD:
5308                         amd64_sse_addsd_reg_reg (code, ins->dreg, ins->sreg2);
5309                         break;
5310                 case OP_FSUB:
5311                         amd64_sse_subsd_reg_reg (code, ins->dreg, ins->sreg2);
5312                         break;          
5313                 case OP_FMUL:
5314                         amd64_sse_mulsd_reg_reg (code, ins->dreg, ins->sreg2);
5315                         break;          
5316                 case OP_FDIV:
5317                         amd64_sse_divsd_reg_reg (code, ins->dreg, ins->sreg2);
5318                         break;          
5319                 case OP_FNEG: {
5320                         static double r8_0 = -0.0;
5321
5322                         g_assert (ins->sreg1 == ins->dreg);
5323                                         
5324                         mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_R8, &r8_0);
5325                         amd64_sse_xorpd_reg_membase (code, ins->dreg, AMD64_RIP, 0);
5326                         break;
5327                 }
5328                 case OP_SIN:
5329                         EMIT_SSE2_FPFUNC (code, fsin, ins->dreg, ins->sreg1);
5330                         break;          
5331                 case OP_COS:
5332                         EMIT_SSE2_FPFUNC (code, fcos, ins->dreg, ins->sreg1);
5333                         break;          
5334                 case OP_ABS: {
5335                         static guint64 d = 0x7fffffffffffffffUL;
5336
5337                         g_assert (ins->sreg1 == ins->dreg);
5338                                         
5339                         mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_R8, &d);
5340                         amd64_sse_andpd_reg_membase (code, ins->dreg, AMD64_RIP, 0);
5341                         break;          
5342                 }
5343                 case OP_SQRT:
5344                         EMIT_SSE2_FPFUNC (code, fsqrt, ins->dreg, ins->sreg1);
5345                         break;
5346                 case OP_IMIN:
5347                         g_assert (cfg->opt & MONO_OPT_CMOV);
5348                         g_assert (ins->dreg == ins->sreg1);
5349                         amd64_alu_reg_reg_size (code, X86_CMP, ins->sreg1, ins->sreg2, 4);
5350                         amd64_cmov_reg_size (code, X86_CC_GT, TRUE, ins->dreg, ins->sreg2, 4);
5351                         break;
5352                 case OP_IMIN_UN:
5353                         g_assert (cfg->opt & MONO_OPT_CMOV);
5354                         g_assert (ins->dreg == ins->sreg1);
5355                         amd64_alu_reg_reg_size (code, X86_CMP, ins->sreg1, ins->sreg2, 4);
5356                         amd64_cmov_reg_size (code, X86_CC_GT, FALSE, ins->dreg, ins->sreg2, 4);
5357                         break;
5358                 case OP_IMAX:
5359                         g_assert (cfg->opt & MONO_OPT_CMOV);
5360                         g_assert (ins->dreg == ins->sreg1);
5361                         amd64_alu_reg_reg_size (code, X86_CMP, ins->sreg1, ins->sreg2, 4);
5362                         amd64_cmov_reg_size (code, X86_CC_LT, TRUE, ins->dreg, ins->sreg2, 4);
5363                         break;
5364                 case OP_IMAX_UN:
5365                         g_assert (cfg->opt & MONO_OPT_CMOV);
5366                         g_assert (ins->dreg == ins->sreg1);
5367                         amd64_alu_reg_reg_size (code, X86_CMP, ins->sreg1, ins->sreg2, 4);
5368                         amd64_cmov_reg_size (code, X86_CC_LT, FALSE, ins->dreg, ins->sreg2, 4);
5369                         break;
5370                 case OP_LMIN:
5371                         g_assert (cfg->opt & MONO_OPT_CMOV);
5372                         g_assert (ins->dreg == ins->sreg1);
5373                         amd64_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2);
5374                         amd64_cmov_reg (code, X86_CC_GT, TRUE, ins->dreg, ins->sreg2);
5375                         break;
5376                 case OP_LMIN_UN:
5377                         g_assert (cfg->opt & MONO_OPT_CMOV);
5378                         g_assert (ins->dreg == ins->sreg1);
5379                         amd64_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2);
5380                         amd64_cmov_reg (code, X86_CC_GT, FALSE, ins->dreg, ins->sreg2);
5381                         break;
5382                 case OP_LMAX:
5383                         g_assert (cfg->opt & MONO_OPT_CMOV);
5384                         g_assert (ins->dreg == ins->sreg1);
5385                         amd64_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2);
5386                         amd64_cmov_reg (code, X86_CC_LT, TRUE, ins->dreg, ins->sreg2);
5387                         break;
5388                 case OP_LMAX_UN:
5389                         g_assert (cfg->opt & MONO_OPT_CMOV);
5390                         g_assert (ins->dreg == ins->sreg1);
5391                         amd64_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2);
5392                         amd64_cmov_reg (code, X86_CC_LT, FALSE, ins->dreg, ins->sreg2);
5393                         break;  
5394                 case OP_X86_FPOP:
5395                         break;          
5396                 case OP_FCOMPARE:
5397                         /* 
5398                          * The two arguments are swapped because the fbranch instructions
5399                          * depend on this for the non-sse case to work.
5400                          */
5401                         amd64_sse_comisd_reg_reg (code, ins->sreg2, ins->sreg1);
5402                         break;
5403                 case OP_FCEQ: {
5404                         /* zeroing the register at the start results in 
5405                          * shorter and faster code (we can also remove the widening op)
5406                          */
5407                         guchar *unordered_check;
5408                         amd64_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
5409                         amd64_sse_comisd_reg_reg (code, ins->sreg1, ins->sreg2);
5410                         unordered_check = code;
5411                         x86_branch8 (code, X86_CC_P, 0, FALSE);
5412                         amd64_set_reg (code, X86_CC_EQ, ins->dreg, FALSE);
5413                         amd64_patch (unordered_check, code);
5414                         break;
5415                 }
5416                 case OP_FCLT:
5417                 case OP_FCLT_UN:
5418                         /* zeroing the register at the start results in 
5419                          * shorter and faster code (we can also remove the widening op)
5420                          */
5421                         amd64_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
5422                         amd64_sse_comisd_reg_reg (code, ins->sreg2, ins->sreg1);
5423                         if (ins->opcode == OP_FCLT_UN) {
5424                                 guchar *unordered_check = code;
5425                                 guchar *jump_to_end;
5426                                 x86_branch8 (code, X86_CC_P, 0, FALSE);
5427                                 amd64_set_reg (code, X86_CC_GT, ins->dreg, FALSE);
5428                                 jump_to_end = code;
5429                                 x86_jump8 (code, 0);
5430                                 amd64_patch (unordered_check, code);
5431                                 amd64_inc_reg (code, ins->dreg);
5432                                 amd64_patch (jump_to_end, code);
5433                         } else {
5434                                 amd64_set_reg (code, X86_CC_GT, ins->dreg, FALSE);
5435                         }
5436                         break;
5437                 case OP_FCGT:
5438                 case OP_FCGT_UN: {
5439                         /* zeroing the register at the start results in 
5440                          * shorter and faster code (we can also remove the widening op)
5441                          */
5442                         guchar *unordered_check;
5443                         amd64_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
5444                         amd64_sse_comisd_reg_reg (code, ins->sreg2, ins->sreg1);
5445                         if (ins->opcode == OP_FCGT) {
5446                                 unordered_check = code;
5447                                 x86_branch8 (code, X86_CC_P, 0, FALSE);
5448                                 amd64_set_reg (code, X86_CC_LT, ins->dreg, FALSE);
5449                                 amd64_patch (unordered_check, code);
5450                         } else {
5451                                 amd64_set_reg (code, X86_CC_LT, ins->dreg, FALSE);
5452                         }
5453                         break;
5454                 }
5455                 case OP_FCLT_MEMBASE:
5456                 case OP_FCGT_MEMBASE:
5457                 case OP_FCLT_UN_MEMBASE:
5458                 case OP_FCGT_UN_MEMBASE:
5459                 case OP_FCEQ_MEMBASE: {
5460                         guchar *unordered_check, *jump_to_end;
5461                         int x86_cond;
5462
5463                         amd64_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
5464                         amd64_sse_comisd_reg_membase (code, ins->sreg1, ins->sreg2, ins->inst_offset);
5465
5466                         switch (ins->opcode) {
5467                         case OP_FCEQ_MEMBASE:
5468                                 x86_cond = X86_CC_EQ;
5469                                 break;
5470                         case OP_FCLT_MEMBASE:
5471                         case OP_FCLT_UN_MEMBASE:
5472                                 x86_cond = X86_CC_LT;
5473                                 break;
5474                         case OP_FCGT_MEMBASE:
5475                         case OP_FCGT_UN_MEMBASE:
5476                                 x86_cond = X86_CC_GT;
5477                                 break;
5478                         default:
5479                                 g_assert_not_reached ();
5480                         }
5481
5482                         unordered_check = code;
5483                         x86_branch8 (code, X86_CC_P, 0, FALSE);
5484                         amd64_set_reg (code, x86_cond, ins->dreg, FALSE);
5485
5486                         switch (ins->opcode) {
5487                         case OP_FCEQ_MEMBASE:
5488                         case OP_FCLT_MEMBASE:
5489                         case OP_FCGT_MEMBASE:
5490                                 amd64_patch (unordered_check, code);
5491                                 break;
5492                         case OP_FCLT_UN_MEMBASE:
5493                         case OP_FCGT_UN_MEMBASE:
5494                                 jump_to_end = code;
5495                                 x86_jump8 (code, 0);
5496                                 amd64_patch (unordered_check, code);
5497                                 amd64_inc_reg (code, ins->dreg);
5498                                 amd64_patch (jump_to_end, code);
5499                                 break;
5500                         default:
5501                                 break;
5502                         }
5503                         break;
5504                 }
5505                 case OP_FBEQ: {
5506                         guchar *jump = code;
5507                         x86_branch8 (code, X86_CC_P, 0, TRUE);
5508                         EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
5509                         amd64_patch (jump, code);
5510                         break;
5511                 }
5512                 case OP_FBNE_UN:
5513                         /* Branch if C013 != 100 */
5514                         /* branch if !ZF or (PF|CF) */
5515                         EMIT_COND_BRANCH (ins, X86_CC_NE, FALSE);
5516                         EMIT_COND_BRANCH (ins, X86_CC_P, FALSE);
5517                         EMIT_COND_BRANCH (ins, X86_CC_B, FALSE);
5518                         break;
5519                 case OP_FBLT:
5520                         EMIT_COND_BRANCH (ins, X86_CC_GT, FALSE);
5521                         break;
5522                 case OP_FBLT_UN:
5523                         EMIT_COND_BRANCH (ins, X86_CC_P, FALSE);
5524                         EMIT_COND_BRANCH (ins, X86_CC_GT, FALSE);
5525                         break;
5526                 case OP_FBGT:
5527                 case OP_FBGT_UN:
5528                         if (ins->opcode == OP_FBGT) {
5529                                 guchar *br1;
5530
5531                                 /* skip branch if C1=1 */
5532                                 br1 = code;
5533                                 x86_branch8 (code, X86_CC_P, 0, FALSE);
5534                                 /* branch if (C0 | C3) = 1 */
5535                                 EMIT_COND_BRANCH (ins, X86_CC_LT, FALSE);
5536                                 amd64_patch (br1, code);
5537                                 break;
5538                         } else {
5539                                 EMIT_COND_BRANCH (ins, X86_CC_LT, FALSE);
5540                         }
5541                         break;
5542                 case OP_FBGE: {
5543                         /* Branch if C013 == 100 or 001 */
5544                         guchar *br1;
5545
5546                         /* skip branch if C1=1 */
5547                         br1 = code;
5548                         x86_branch8 (code, X86_CC_P, 0, FALSE);
5549                         /* branch if (C0 | C3) = 1 */
5550                         EMIT_COND_BRANCH (ins, X86_CC_BE, FALSE);
5551                         amd64_patch (br1, code);
5552                         break;
5553                 }
5554                 case OP_FBGE_UN:
5555                         /* Branch if C013 == 000 */
5556                         EMIT_COND_BRANCH (ins, X86_CC_LE, FALSE);
5557                         break;
5558                 case OP_FBLE: {
5559                         /* Branch if C013=000 or 100 */
5560                         guchar *br1;
5561
5562                         /* skip branch if C1=1 */
5563                         br1 = code;
5564                         x86_branch8 (code, X86_CC_P, 0, FALSE);
5565                         /* branch if C0=0 */
5566                         EMIT_COND_BRANCH (ins, X86_CC_NB, FALSE);
5567                         amd64_patch (br1, code);
5568                         break;
5569                 }
5570                 case OP_FBLE_UN:
5571                         /* Branch if C013 != 001 */
5572                         EMIT_COND_BRANCH (ins, X86_CC_P, FALSE);
5573                         EMIT_COND_BRANCH (ins, X86_CC_GE, FALSE);
5574                         break;
5575                 case OP_CKFINITE:
5576                         /* Transfer value to the fp stack */
5577                         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 16);
5578                         amd64_movsd_membase_reg (code, AMD64_RSP, 0, ins->sreg1);
5579                         amd64_fld_membase (code, AMD64_RSP, 0, TRUE);
5580
5581                         amd64_push_reg (code, AMD64_RAX);
5582                         amd64_fxam (code);
5583                         amd64_fnstsw (code);
5584                         amd64_alu_reg_imm (code, X86_AND, AMD64_RAX, 0x4100);
5585                         amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, X86_FP_C0);
5586                         amd64_pop_reg (code, AMD64_RAX);
5587                         amd64_fstp (code, 0);
5588                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_EQ, FALSE, "ArithmeticException");
5589                         amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 16);
5590                         break;
5591                 case OP_TLS_GET: {
5592                         code = mono_amd64_emit_tls_get (code, ins->dreg, ins->inst_offset);
5593                         break;
5594                 }
5595                 case OP_MEMORY_BARRIER: {
5596                         switch (ins->backend.memory_barrier_kind) {
5597                         case StoreLoadBarrier:
5598                         case FullBarrier:
5599                                 /* http://blogs.sun.com/dave/resource/NHM-Pipeline-Blog-V2.txt */
5600                                 x86_prefix (code, X86_LOCK_PREFIX);
5601                                 amd64_alu_membase_imm (code, X86_ADD, AMD64_RSP, 0, 0);
5602                                 break;
5603                         }
5604                         break;
5605                 }
5606                 case OP_ATOMIC_ADD_I4:
5607                 case OP_ATOMIC_ADD_I8: {
5608                         int dreg = ins->dreg;
5609                         guint32 size = (ins->opcode == OP_ATOMIC_ADD_I4) ? 4 : 8;
5610
5611                         if (dreg == ins->inst_basereg)
5612                                 dreg = AMD64_R11;
5613                         
5614                         if (dreg != ins->sreg2)
5615                                 amd64_mov_reg_reg (code, ins->dreg, ins->sreg2, size);
5616
5617                         x86_prefix (code, X86_LOCK_PREFIX);
5618                         amd64_xadd_membase_reg (code, ins->inst_basereg, ins->inst_offset, dreg, size);
5619
5620                         if (dreg != ins->dreg)
5621                                 amd64_mov_reg_reg (code, ins->dreg, dreg, size);
5622
5623                         break;
5624                 }
5625                 case OP_ATOMIC_ADD_NEW_I4:
5626                 case OP_ATOMIC_ADD_NEW_I8: {
5627                         int dreg = ins->dreg;
5628                         guint32 size = (ins->opcode == OP_ATOMIC_ADD_NEW_I4) ? 4 : 8;
5629
5630                         if ((dreg == ins->sreg2) || (dreg == ins->inst_basereg))
5631                                 dreg = AMD64_R11;
5632
5633                         amd64_mov_reg_reg (code, dreg, ins->sreg2, size);
5634                         amd64_prefix (code, X86_LOCK_PREFIX);
5635                         amd64_xadd_membase_reg (code, ins->inst_basereg, ins->inst_offset, dreg, size);
5636                         /* dreg contains the old value, add with sreg2 value */
5637                         amd64_alu_reg_reg_size (code, X86_ADD, dreg, ins->sreg2, size);
5638                         
5639                         if (ins->dreg != dreg)
5640                                 amd64_mov_reg_reg (code, ins->dreg, dreg, size);
5641
5642                         break;
5643                 }
5644                 case OP_ATOMIC_EXCHANGE_I4:
5645                 case OP_ATOMIC_EXCHANGE_I8: {
5646                         guchar *br[2];
5647                         int sreg2 = ins->sreg2;
5648                         int breg = ins->inst_basereg;
5649                         guint32 size;
5650                         gboolean need_push = FALSE, rdx_pushed = FALSE;
5651
5652                         if (ins->opcode == OP_ATOMIC_EXCHANGE_I8)
5653                                 size = 8;
5654                         else
5655                                 size = 4;
5656
5657                         /* 
5658                          * See http://msdn.microsoft.com/en-us/magazine/cc302329.aspx for
5659                          * an explanation of how this works.
5660                          */
5661
5662                         /* cmpxchg uses eax as comperand, need to make sure we can use it
5663                          * hack to overcome limits in x86 reg allocator 
5664                          * (req: dreg == eax and sreg2 != eax and breg != eax) 
5665                          */
5666                         g_assert (ins->dreg == AMD64_RAX);
5667
5668                         if (breg == AMD64_RAX && ins->sreg2 == AMD64_RAX)
5669                                 /* Highly unlikely, but possible */
5670                                 need_push = TRUE;
5671
5672                         /* The pushes invalidate rsp */
5673                         if ((breg == AMD64_RAX) || need_push) {
5674                                 amd64_mov_reg_reg (code, AMD64_R11, breg, 8);
5675                                 breg = AMD64_R11;
5676                         }
5677
5678                         /* We need the EAX reg for the comparand */
5679                         if (ins->sreg2 == AMD64_RAX) {
5680                                 if (breg != AMD64_R11) {
5681                                         amd64_mov_reg_reg (code, AMD64_R11, AMD64_RAX, 8);
5682                                         sreg2 = AMD64_R11;
5683                                 } else {
5684                                         g_assert (need_push);
5685                                         amd64_push_reg (code, AMD64_RDX);
5686                                         amd64_mov_reg_reg (code, AMD64_RDX, AMD64_RAX, size);
5687                                         sreg2 = AMD64_RDX;
5688                                         rdx_pushed = TRUE;
5689                                 }
5690                         }
5691
5692                         amd64_mov_reg_membase (code, AMD64_RAX, breg, ins->inst_offset, size);
5693
5694                         br [0] = code; amd64_prefix (code, X86_LOCK_PREFIX);
5695                         amd64_cmpxchg_membase_reg_size (code, breg, ins->inst_offset, sreg2, size);
5696                         br [1] = code; amd64_branch8 (code, X86_CC_NE, -1, FALSE);
5697                         amd64_patch (br [1], br [0]);
5698
5699                         if (rdx_pushed)
5700                                 amd64_pop_reg (code, AMD64_RDX);
5701
5702                         break;
5703                 }
5704                 case OP_ATOMIC_CAS_I4:
5705                 case OP_ATOMIC_CAS_I8: {
5706                         guint32 size;
5707
5708                         if (ins->opcode == OP_ATOMIC_CAS_I8)
5709                                 size = 8;
5710                         else
5711                                 size = 4;
5712
5713                         /* 
5714                          * See http://msdn.microsoft.com/en-us/magazine/cc302329.aspx for
5715                          * an explanation of how this works.
5716                          */
5717                         g_assert (ins->sreg3 == AMD64_RAX);
5718                         g_assert (ins->sreg1 != AMD64_RAX);
5719                         g_assert (ins->sreg1 != ins->sreg2);
5720
5721                         amd64_prefix (code, X86_LOCK_PREFIX);
5722                         amd64_cmpxchg_membase_reg_size (code, ins->sreg1, ins->inst_offset, ins->sreg2, size);
5723
5724                         if (ins->dreg != AMD64_RAX)
5725                                 amd64_mov_reg_reg (code, ins->dreg, AMD64_RAX, size);
5726                         break;
5727                 }
5728                 case OP_CARD_TABLE_WBARRIER: {
5729                         int ptr = ins->sreg1;
5730                         int value = ins->sreg2;
5731                         guchar *br;
5732                         int nursery_shift, card_table_shift;
5733                         gpointer card_table_mask;
5734                         size_t nursery_size;
5735
5736                         gpointer card_table = mono_gc_get_card_table (&card_table_shift, &card_table_mask);
5737                         guint64 nursery_start = (guint64)mono_gc_get_nursery (&nursery_shift, &nursery_size);
5738                         guint64 shifted_nursery_start = nursery_start >> nursery_shift;
5739
5740                         /*If either point to the stack we can simply avoid the WB. This happens due to
5741                          * optimizations revealing a stack store that was not visible when op_cardtable was emited.
5742                          */
5743                         if (ins->sreg1 == AMD64_RSP || ins->sreg2 == AMD64_RSP)
5744                                 continue;
5745
5746                         /*
5747                          * We need one register we can clobber, we choose EDX and make sreg1
5748                          * fixed EAX to work around limitations in the local register allocator.
5749                          * sreg2 might get allocated to EDX, but that is not a problem since
5750                          * we use it before clobbering EDX.
5751                          */
5752                         g_assert (ins->sreg1 == AMD64_RAX);
5753
5754                         /*
5755                          * This is the code we produce:
5756                          *
5757                          *   edx = value
5758                          *   edx >>= nursery_shift
5759                          *   cmp edx, (nursery_start >> nursery_shift)
5760                          *   jne done
5761                          *   edx = ptr
5762                          *   edx >>= card_table_shift
5763                          *   edx += cardtable
5764                          *   [edx] = 1
5765                          * done:
5766                          */
5767
5768                         if (value != AMD64_RDX)
5769                                 amd64_mov_reg_reg (code, AMD64_RDX, value, 8);
5770                         amd64_shift_reg_imm (code, X86_SHR, AMD64_RDX, nursery_shift);
5771                         if (shifted_nursery_start >> 31) {
5772                                 /*
5773                                  * The value we need to compare against is 64 bits, so we need
5774                                  * another spare register.  We use RBX, which we save and
5775                                  * restore.
5776                                  */
5777                                 amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RBX, 8);
5778                                 amd64_mov_reg_imm (code, AMD64_RBX, shifted_nursery_start);
5779                                 amd64_alu_reg_reg (code, X86_CMP, AMD64_RDX, AMD64_RBX);
5780                                 amd64_mov_reg_membase (code, AMD64_RBX, AMD64_RSP, -8, 8);
5781                         } else {
5782                                 amd64_alu_reg_imm (code, X86_CMP, AMD64_RDX, shifted_nursery_start);
5783                         }
5784                         br = code; x86_branch8 (code, X86_CC_NE, -1, FALSE);
5785                         amd64_mov_reg_reg (code, AMD64_RDX, ptr, 8);
5786                         amd64_shift_reg_imm (code, X86_SHR, AMD64_RDX, card_table_shift);
5787                         if (card_table_mask)
5788                                 amd64_alu_reg_imm (code, X86_AND, AMD64_RDX, (guint32)(guint64)card_table_mask);
5789
5790                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_GC_CARD_TABLE_ADDR, card_table);
5791                         amd64_alu_reg_membase (code, X86_ADD, AMD64_RDX, AMD64_RIP, 0);
5792
5793                         amd64_mov_membase_imm (code, AMD64_RDX, 0, 1, 1);
5794                         x86_patch (br, code);
5795                         break;
5796                 }
5797 #ifdef MONO_ARCH_SIMD_INTRINSICS
5798                 /* TODO: Some of these IR opcodes are marked as no clobber when they indeed do. */
5799                 case OP_ADDPS:
5800                         amd64_sse_addps_reg_reg (code, ins->sreg1, ins->sreg2);
5801                         break;
5802                 case OP_DIVPS:
5803                         amd64_sse_divps_reg_reg (code, ins->sreg1, ins->sreg2);
5804                         break;
5805                 case OP_MULPS:
5806                         amd64_sse_mulps_reg_reg (code, ins->sreg1, ins->sreg2);
5807                         break;
5808                 case OP_SUBPS:
5809                         amd64_sse_subps_reg_reg (code, ins->sreg1, ins->sreg2);
5810                         break;
5811                 case OP_MAXPS:
5812                         amd64_sse_maxps_reg_reg (code, ins->sreg1, ins->sreg2);
5813                         break;
5814                 case OP_MINPS:
5815                         amd64_sse_minps_reg_reg (code, ins->sreg1, ins->sreg2);
5816                         break;
5817                 case OP_COMPPS:
5818                         g_assert (ins->inst_c0 >= 0 && ins->inst_c0 <= 7);
5819                         amd64_sse_cmpps_reg_reg_imm (code, ins->sreg1, ins->sreg2, ins->inst_c0);
5820                         break;
5821                 case OP_ANDPS:
5822                         amd64_sse_andps_reg_reg (code, ins->sreg1, ins->sreg2);
5823                         break;
5824                 case OP_ANDNPS:
5825                         amd64_sse_andnps_reg_reg (code, ins->sreg1, ins->sreg2);
5826                         break;
5827                 case OP_ORPS:
5828                         amd64_sse_orps_reg_reg (code, ins->sreg1, ins->sreg2);
5829                         break;
5830                 case OP_XORPS:
5831                         amd64_sse_xorps_reg_reg (code, ins->sreg1, ins->sreg2);
5832                         break;
5833                 case OP_SQRTPS:
5834                         amd64_sse_sqrtps_reg_reg (code, ins->dreg, ins->sreg1);
5835                         break;
5836                 case OP_RSQRTPS:
5837                         amd64_sse_rsqrtps_reg_reg (code, ins->dreg, ins->sreg1);
5838                         break;
5839                 case OP_RCPPS:
5840                         amd64_sse_rcpps_reg_reg (code, ins->dreg, ins->sreg1);
5841                         break;
5842                 case OP_ADDSUBPS:
5843                         amd64_sse_addsubps_reg_reg (code, ins->sreg1, ins->sreg2);
5844                         break;
5845                 case OP_HADDPS:
5846                         amd64_sse_haddps_reg_reg (code, ins->sreg1, ins->sreg2);
5847                         break;
5848                 case OP_HSUBPS:
5849                         amd64_sse_hsubps_reg_reg (code, ins->sreg1, ins->sreg2);
5850                         break;
5851                 case OP_DUPPS_HIGH:
5852                         amd64_sse_movshdup_reg_reg (code, ins->dreg, ins->sreg1);
5853                         break;
5854                 case OP_DUPPS_LOW:
5855                         amd64_sse_movsldup_reg_reg (code, ins->dreg, ins->sreg1);
5856                         break;
5857
5858                 case OP_PSHUFLEW_HIGH:
5859                         g_assert (ins->inst_c0 >= 0 && ins->inst_c0 <= 0xFF);
5860                         amd64_sse_pshufhw_reg_reg_imm (code, ins->dreg, ins->sreg1, ins->inst_c0);
5861                         break;
5862                 case OP_PSHUFLEW_LOW:
5863                         g_assert (ins->inst_c0 >= 0 && ins->inst_c0 <= 0xFF);
5864                         amd64_sse_pshuflw_reg_reg_imm (code, ins->dreg, ins->sreg1, ins->inst_c0);
5865                         break;
5866                 case OP_PSHUFLED:
5867                         g_assert (ins->inst_c0 >= 0 && ins->inst_c0 <= 0xFF);
5868                         amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->sreg1, ins->inst_c0);
5869                         break;
5870                 case OP_SHUFPS:
5871                         g_assert (ins->inst_c0 >= 0 && ins->inst_c0 <= 0xFF);
5872                         amd64_sse_shufps_reg_reg_imm (code, ins->sreg1, ins->sreg2, ins->inst_c0);
5873                         break;
5874                 case OP_SHUFPD:
5875                         g_assert (ins->inst_c0 >= 0 && ins->inst_c0 <= 0x3);
5876                         amd64_sse_shufpd_reg_reg_imm (code, ins->sreg1, ins->sreg2, ins->inst_c0);
5877                         break;
5878
5879                 case OP_ADDPD:
5880                         amd64_sse_addpd_reg_reg (code, ins->sreg1, ins->sreg2);
5881                         break;
5882                 case OP_DIVPD:
5883                         amd64_sse_divpd_reg_reg (code, ins->sreg1, ins->sreg2);
5884                         break;
5885                 case OP_MULPD:
5886                         amd64_sse_mulpd_reg_reg (code, ins->sreg1, ins->sreg2);
5887                         break;
5888                 case OP_SUBPD:
5889                         amd64_sse_subpd_reg_reg (code, ins->sreg1, ins->sreg2);
5890                         break;
5891                 case OP_MAXPD:
5892                         amd64_sse_maxpd_reg_reg (code, ins->sreg1, ins->sreg2);
5893                         break;
5894                 case OP_MINPD:
5895                         amd64_sse_minpd_reg_reg (code, ins->sreg1, ins->sreg2);
5896                         break;
5897                 case OP_COMPPD:
5898                         g_assert (ins->inst_c0 >= 0 && ins->inst_c0 <= 7);
5899                         amd64_sse_cmppd_reg_reg_imm (code, ins->sreg1, ins->sreg2, ins->inst_c0);
5900                         break;
5901                 case OP_ANDPD:
5902                         amd64_sse_andpd_reg_reg (code, ins->sreg1, ins->sreg2);
5903                         break;
5904                 case OP_ANDNPD:
5905                         amd64_sse_andnpd_reg_reg (code, ins->sreg1, ins->sreg2);
5906                         break;
5907                 case OP_ORPD:
5908                         amd64_sse_orpd_reg_reg (code, ins->sreg1, ins->sreg2);
5909                         break;
5910                 case OP_XORPD:
5911                         amd64_sse_xorpd_reg_reg (code, ins->sreg1, ins->sreg2);
5912                         break;
5913                 case OP_SQRTPD:
5914                         amd64_sse_sqrtpd_reg_reg (code, ins->dreg, ins->sreg1);
5915                         break;
5916                 case OP_ADDSUBPD:
5917                         amd64_sse_addsubpd_reg_reg (code, ins->sreg1, ins->sreg2);
5918                         break;
5919                 case OP_HADDPD:
5920                         amd64_sse_haddpd_reg_reg (code, ins->sreg1, ins->sreg2);
5921                         break;
5922                 case OP_HSUBPD:
5923                         amd64_sse_hsubpd_reg_reg (code, ins->sreg1, ins->sreg2);
5924                         break;
5925                 case OP_DUPPD:
5926                         amd64_sse_movddup_reg_reg (code, ins->dreg, ins->sreg1);
5927                         break;
5928
5929                 case OP_EXTRACT_MASK:
5930                         amd64_sse_pmovmskb_reg_reg (code, ins->dreg, ins->sreg1);
5931                         break;
5932
5933                 case OP_PAND:
5934                         amd64_sse_pand_reg_reg (code, ins->sreg1, ins->sreg2);
5935                         break;
5936                 case OP_POR:
5937                         amd64_sse_por_reg_reg (code, ins->sreg1, ins->sreg2);
5938                         break;
5939                 case OP_PXOR:
5940                         amd64_sse_pxor_reg_reg (code, ins->sreg1, ins->sreg2);
5941                         break;
5942
5943                 case OP_PADDB:
5944                         amd64_sse_paddb_reg_reg (code, ins->sreg1, ins->sreg2);
5945                         break;
5946                 case OP_PADDW:
5947                         amd64_sse_paddw_reg_reg (code, ins->sreg1, ins->sreg2);
5948                         break;
5949                 case OP_PADDD:
5950                         amd64_sse_paddd_reg_reg (code, ins->sreg1, ins->sreg2);
5951                         break;
5952                 case OP_PADDQ:
5953                         amd64_sse_paddq_reg_reg (code, ins->sreg1, ins->sreg2);
5954                         break;
5955
5956                 case OP_PSUBB:
5957                         amd64_sse_psubb_reg_reg (code, ins->sreg1, ins->sreg2);
5958                         break;
5959                 case OP_PSUBW:
5960                         amd64_sse_psubw_reg_reg (code, ins->sreg1, ins->sreg2);
5961                         break;
5962                 case OP_PSUBD:
5963                         amd64_sse_psubd_reg_reg (code, ins->sreg1, ins->sreg2);
5964                         break;
5965                 case OP_PSUBQ:
5966                         amd64_sse_psubq_reg_reg (code, ins->sreg1, ins->sreg2);
5967                         break;
5968
5969                 case OP_PMAXB_UN:
5970                         amd64_sse_pmaxub_reg_reg (code, ins->sreg1, ins->sreg2);
5971                         break;
5972                 case OP_PMAXW_UN:
5973                         amd64_sse_pmaxuw_reg_reg (code, ins->sreg1, ins->sreg2);
5974                         break;
5975                 case OP_PMAXD_UN:
5976                         amd64_sse_pmaxud_reg_reg (code, ins->sreg1, ins->sreg2);
5977                         break;
5978                 
5979                 case OP_PMAXB:
5980                         amd64_sse_pmaxsb_reg_reg (code, ins->sreg1, ins->sreg2);
5981                         break;
5982                 case OP_PMAXW:
5983                         amd64_sse_pmaxsw_reg_reg (code, ins->sreg1, ins->sreg2);
5984                         break;
5985                 case OP_PMAXD:
5986                         amd64_sse_pmaxsd_reg_reg (code, ins->sreg1, ins->sreg2);
5987                         break;
5988
5989                 case OP_PAVGB_UN:
5990                         amd64_sse_pavgb_reg_reg (code, ins->sreg1, ins->sreg2);
5991                         break;
5992                 case OP_PAVGW_UN:
5993                         amd64_sse_pavgw_reg_reg (code, ins->sreg1, ins->sreg2);
5994                         break;
5995
5996                 case OP_PMINB_UN:
5997                         amd64_sse_pminub_reg_reg (code, ins->sreg1, ins->sreg2);
5998                         break;
5999                 case OP_PMINW_UN:
6000                         amd64_sse_pminuw_reg_reg (code, ins->sreg1, ins->sreg2);
6001                         break;
6002                 case OP_PMIND_UN:
6003                         amd64_sse_pminud_reg_reg (code, ins->sreg1, ins->sreg2);
6004                         break;
6005
6006                 case OP_PMINB:
6007                         amd64_sse_pminsb_reg_reg (code, ins->sreg1, ins->sreg2);
6008                         break;
6009                 case OP_PMINW:
6010                         amd64_sse_pminsw_reg_reg (code, ins->sreg1, ins->sreg2);
6011                         break;
6012                 case OP_PMIND:
6013                         amd64_sse_pminsd_reg_reg (code, ins->sreg1, ins->sreg2);
6014                         break;
6015
6016                 case OP_PCMPEQB:
6017                         amd64_sse_pcmpeqb_reg_reg (code, ins->sreg1, ins->sreg2);
6018                         break;
6019                 case OP_PCMPEQW:
6020                         amd64_sse_pcmpeqw_reg_reg (code, ins->sreg1, ins->sreg2);
6021                         break;
6022                 case OP_PCMPEQD:
6023                         amd64_sse_pcmpeqd_reg_reg (code, ins->sreg1, ins->sreg2);
6024                         break;
6025                 case OP_PCMPEQQ:
6026                         amd64_sse_pcmpeqq_reg_reg (code, ins->sreg1, ins->sreg2);
6027                         break;
6028
6029                 case OP_PCMPGTB:
6030                         amd64_sse_pcmpgtb_reg_reg (code, ins->sreg1, ins->sreg2);
6031                         break;
6032                 case OP_PCMPGTW:
6033                         amd64_sse_pcmpgtw_reg_reg (code, ins->sreg1, ins->sreg2);
6034                         break;
6035                 case OP_PCMPGTD:
6036                         amd64_sse_pcmpgtd_reg_reg (code, ins->sreg1, ins->sreg2);
6037                         break;
6038                 case OP_PCMPGTQ:
6039                         amd64_sse_pcmpgtq_reg_reg (code, ins->sreg1, ins->sreg2);
6040                         break;
6041
6042                 case OP_PSUM_ABS_DIFF:
6043                         amd64_sse_psadbw_reg_reg (code, ins->sreg1, ins->sreg2);
6044                         break;
6045
6046                 case OP_UNPACK_LOWB:
6047                         amd64_sse_punpcklbw_reg_reg (code, ins->sreg1, ins->sreg2);
6048                         break;
6049                 case OP_UNPACK_LOWW:
6050                         amd64_sse_punpcklwd_reg_reg (code, ins->sreg1, ins->sreg2);
6051                         break;
6052                 case OP_UNPACK_LOWD:
6053                         amd64_sse_punpckldq_reg_reg (code, ins->sreg1, ins->sreg2);
6054                         break;
6055                 case OP_UNPACK_LOWQ:
6056                         amd64_sse_punpcklqdq_reg_reg (code, ins->sreg1, ins->sreg2);
6057                         break;
6058                 case OP_UNPACK_LOWPS:
6059                         amd64_sse_unpcklps_reg_reg (code, ins->sreg1, ins->sreg2);
6060                         break;
6061                 case OP_UNPACK_LOWPD:
6062                         amd64_sse_unpcklpd_reg_reg (code, ins->sreg1, ins->sreg2);
6063                         break;
6064
6065                 case OP_UNPACK_HIGHB:
6066                         amd64_sse_punpckhbw_reg_reg (code, ins->sreg1, ins->sreg2);
6067                         break;
6068                 case OP_UNPACK_HIGHW:
6069                         amd64_sse_punpckhwd_reg_reg (code, ins->sreg1, ins->sreg2);
6070                         break;
6071                 case OP_UNPACK_HIGHD:
6072                         amd64_sse_punpckhdq_reg_reg (code, ins->sreg1, ins->sreg2);
6073                         break;
6074                 case OP_UNPACK_HIGHQ:
6075                         amd64_sse_punpckhqdq_reg_reg (code, ins->sreg1, ins->sreg2);
6076                         break;
6077                 case OP_UNPACK_HIGHPS:
6078                         amd64_sse_unpckhps_reg_reg (code, ins->sreg1, ins->sreg2);
6079                         break;
6080                 case OP_UNPACK_HIGHPD:
6081                         amd64_sse_unpckhpd_reg_reg (code, ins->sreg1, ins->sreg2);
6082                         break;
6083
6084                 case OP_PACKW:
6085                         amd64_sse_packsswb_reg_reg (code, ins->sreg1, ins->sreg2);
6086                         break;
6087                 case OP_PACKD:
6088                         amd64_sse_packssdw_reg_reg (code, ins->sreg1, ins->sreg2);
6089                         break;
6090                 case OP_PACKW_UN:
6091                         amd64_sse_packuswb_reg_reg (code, ins->sreg1, ins->sreg2);
6092                         break;
6093                 case OP_PACKD_UN:
6094                         amd64_sse_packusdw_reg_reg (code, ins->sreg1, ins->sreg2);
6095                         break;
6096
6097                 case OP_PADDB_SAT_UN:
6098                         amd64_sse_paddusb_reg_reg (code, ins->sreg1, ins->sreg2);
6099                         break;
6100                 case OP_PSUBB_SAT_UN:
6101                         amd64_sse_psubusb_reg_reg (code, ins->sreg1, ins->sreg2);
6102                         break;
6103                 case OP_PADDW_SAT_UN:
6104                         amd64_sse_paddusw_reg_reg (code, ins->sreg1, ins->sreg2);
6105                         break;
6106                 case OP_PSUBW_SAT_UN:
6107                         amd64_sse_psubusw_reg_reg (code, ins->sreg1, ins->sreg2);
6108                         break;
6109
6110                 case OP_PADDB_SAT:
6111                         amd64_sse_paddsb_reg_reg (code, ins->sreg1, ins->sreg2);
6112                         break;
6113                 case OP_PSUBB_SAT:
6114                         amd64_sse_psubsb_reg_reg (code, ins->sreg1, ins->sreg2);
6115                         break;
6116                 case OP_PADDW_SAT:
6117                         amd64_sse_paddsw_reg_reg (code, ins->sreg1, ins->sreg2);
6118                         break;
6119                 case OP_PSUBW_SAT:
6120                         amd64_sse_psubsw_reg_reg (code, ins->sreg1, ins->sreg2);
6121                         break;
6122                         
6123                 case OP_PMULW:
6124                         amd64_sse_pmullw_reg_reg (code, ins->sreg1, ins->sreg2);
6125                         break;
6126                 case OP_PMULD:
6127                         amd64_sse_pmulld_reg_reg (code, ins->sreg1, ins->sreg2);
6128                         break;
6129                 case OP_PMULQ:
6130                         amd64_sse_pmuludq_reg_reg (code, ins->sreg1, ins->sreg2);
6131                         break;
6132                 case OP_PMULW_HIGH_UN:
6133                         amd64_sse_pmulhuw_reg_reg (code, ins->sreg1, ins->sreg2);
6134                         break;
6135                 case OP_PMULW_HIGH:
6136                         amd64_sse_pmulhw_reg_reg (code, ins->sreg1, ins->sreg2);
6137                         break;
6138
6139                 case OP_PSHRW:
6140                         amd64_sse_psrlw_reg_imm (code, ins->dreg, ins->inst_imm);
6141                         break;
6142                 case OP_PSHRW_REG:
6143                         amd64_sse_psrlw_reg_reg (code, ins->dreg, ins->sreg2);
6144                         break;
6145
6146                 case OP_PSARW:
6147                         amd64_sse_psraw_reg_imm (code, ins->dreg, ins->inst_imm);
6148                         break;
6149                 case OP_PSARW_REG:
6150                         amd64_sse_psraw_reg_reg (code, ins->dreg, ins->sreg2);
6151                         break;
6152
6153                 case OP_PSHLW:
6154                         amd64_sse_psllw_reg_imm (code, ins->dreg, ins->inst_imm);
6155                         break;
6156                 case OP_PSHLW_REG:
6157                         amd64_sse_psllw_reg_reg (code, ins->dreg, ins->sreg2);
6158                         break;
6159
6160                 case OP_PSHRD:
6161                         amd64_sse_psrld_reg_imm (code, ins->dreg, ins->inst_imm);
6162                         break;
6163                 case OP_PSHRD_REG:
6164                         amd64_sse_psrld_reg_reg (code, ins->dreg, ins->sreg2);
6165                         break;
6166
6167                 case OP_PSARD:
6168                         amd64_sse_psrad_reg_imm (code, ins->dreg, ins->inst_imm);
6169                         break;
6170                 case OP_PSARD_REG:
6171                         amd64_sse_psrad_reg_reg (code, ins->dreg, ins->sreg2);
6172                         break;
6173
6174                 case OP_PSHLD:
6175                         amd64_sse_pslld_reg_imm (code, ins->dreg, ins->inst_imm);
6176                         break;
6177                 case OP_PSHLD_REG:
6178                         amd64_sse_pslld_reg_reg (code, ins->dreg, ins->sreg2);
6179                         break;
6180
6181                 case OP_PSHRQ:
6182                         amd64_sse_psrlq_reg_imm (code, ins->dreg, ins->inst_imm);
6183                         break;
6184                 case OP_PSHRQ_REG:
6185                         amd64_sse_psrlq_reg_reg (code, ins->dreg, ins->sreg2);
6186                         break;
6187                 
6188                 /*TODO: This is appart of the sse spec but not added
6189                 case OP_PSARQ:
6190                         amd64_sse_psraq_reg_imm (code, ins->dreg, ins->inst_imm);
6191                         break;
6192                 case OP_PSARQ_REG:
6193                         amd64_sse_psraq_reg_reg (code, ins->dreg, ins->sreg2);
6194                         break;  
6195                 */
6196         
6197                 case OP_PSHLQ:
6198                         amd64_sse_psllq_reg_imm (code, ins->dreg, ins->inst_imm);
6199                         break;
6200                 case OP_PSHLQ_REG:
6201                         amd64_sse_psllq_reg_reg (code, ins->dreg, ins->sreg2);
6202                         break;  
6203                 case OP_CVTDQ2PD:
6204                         amd64_sse_cvtdq2pd_reg_reg (code, ins->dreg, ins->sreg1);
6205                         break;
6206                 case OP_CVTDQ2PS:
6207                         amd64_sse_cvtdq2ps_reg_reg (code, ins->dreg, ins->sreg1);
6208                         break;
6209                 case OP_CVTPD2DQ:
6210                         amd64_sse_cvtpd2dq_reg_reg (code, ins->dreg, ins->sreg1);
6211                         break;
6212                 case OP_CVTPD2PS:
6213                         amd64_sse_cvtpd2ps_reg_reg (code, ins->dreg, ins->sreg1);
6214                         break;
6215                 case OP_CVTPS2DQ:
6216                         amd64_sse_cvtps2dq_reg_reg (code, ins->dreg, ins->sreg1);
6217                         break;
6218                 case OP_CVTPS2PD:
6219                         amd64_sse_cvtps2pd_reg_reg (code, ins->dreg, ins->sreg1);
6220                         break;
6221                 case OP_CVTTPD2DQ:
6222                         amd64_sse_cvttpd2dq_reg_reg (code, ins->dreg, ins->sreg1);
6223                         break;
6224                 case OP_CVTTPS2DQ:
6225                         amd64_sse_cvttps2dq_reg_reg (code, ins->dreg, ins->sreg1);
6226                         break;
6227
6228                 case OP_ICONV_TO_X:
6229                         amd64_movd_xreg_reg_size (code, ins->dreg, ins->sreg1, 4);
6230                         break;
6231                 case OP_EXTRACT_I4:
6232                         amd64_movd_reg_xreg_size (code, ins->dreg, ins->sreg1, 4);
6233                         break;
6234                 case OP_EXTRACT_I8:
6235                         if (ins->inst_c0) {
6236                                 amd64_movhlps_reg_reg (code, AMD64_XMM15, ins->sreg1);
6237                                 amd64_movd_reg_xreg_size (code, ins->dreg, AMD64_XMM15, 8);
6238                         } else {
6239                                 amd64_movd_reg_xreg_size (code, ins->dreg, ins->sreg1, 8);
6240                         }
6241                         break;
6242                 case OP_EXTRACT_I1:
6243                 case OP_EXTRACT_U1:
6244                         amd64_movd_reg_xreg_size (code, ins->dreg, ins->sreg1, 4);
6245                         if (ins->inst_c0)
6246                                 amd64_shift_reg_imm (code, X86_SHR, ins->dreg, ins->inst_c0 * 8);
6247                         amd64_widen_reg (code, ins->dreg, ins->dreg, ins->opcode == OP_EXTRACT_I1, FALSE);
6248                         break;
6249                 case OP_EXTRACT_I2:
6250                 case OP_EXTRACT_U2:
6251                         /*amd64_movd_reg_xreg_size (code, ins->dreg, ins->sreg1, 4);
6252                         if (ins->inst_c0)
6253                                 amd64_shift_reg_imm_size (code, X86_SHR, ins->dreg, 16, 4);*/
6254                         amd64_sse_pextrw_reg_reg_imm (code, ins->dreg, ins->sreg1, ins->inst_c0);
6255                         amd64_widen_reg_size (code, ins->dreg, ins->dreg, ins->opcode == OP_EXTRACT_I2, TRUE, 4);
6256                         break;
6257                 case OP_EXTRACT_R8:
6258                         if (ins->inst_c0)
6259                                 amd64_movhlps_reg_reg (code, ins->dreg, ins->sreg1);
6260                         else
6261                                 amd64_sse_movsd_reg_reg (code, ins->dreg, ins->sreg1);
6262                         break;
6263                 case OP_INSERT_I2:
6264                         amd64_sse_pinsrw_reg_reg_imm (code, ins->sreg1, ins->sreg2, ins->inst_c0);
6265                         break;
6266                 case OP_EXTRACTX_U2:
6267                         amd64_sse_pextrw_reg_reg_imm (code, ins->dreg, ins->sreg1, ins->inst_c0);
6268                         break;
6269                 case OP_INSERTX_U1_SLOW:
6270                         /*sreg1 is the extracted ireg (scratch)
6271                         /sreg2 is the to be inserted ireg (scratch)
6272                         /dreg is the xreg to receive the value*/
6273
6274                         /*clear the bits from the extracted word*/
6275                         amd64_alu_reg_imm (code, X86_AND, ins->sreg1, ins->inst_c0 & 1 ? 0x00FF : 0xFF00);
6276                         /*shift the value to insert if needed*/
6277                         if (ins->inst_c0 & 1)
6278                                 amd64_shift_reg_imm_size (code, X86_SHL, ins->sreg2, 8, 4);
6279                         /*join them together*/
6280                         amd64_alu_reg_reg (code, X86_OR, ins->sreg1, ins->sreg2);
6281                         amd64_sse_pinsrw_reg_reg_imm (code, ins->dreg, ins->sreg1, ins->inst_c0 / 2);
6282                         break;
6283                 case OP_INSERTX_I4_SLOW:
6284                         amd64_sse_pinsrw_reg_reg_imm (code, ins->dreg, ins->sreg2, ins->inst_c0 * 2);
6285                         amd64_shift_reg_imm (code, X86_SHR, ins->sreg2, 16);
6286                         amd64_sse_pinsrw_reg_reg_imm (code, ins->dreg, ins->sreg2, ins->inst_c0 * 2 + 1);
6287                         break;
6288                 case OP_INSERTX_I8_SLOW:
6289                         amd64_movd_xreg_reg_size(code, AMD64_XMM15, ins->sreg2, 8);
6290                         if (ins->inst_c0)
6291                                 amd64_movlhps_reg_reg (code, ins->dreg, AMD64_XMM15);
6292                         else
6293                                 amd64_sse_movsd_reg_reg (code, ins->dreg, AMD64_XMM15);
6294                         break;
6295
6296                 case OP_INSERTX_R4_SLOW:
6297                         switch (ins->inst_c0) {
6298                         case 0:
6299                                 amd64_sse_cvtsd2ss_reg_reg (code, ins->dreg, ins->sreg2);
6300                                 break;
6301                         case 1:
6302                                 amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, mono_simd_shuffle_mask(1, 0, 2, 3));
6303                                 amd64_sse_cvtsd2ss_reg_reg (code, ins->dreg, ins->sreg2);
6304                                 amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, mono_simd_shuffle_mask(1, 0, 2, 3));
6305                                 break;
6306                         case 2:
6307                                 amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, mono_simd_shuffle_mask(2, 1, 0, 3));
6308                                 amd64_sse_cvtsd2ss_reg_reg (code, ins->dreg, ins->sreg2);
6309                                 amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, mono_simd_shuffle_mask(2, 1, 0, 3));
6310                                 break;
6311                         case 3:
6312                                 amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, mono_simd_shuffle_mask(3, 1, 2, 0));
6313                                 amd64_sse_cvtsd2ss_reg_reg (code, ins->dreg, ins->sreg2);
6314                                 amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, mono_simd_shuffle_mask(3, 1, 2, 0));
6315                                 break;
6316                         }
6317                         break;
6318                 case OP_INSERTX_R8_SLOW:
6319                         if (ins->inst_c0)
6320                                 amd64_movlhps_reg_reg (code, ins->dreg, ins->sreg2);
6321                         else
6322                                 amd64_sse_movsd_reg_reg (code, ins->dreg, ins->sreg2);
6323                         break;
6324                 case OP_STOREX_MEMBASE_REG:
6325                 case OP_STOREX_MEMBASE:
6326                         amd64_sse_movups_membase_reg (code, ins->dreg, ins->inst_offset, ins->sreg1);
6327                         break;
6328                 case OP_LOADX_MEMBASE:
6329                         amd64_sse_movups_reg_membase (code, ins->dreg, ins->sreg1, ins->inst_offset);
6330                         break;
6331                 case OP_LOADX_ALIGNED_MEMBASE:
6332                         amd64_sse_movaps_reg_membase (code, ins->dreg, ins->sreg1, ins->inst_offset);
6333                         break;
6334                 case OP_STOREX_ALIGNED_MEMBASE_REG:
6335                         amd64_sse_movaps_membase_reg (code, ins->dreg, ins->inst_offset, ins->sreg1);
6336                         break;
6337                 case OP_STOREX_NTA_MEMBASE_REG:
6338                         amd64_sse_movntps_reg_membase (code, ins->dreg, ins->sreg1, ins->inst_offset);
6339                         break;
6340                 case OP_PREFETCH_MEMBASE:
6341                         amd64_sse_prefetch_reg_membase (code, ins->backend.arg_info, ins->sreg1, ins->inst_offset);
6342                         break;
6343
6344                 case OP_XMOVE:
6345                         /*FIXME the peephole pass should have killed this*/
6346                         if (ins->dreg != ins->sreg1)
6347                                 amd64_sse_movaps_reg_reg (code, ins->dreg, ins->sreg1);
6348                         break;          
6349                 case OP_XZERO:
6350                         amd64_sse_pxor_reg_reg (code, ins->dreg, ins->dreg);
6351                         break;
6352                 case OP_ICONV_TO_R8_RAW:
6353                         amd64_movd_xreg_reg_size (code, ins->dreg, ins->sreg1, 4);
6354                         amd64_sse_cvtss2sd_reg_reg (code, ins->dreg, ins->dreg);
6355                         break;
6356
6357                 case OP_FCONV_TO_R8_X:
6358                         amd64_sse_movsd_reg_reg (code, ins->dreg, ins->sreg1);
6359                         break;
6360
6361                 case OP_XCONV_R8_TO_I4:
6362                         amd64_sse_cvttsd2si_reg_xreg_size (code, ins->dreg, ins->sreg1, 4);
6363                         switch (ins->backend.source_opcode) {
6364                         case OP_FCONV_TO_I1:
6365                                 amd64_widen_reg (code, ins->dreg, ins->dreg, TRUE, FALSE);
6366                                 break;
6367                         case OP_FCONV_TO_U1:
6368                                 amd64_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
6369                                 break;
6370                         case OP_FCONV_TO_I2:
6371                                 amd64_widen_reg (code, ins->dreg, ins->dreg, TRUE, TRUE);
6372                                 break;
6373                         case OP_FCONV_TO_U2:
6374                                 amd64_widen_reg (code, ins->dreg, ins->dreg, FALSE, TRUE);
6375                                 break;
6376                         }                       
6377                         break;
6378
6379                 case OP_EXPAND_I2:
6380                         amd64_sse_pinsrw_reg_reg_imm (code, ins->dreg, ins->sreg1, 0);
6381                         amd64_sse_pinsrw_reg_reg_imm (code, ins->dreg, ins->sreg1, 1);
6382                         amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, 0);
6383                         break;
6384                 case OP_EXPAND_I4:
6385                         amd64_movd_xreg_reg_size (code, ins->dreg, ins->sreg1, 4);
6386                         amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, 0);
6387                         break;
6388                 case OP_EXPAND_I8:
6389                         amd64_movd_xreg_reg_size (code, ins->dreg, ins->sreg1, 8);
6390                         amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, 0x44);
6391                         break;
6392                 case OP_EXPAND_R4:
6393                         amd64_sse_movsd_reg_reg (code, ins->dreg, ins->sreg1);
6394                         amd64_sse_cvtsd2ss_reg_reg (code, ins->dreg, ins->dreg);
6395                         amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, 0);
6396                         break;
6397                 case OP_EXPAND_R8:
6398                         amd64_sse_movsd_reg_reg (code, ins->dreg, ins->sreg1);
6399                         amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, 0x44);
6400                         break;
6401 #endif
6402                 case OP_LIVERANGE_START: {
6403                         if (cfg->verbose_level > 1)
6404                                 printf ("R%d START=0x%x\n", MONO_VARINFO (cfg, ins->inst_c0)->vreg, (int)(code - cfg->native_code));
6405                         MONO_VARINFO (cfg, ins->inst_c0)->live_range_start = code - cfg->native_code;
6406                         break;
6407                 }
6408                 case OP_LIVERANGE_END: {
6409                         if (cfg->verbose_level > 1)
6410                                 printf ("R%d END=0x%x\n", MONO_VARINFO (cfg, ins->inst_c0)->vreg, (int)(code - cfg->native_code));
6411                         MONO_VARINFO (cfg, ins->inst_c0)->live_range_end = code - cfg->native_code;
6412                         break;
6413                 }
6414                 case OP_NACL_GC_SAFE_POINT: {
6415 #if defined(__native_client_codegen__)
6416                         code = emit_call (cfg, code, MONO_PATCH_INFO_ABS, (gpointer)mono_nacl_gc, TRUE);
6417 #endif
6418                         break;
6419                 }
6420                 case OP_GC_LIVENESS_DEF:
6421                 case OP_GC_LIVENESS_USE:
6422                 case OP_GC_PARAM_SLOT_LIVENESS_DEF:
6423                         ins->backend.pc_offset = code - cfg->native_code;
6424                         break;
6425                 case OP_GC_SPILL_SLOT_LIVENESS_DEF:
6426                         ins->backend.pc_offset = code - cfg->native_code;
6427                         bb->spill_slot_defs = g_slist_prepend_mempool (cfg->mempool, bb->spill_slot_defs, ins);
6428                         break;
6429                 default:
6430                         g_warning ("unknown opcode %s in %s()\n", mono_inst_name (ins->opcode), __FUNCTION__);
6431                         g_assert_not_reached ();
6432                 }
6433
6434                 if ((code - cfg->native_code - offset) > max_len) {
6435 #if !defined(__native_client_codegen__)
6436                         g_warning ("wrong maximal instruction length of instruction %s (expected %d, got %ld)",
6437                                    mono_inst_name (ins->opcode), max_len, code - cfg->native_code - offset);
6438                         g_assert_not_reached ();
6439 #endif
6440                 }
6441                
6442                 last_ins = ins;
6443                 last_offset = offset;
6444         }
6445
6446         cfg->code_len = code - cfg->native_code;
6447 }
6448
6449 #endif /* DISABLE_JIT */
6450
6451 void
6452 mono_arch_register_lowlevel_calls (void)
6453 {
6454         /* The signature doesn't matter */
6455         mono_register_jit_icall (mono_amd64_throw_exception, "mono_amd64_throw_exception", mono_create_icall_signature ("void"), TRUE);
6456 }
6457
6458 void
6459 mono_arch_patch_code (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *ji, MonoCodeManager *dyn_code_mp, gboolean run_cctors)
6460 {
6461         MonoJumpInfo *patch_info;
6462         gboolean compile_aot = !run_cctors;
6463
6464         for (patch_info = ji; patch_info; patch_info = patch_info->next) {
6465                 unsigned char *ip = patch_info->ip.i + code;
6466                 unsigned char *target;
6467
6468                 target = mono_resolve_patch_target (method, domain, code, patch_info, run_cctors);
6469
6470                 if (compile_aot) {
6471                         switch (patch_info->type) {
6472                         case MONO_PATCH_INFO_BB:
6473                         case MONO_PATCH_INFO_LABEL:
6474                                 break;
6475                         default:
6476                                 /* No need to patch these */
6477                                 continue;
6478                         }
6479                 }
6480
6481                 switch (patch_info->type) {
6482                 case MONO_PATCH_INFO_NONE:
6483                         continue;
6484                 case MONO_PATCH_INFO_METHOD_REL:
6485                 case MONO_PATCH_INFO_R8:
6486                 case MONO_PATCH_INFO_R4:
6487                         g_assert_not_reached ();
6488                         continue;
6489                 case MONO_PATCH_INFO_BB:
6490                         break;
6491                 default:
6492                         break;
6493                 }
6494
6495                 /* 
6496                  * Debug code to help track down problems where the target of a near call is
6497                  * is not valid.
6498                  */
6499                 if (amd64_is_near_call (ip)) {
6500                         gint64 disp = (guint8*)target - (guint8*)ip;
6501
6502                         if (!amd64_is_imm32 (disp)) {
6503                                 printf ("TYPE: %d\n", patch_info->type);
6504                                 switch (patch_info->type) {
6505                                 case MONO_PATCH_INFO_INTERNAL_METHOD:
6506                                         printf ("V: %s\n", patch_info->data.name);
6507                                         break;
6508                                 case MONO_PATCH_INFO_METHOD_JUMP:
6509                                 case MONO_PATCH_INFO_METHOD:
6510                                         printf ("V: %s\n", patch_info->data.method->name);
6511                                         break;
6512                                 default:
6513                                         break;
6514                                 }
6515                         }
6516                 }
6517
6518                 amd64_patch (ip, (gpointer)target);
6519         }
6520 }
6521
6522 #ifndef DISABLE_JIT
6523
6524 static int
6525 get_max_epilog_size (MonoCompile *cfg)
6526 {
6527         int max_epilog_size = 16;
6528         
6529         if (cfg->method->save_lmf)
6530                 max_epilog_size += 256;
6531         
6532         if (mono_jit_trace_calls != NULL)
6533                 max_epilog_size += 50;
6534
6535         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
6536                 max_epilog_size += 50;
6537
6538         max_epilog_size += (AMD64_NREG * 2);
6539
6540         return max_epilog_size;
6541 }
6542
6543 /*
6544  * This macro is used for testing whenever the unwinder works correctly at every point
6545  * where an async exception can happen.
6546  */
6547 /* This will generate a SIGSEGV at the given point in the code */
6548 #define async_exc_point(code) do { \
6549     if (mono_inject_async_exc_method && mono_method_desc_full_match (mono_inject_async_exc_method, cfg->method)) { \
6550          if (cfg->arch.async_point_count == mono_inject_async_exc_pos) \
6551              amd64_mov_reg_mem (code, AMD64_RAX, 0, 4); \
6552          cfg->arch.async_point_count ++; \
6553     } \
6554 } while (0)
6555
6556 guint8 *
6557 mono_arch_emit_prolog (MonoCompile *cfg)
6558 {
6559         MonoMethod *method = cfg->method;
6560         MonoBasicBlock *bb;
6561         MonoMethodSignature *sig;
6562         MonoInst *ins;
6563         int alloc_size, pos, i, cfa_offset, quad, max_epilog_size;
6564         guint8 *code;
6565         CallInfo *cinfo;
6566         MonoInst *lmf_var = cfg->arch.lmf_var;
6567         gboolean args_clobbered = FALSE;
6568         gboolean trace = FALSE;
6569 #ifdef __native_client_codegen__
6570         guint alignment_check;
6571 #endif
6572
6573         cfg->code_size =  MAX (cfg->header->code_size * 4, 10240);
6574
6575 #if defined(__default_codegen__)
6576         code = cfg->native_code = g_malloc (cfg->code_size);
6577 #elif defined(__native_client_codegen__)
6578         /* native_code_alloc is not 32-byte aligned, native_code is. */
6579         cfg->native_code_alloc = g_malloc (cfg->code_size + kNaClAlignment);
6580
6581         /* Align native_code to next nearest kNaclAlignment byte. */
6582         cfg->native_code = (uintptr_t)cfg->native_code_alloc + kNaClAlignment;
6583         cfg->native_code = (uintptr_t)cfg->native_code & ~kNaClAlignmentMask;
6584
6585         code = cfg->native_code;
6586
6587         alignment_check = (guint)cfg->native_code & kNaClAlignmentMask;
6588         g_assert (alignment_check == 0);
6589 #endif
6590
6591         if (mono_jit_trace_calls != NULL && mono_trace_eval (method))
6592                 trace = TRUE;
6593
6594         /* Amount of stack space allocated by register saving code */
6595         pos = 0;
6596
6597         /* Offset between RSP and the CFA */
6598         cfa_offset = 0;
6599
6600         /* 
6601          * The prolog consists of the following parts:
6602          * FP present:
6603          * - push rbp, mov rbp, rsp
6604          * - save callee saved regs using pushes
6605          * - allocate frame
6606          * - save rgctx if needed
6607          * - save lmf if needed
6608          * FP not present:
6609          * - allocate frame
6610          * - save rgctx if needed
6611          * - save lmf if needed
6612          * - save callee saved regs using moves
6613          */
6614
6615         // CFA = sp + 8
6616         cfa_offset = 8;
6617         mono_emit_unwind_op_def_cfa (cfg, code, AMD64_RSP, 8);
6618         // IP saved at CFA - 8
6619         mono_emit_unwind_op_offset (cfg, code, AMD64_RIP, -cfa_offset);
6620         async_exc_point (code);
6621         mini_gc_set_slot_type_from_cfa (cfg, -cfa_offset, SLOT_NOREF);
6622
6623         if (!cfg->arch.omit_fp) {
6624                 amd64_push_reg (code, AMD64_RBP);
6625                 cfa_offset += 8;
6626                 mono_emit_unwind_op_def_cfa_offset (cfg, code, cfa_offset);
6627                 mono_emit_unwind_op_offset (cfg, code, AMD64_RBP, - cfa_offset);
6628                 async_exc_point (code);
6629 #ifdef HOST_WIN32
6630                 mono_arch_unwindinfo_add_push_nonvol (&cfg->arch.unwindinfo, cfg->native_code, code, AMD64_RBP);
6631 #endif
6632                 /* These are handled automatically by the stack marking code */
6633                 mini_gc_set_slot_type_from_cfa (cfg, -cfa_offset, SLOT_NOREF);
6634                 
6635                 amd64_mov_reg_reg (code, AMD64_RBP, AMD64_RSP, sizeof(mgreg_t));
6636                 mono_emit_unwind_op_def_cfa_reg (cfg, code, AMD64_RBP);
6637                 async_exc_point (code);
6638 #ifdef HOST_WIN32
6639                 mono_arch_unwindinfo_add_set_fpreg (&cfg->arch.unwindinfo, cfg->native_code, code, AMD64_RBP);
6640 #endif
6641         }
6642
6643         /* Save callee saved registers */
6644         if (!cfg->arch.omit_fp && !method->save_lmf) {
6645                 int offset = cfa_offset;
6646
6647                 for (i = 0; i < AMD64_NREG; ++i)
6648                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
6649                                 amd64_push_reg (code, i);
6650                                 pos += 8; /* AMD64 push inst is always 8 bytes, no way to change it */
6651                                 offset += 8;
6652                                 mono_emit_unwind_op_offset (cfg, code, i, - offset);
6653                                 async_exc_point (code);
6654
6655                                 /* These are handled automatically by the stack marking code */
6656                                 mini_gc_set_slot_type_from_cfa (cfg, - offset, SLOT_NOREF);
6657                         }
6658         }
6659
6660         /* The param area is always at offset 0 from sp */
6661         /* This needs to be allocated here, since it has to come after the spill area */
6662         if (cfg->arch.no_pushes && cfg->param_area) {
6663                 if (cfg->arch.omit_fp)
6664                         // FIXME:
6665                         g_assert_not_reached ();
6666                 cfg->stack_offset += ALIGN_TO (cfg->param_area, sizeof(mgreg_t));
6667         }
6668
6669         if (cfg->arch.omit_fp) {
6670                 /* 
6671                  * On enter, the stack is misaligned by the pushing of the return
6672                  * address. It is either made aligned by the pushing of %rbp, or by
6673                  * this.
6674                  */
6675                 alloc_size = ALIGN_TO (cfg->stack_offset, 8);
6676                 if ((alloc_size % 16) == 0) {
6677                         alloc_size += 8;
6678                         /* Mark the padding slot as NOREF */
6679                         mini_gc_set_slot_type_from_cfa (cfg, -cfa_offset - sizeof (mgreg_t), SLOT_NOREF);
6680                 }
6681         } else {
6682                 alloc_size = ALIGN_TO (cfg->stack_offset, MONO_ARCH_FRAME_ALIGNMENT);
6683                 if (cfg->stack_offset != alloc_size) {
6684                         /* Mark the padding slot as NOREF */
6685                         mini_gc_set_slot_type_from_fp (cfg, -alloc_size + cfg->param_area, SLOT_NOREF);
6686                 }
6687                 cfg->arch.sp_fp_offset = alloc_size;
6688                 alloc_size -= pos;
6689         }
6690
6691         cfg->arch.stack_alloc_size = alloc_size;
6692
6693         /* Allocate stack frame */
6694         if (alloc_size) {
6695                 /* See mono_emit_stack_alloc */
6696 #if defined(HOST_WIN32) || defined(MONO_ARCH_SIGSEGV_ON_ALTSTACK)
6697                 guint32 remaining_size = alloc_size;
6698                 /*FIXME handle unbounded code expansion, we should use a loop in case of more than X interactions*/
6699                 guint32 required_code_size = ((remaining_size / 0x1000) + 1) * 10; /*10 is the max size of amd64_alu_reg_imm + amd64_test_membase_reg*/
6700                 guint32 offset = code - cfg->native_code;
6701                 if (G_UNLIKELY (required_code_size >= (cfg->code_size - offset))) {
6702                         while (required_code_size >= (cfg->code_size - offset))
6703                                 cfg->code_size *= 2;
6704                         cfg->native_code = mono_realloc_native_code (cfg);
6705                         code = cfg->native_code + offset;
6706                         cfg->stat_code_reallocs++;
6707                 }
6708
6709                 while (remaining_size >= 0x1000) {
6710                         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 0x1000);
6711                         if (cfg->arch.omit_fp) {
6712                                 cfa_offset += 0x1000;
6713                                 mono_emit_unwind_op_def_cfa_offset (cfg, code, cfa_offset);
6714                         }
6715                         async_exc_point (code);
6716 #ifdef HOST_WIN32
6717                         if (cfg->arch.omit_fp) 
6718                                 mono_arch_unwindinfo_add_alloc_stack (&cfg->arch.unwindinfo, cfg->native_code, code, 0x1000);
6719 #endif
6720
6721                         amd64_test_membase_reg (code, AMD64_RSP, 0, AMD64_RSP);
6722                         remaining_size -= 0x1000;
6723                 }
6724                 if (remaining_size) {
6725                         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, remaining_size);
6726                         if (cfg->arch.omit_fp) {
6727                                 cfa_offset += remaining_size;
6728                                 mono_emit_unwind_op_def_cfa_offset (cfg, code, cfa_offset);
6729                                 async_exc_point (code);
6730                         }
6731 #ifdef HOST_WIN32
6732                         if (cfg->arch.omit_fp) 
6733                                 mono_arch_unwindinfo_add_alloc_stack (&cfg->arch.unwindinfo, cfg->native_code, code, remaining_size);
6734 #endif
6735                 }
6736 #else
6737                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, alloc_size);
6738                 if (cfg->arch.omit_fp) {
6739                         cfa_offset += alloc_size;
6740                         mono_emit_unwind_op_def_cfa_offset (cfg, code, cfa_offset);
6741                         async_exc_point (code);
6742                 }
6743 #endif
6744         }
6745
6746         /* Stack alignment check */
6747 #if 0
6748         {
6749                 amd64_mov_reg_reg (code, AMD64_RAX, AMD64_RSP, 8);
6750                 amd64_alu_reg_imm (code, X86_AND, AMD64_RAX, 0xf);
6751                 amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, 0);
6752                 x86_branch8 (code, X86_CC_EQ, 2, FALSE);
6753                 amd64_breakpoint (code);
6754         }
6755 #endif
6756
6757 #ifndef TARGET_WIN32
6758         if (mini_get_debug_options ()->init_stacks) {
6759                 /* Fill the stack frame with a dummy value to force deterministic behavior */
6760         
6761                 /* Save registers to the red zone */
6762                 amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RDI, 8);
6763                 amd64_mov_membase_reg (code, AMD64_RSP, -16, AMD64_RCX, 8);
6764
6765                 amd64_mov_reg_imm (code, AMD64_RAX, 0x2a2a2a2a2a2a2a2a);
6766                 amd64_mov_reg_imm (code, AMD64_RCX, alloc_size / 8);
6767                 amd64_mov_reg_reg (code, AMD64_RDI, AMD64_RSP, 8);
6768
6769                 amd64_cld (code);
6770 #if defined(__default_codegen__)
6771                 amd64_prefix (code, X86_REP_PREFIX);
6772                 amd64_stosl (code);
6773 #elif defined(__native_client_codegen__)
6774                 /* NaCl stos pseudo-instruction */
6775                 amd64_codegen_pre (code);
6776                 /* First, clear the upper 32 bits of RDI (mov %edi, %edi)  */
6777                 amd64_mov_reg_reg (code, AMD64_RDI, AMD64_RDI, 4);
6778                 /* Add %r15 to %rdi using lea, condition flags unaffected. */
6779                 amd64_lea_memindex_size (code, AMD64_RDI, AMD64_R15, 0, AMD64_RDI, 0, 8);
6780                 amd64_prefix (code, X86_REP_PREFIX);
6781                 amd64_stosl (code);
6782                 amd64_codegen_post (code);
6783 #endif /* __native_client_codegen__ */
6784
6785                 amd64_mov_reg_membase (code, AMD64_RDI, AMD64_RSP, -8, 8);
6786                 amd64_mov_reg_membase (code, AMD64_RCX, AMD64_RSP, -16, 8);
6787         }
6788 #endif  
6789
6790         /* Save LMF */
6791         if (method->save_lmf) {
6792                 code = emit_setup_lmf (cfg, code, lmf_var->inst_offset, cfa_offset);
6793         }
6794
6795         /* Save callee saved registers */
6796         if (cfg->arch.omit_fp && !method->save_lmf) {
6797                 gint32 save_area_offset = cfg->arch.reg_save_area_offset;
6798
6799                 /* Save caller saved registers after sp is adjusted */
6800                 /* The registers are saved at the bottom of the frame */
6801                 /* FIXME: Optimize this so the regs are saved at the end of the frame in increasing order */
6802                 for (i = 0; i < AMD64_NREG; ++i)
6803                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
6804                                 amd64_mov_membase_reg (code, AMD64_RSP, save_area_offset, i, 8);
6805                                 mono_emit_unwind_op_offset (cfg, code, i, - (cfa_offset - save_area_offset));
6806
6807                                 /* These are handled automatically by the stack marking code */
6808                                 mini_gc_set_slot_type_from_cfa (cfg, - (cfa_offset - save_area_offset), SLOT_NOREF);
6809
6810                                 save_area_offset += 8;
6811                                 async_exc_point (code);
6812                         }
6813         }
6814
6815         /* store runtime generic context */
6816         if (cfg->rgctx_var) {
6817                 g_assert (cfg->rgctx_var->opcode == OP_REGOFFSET &&
6818                                 (cfg->rgctx_var->inst_basereg == AMD64_RBP || cfg->rgctx_var->inst_basereg == AMD64_RSP));
6819
6820                 amd64_mov_membase_reg (code, cfg->rgctx_var->inst_basereg, cfg->rgctx_var->inst_offset, MONO_ARCH_RGCTX_REG, sizeof(gpointer));
6821
6822                 mono_add_var_location (cfg, cfg->rgctx_var, TRUE, MONO_ARCH_RGCTX_REG, 0, 0, code - cfg->native_code);
6823                 mono_add_var_location (cfg, cfg->rgctx_var, FALSE, cfg->rgctx_var->inst_basereg, cfg->rgctx_var->inst_offset, code - cfg->native_code, 0);
6824         }
6825
6826         /* compute max_length in order to use short forward jumps */
6827         max_epilog_size = get_max_epilog_size (cfg);
6828         if (cfg->opt & MONO_OPT_BRANCH) {
6829                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
6830                         MonoInst *ins;
6831                         int max_length = 0;
6832
6833                         if (cfg->prof_options & MONO_PROFILE_COVERAGE)
6834                                 max_length += 6;
6835                         /* max alignment for loops */
6836                         if ((cfg->opt & MONO_OPT_LOOP) && bb_is_loop_start (bb))
6837                                 max_length += LOOP_ALIGNMENT;
6838 #ifdef __native_client_codegen__
6839                         /* max alignment for native client */
6840                         max_length += kNaClAlignment;
6841 #endif
6842
6843                         MONO_BB_FOR_EACH_INS (bb, ins) {
6844 #ifdef __native_client_codegen__
6845                                 {
6846                                         int space_in_block = kNaClAlignment -
6847                                                 ((max_length + cfg->code_len) & kNaClAlignmentMask);
6848                                         int max_len = ((guint8 *)ins_get_spec (ins->opcode))[MONO_INST_LEN];
6849                                         if (space_in_block < max_len && max_len < kNaClAlignment) {
6850                                                 max_length += space_in_block;
6851                                         }
6852                                 }
6853 #endif  /*__native_client_codegen__*/
6854                                 max_length += ((guint8 *)ins_get_spec (ins->opcode))[MONO_INST_LEN];
6855                         }
6856
6857                         /* Take prolog and epilog instrumentation into account */
6858                         if (bb == cfg->bb_entry || bb == cfg->bb_exit)
6859                                 max_length += max_epilog_size;
6860                         
6861                         bb->max_length = max_length;
6862                 }
6863         }
6864
6865         sig = mono_method_signature (method);
6866         pos = 0;
6867
6868         cinfo = cfg->arch.cinfo;
6869
6870         if (sig->ret->type != MONO_TYPE_VOID) {
6871                 /* Save volatile arguments to the stack */
6872                 if (cfg->vret_addr && (cfg->vret_addr->opcode != OP_REGVAR))
6873                         amd64_mov_membase_reg (code, cfg->vret_addr->inst_basereg, cfg->vret_addr->inst_offset, cinfo->ret.reg, 8);
6874         }
6875
6876         /* Keep this in sync with emit_load_volatile_arguments */
6877         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6878                 ArgInfo *ainfo = cinfo->args + i;
6879                 gint32 stack_offset;
6880                 MonoType *arg_type;
6881
6882                 ins = cfg->args [i];
6883
6884                 if ((ins->flags & MONO_INST_IS_DEAD) && !trace)
6885                         /* Unused arguments */
6886                         continue;
6887
6888                 if (sig->hasthis && (i == 0))
6889                         arg_type = &mono_defaults.object_class->byval_arg;
6890                 else
6891                         arg_type = sig->params [i - sig->hasthis];
6892
6893                 stack_offset = ainfo->offset + ARGS_OFFSET;
6894
6895                 if (cfg->globalra) {
6896                         /* All the other moves are done by the register allocator */
6897                         switch (ainfo->storage) {
6898                         case ArgInFloatSSEReg:
6899                                 amd64_sse_cvtss2sd_reg_reg (code, ainfo->reg, ainfo->reg);
6900                                 break;
6901                         case ArgValuetypeInReg:
6902                                 for (quad = 0; quad < 2; quad ++) {
6903                                         switch (ainfo->pair_storage [quad]) {
6904                                         case ArgInIReg:
6905                                                 amd64_mov_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof(mgreg_t)), ainfo->pair_regs [quad], sizeof(mgreg_t));
6906                                                 break;
6907                                         case ArgInFloatSSEReg:
6908                                                 amd64_movss_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof(mgreg_t)), ainfo->pair_regs [quad]);
6909                                                 break;
6910                                         case ArgInDoubleSSEReg:
6911                                                 amd64_movsd_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof(mgreg_t)), ainfo->pair_regs [quad]);
6912                                                 break;
6913                                         case ArgNone:
6914                                                 break;
6915                                         default:
6916                                                 g_assert_not_reached ();
6917                                         }
6918                                 }
6919                                 break;
6920                         default:
6921                                 break;
6922                         }
6923
6924                         continue;
6925                 }
6926
6927                 /* Save volatile arguments to the stack */
6928                 if (ins->opcode != OP_REGVAR) {
6929                         switch (ainfo->storage) {
6930                         case ArgInIReg: {
6931                                 guint32 size = 8;
6932
6933                                 /* FIXME: I1 etc */
6934                                 /*
6935                                 if (stack_offset & 0x1)
6936                                         size = 1;
6937                                 else if (stack_offset & 0x2)
6938                                         size = 2;
6939                                 else if (stack_offset & 0x4)
6940                                         size = 4;
6941                                 else
6942                                         size = 8;
6943                                 */
6944                                 amd64_mov_membase_reg (code, ins->inst_basereg, ins->inst_offset, ainfo->reg, size);
6945
6946                                 /*
6947                                  * Save the original location of 'this',
6948                                  * get_generic_info_from_stack_frame () needs this to properly look up
6949                                  * the argument value during the handling of async exceptions.
6950                                  */
6951                                 if (ins == cfg->args [0]) {
6952                                         mono_add_var_location (cfg, ins, TRUE, ainfo->reg, 0, 0, code - cfg->native_code);
6953                                         mono_add_var_location (cfg, ins, FALSE, ins->inst_basereg, ins->inst_offset, code - cfg->native_code, 0);
6954                                 }
6955                                 break;
6956                         }
6957                         case ArgInFloatSSEReg:
6958                                 amd64_movss_membase_reg (code, ins->inst_basereg, ins->inst_offset, ainfo->reg);
6959                                 break;
6960                         case ArgInDoubleSSEReg:
6961                                 amd64_movsd_membase_reg (code, ins->inst_basereg, ins->inst_offset, ainfo->reg);
6962                                 break;
6963                         case ArgValuetypeInReg:
6964                                 for (quad = 0; quad < 2; quad ++) {
6965                                         switch (ainfo->pair_storage [quad]) {
6966                                         case ArgInIReg:
6967                                                 amd64_mov_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof(mgreg_t)), ainfo->pair_regs [quad], sizeof(mgreg_t));
6968                                                 break;
6969                                         case ArgInFloatSSEReg:
6970                                                 amd64_movss_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof(mgreg_t)), ainfo->pair_regs [quad]);
6971                                                 break;
6972                                         case ArgInDoubleSSEReg:
6973                                                 amd64_movsd_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof(mgreg_t)), ainfo->pair_regs [quad]);
6974                                                 break;
6975                                         case ArgNone:
6976                                                 break;
6977                                         default:
6978                                                 g_assert_not_reached ();
6979                                         }
6980                                 }
6981                                 break;
6982                         case ArgValuetypeAddrInIReg:
6983                                 if (ainfo->pair_storage [0] == ArgInIReg)
6984                                         amd64_mov_membase_reg (code, ins->inst_left->inst_basereg, ins->inst_left->inst_offset, ainfo->pair_regs [0],  sizeof (gpointer));
6985                                 break;
6986                         default:
6987                                 break;
6988                         }
6989                 } else {
6990                         /* Argument allocated to (non-volatile) register */
6991                         switch (ainfo->storage) {
6992                         case ArgInIReg:
6993                                 amd64_mov_reg_reg (code, ins->dreg, ainfo->reg, 8);
6994                                 break;
6995                         case ArgOnStack:
6996                                 amd64_mov_reg_membase (code, ins->dreg, AMD64_RBP, ARGS_OFFSET + ainfo->offset, 8);
6997                                 break;
6998                         default:
6999                                 g_assert_not_reached ();
7000                         }
7001
7002                         if (ins == cfg->args [0]) {
7003                                 mono_add_var_location (cfg, ins, TRUE, ainfo->reg, 0, 0, code - cfg->native_code);
7004                                 mono_add_var_location (cfg, ins, TRUE, ins->dreg, 0, code - cfg->native_code, 0);
7005                         }
7006                 }
7007         }
7008
7009         if (method->save_lmf) {
7010                 code = emit_save_lmf (cfg, code, lmf_var->inst_offset, &args_clobbered);
7011         }
7012
7013         if (trace) {
7014                 args_clobbered = TRUE;
7015                 code = mono_arch_instrument_prolog (cfg, mono_trace_enter_method, code, TRUE);
7016         }
7017
7018         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
7019                 args_clobbered = TRUE;
7020
7021         /*
7022          * Optimize the common case of the first bblock making a call with the same
7023          * arguments as the method. This works because the arguments are still in their
7024          * original argument registers.
7025          * FIXME: Generalize this
7026          */
7027         if (!args_clobbered) {
7028                 MonoBasicBlock *first_bb = cfg->bb_entry;
7029                 MonoInst *next;
7030
7031                 next = mono_bb_first_ins (first_bb);
7032                 if (!next && first_bb->next_bb) {
7033                         first_bb = first_bb->next_bb;
7034                         next = mono_bb_first_ins (first_bb);
7035                 }
7036
7037                 if (first_bb->in_count > 1)
7038                         next = NULL;
7039
7040                 for (i = 0; next && i < sig->param_count + sig->hasthis; ++i) {
7041                         ArgInfo *ainfo = cinfo->args + i;
7042                         gboolean match = FALSE;
7043                         
7044                         ins = cfg->args [i];
7045                         if (ins->opcode != OP_REGVAR) {
7046                                 switch (ainfo->storage) {
7047                                 case ArgInIReg: {
7048                                         if (((next->opcode == OP_LOAD_MEMBASE) || (next->opcode == OP_LOADI4_MEMBASE)) && next->inst_basereg == ins->inst_basereg && next->inst_offset == ins->inst_offset) {
7049                                                 if (next->dreg == ainfo->reg) {
7050                                                         NULLIFY_INS (next);
7051                                                         match = TRUE;
7052                                                 } else {
7053                                                         next->opcode = OP_MOVE;
7054                                                         next->sreg1 = ainfo->reg;
7055                                                         /* Only continue if the instruction doesn't change argument regs */
7056                                                         if (next->dreg == ainfo->reg || next->dreg == AMD64_RAX)
7057                                                                 match = TRUE;
7058                                                 }
7059                                         }
7060                                         break;
7061                                 }
7062                                 default:
7063                                         break;
7064                                 }
7065                         } else {
7066                                 /* Argument allocated to (non-volatile) register */
7067                                 switch (ainfo->storage) {
7068                                 case ArgInIReg:
7069                                         if (next->opcode == OP_MOVE && next->sreg1 == ins->dreg && next->dreg == ainfo->reg) {
7070                                                 NULLIFY_INS (next);
7071                                                 match = TRUE;
7072                                         }
7073                                         break;
7074                                 default:
7075                                         break;
7076                                 }
7077                         }
7078
7079                         if (match) {
7080                                 next = next->next;
7081                                 //next = mono_inst_list_next (&next->node, &first_bb->ins_list);
7082                                 if (!next)
7083                                         break;
7084                         }
7085                 }
7086         }
7087
7088         if (cfg->gen_seq_points) {
7089                 MonoInst *info_var = cfg->arch.seq_point_info_var;
7090
7091                 /* Initialize seq_point_info_var */
7092                 if (cfg->compile_aot) {
7093                         /* Initialize the variable from a GOT slot */
7094                         /* Same as OP_AOTCONST */
7095                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_SEQ_POINT_INFO, cfg->method);
7096                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, sizeof(gpointer));
7097                         g_assert (info_var->opcode == OP_REGOFFSET);
7098                         amd64_mov_membase_reg (code, info_var->inst_basereg, info_var->inst_offset, AMD64_R11, 8);
7099                 }
7100
7101                 /* Initialize ss_trigger_page_var */
7102                 ins = cfg->arch.ss_trigger_page_var;
7103
7104                 g_assert (ins->opcode == OP_REGOFFSET);
7105
7106                 if (cfg->compile_aot) {
7107                         amd64_mov_reg_membase (code, AMD64_R11, info_var->inst_basereg, info_var->inst_offset, 8);
7108                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, G_STRUCT_OFFSET (SeqPointInfo, ss_trigger_page), 8);
7109                 } else {
7110                         amd64_mov_reg_imm (code, AMD64_R11, (guint64)ss_trigger_page);
7111                 }
7112                 amd64_mov_membase_reg (code, ins->inst_basereg, ins->inst_offset, AMD64_R11, 8);
7113         }
7114
7115         cfg->code_len = code - cfg->native_code;
7116
7117         g_assert (cfg->code_len < cfg->code_size);
7118
7119         return code;
7120 }
7121
7122 void
7123 mono_arch_emit_epilog (MonoCompile *cfg)
7124 {
7125         MonoMethod *method = cfg->method;
7126         int quad, pos, i;
7127         guint8 *code;
7128         int max_epilog_size;
7129         CallInfo *cinfo;
7130         gint32 lmf_offset = cfg->arch.lmf_var ? ((MonoInst*)cfg->arch.lmf_var)->inst_offset : -1;
7131         
7132         max_epilog_size = get_max_epilog_size (cfg);
7133
7134         while (cfg->code_len + max_epilog_size > (cfg->code_size - 16)) {
7135                 cfg->code_size *= 2;
7136                 cfg->native_code = mono_realloc_native_code (cfg);
7137                 cfg->stat_code_reallocs++;
7138         }
7139
7140         code = cfg->native_code + cfg->code_len;
7141
7142         if (mono_jit_trace_calls != NULL && mono_trace_eval (method))
7143                 code = mono_arch_instrument_epilog (cfg, mono_trace_leave_method, code, TRUE);
7144
7145         /* the code restoring the registers must be kept in sync with OP_JMP */
7146         pos = 0;
7147         
7148         if (method->save_lmf) {
7149                 /* check if we need to restore protection of the stack after a stack overflow */
7150                 if (mono_get_jit_tls_offset () != -1) {
7151                         guint8 *patch;
7152                         code = mono_amd64_emit_tls_get (code, AMD64_RCX, mono_get_jit_tls_offset ());
7153                         /* we load the value in a separate instruction: this mechanism may be
7154                          * used later as a safer way to do thread interruption
7155                          */
7156                         amd64_mov_reg_membase (code, AMD64_RCX, AMD64_RCX, G_STRUCT_OFFSET (MonoJitTlsData, restore_stack_prot), 8);
7157                         x86_alu_reg_imm (code, X86_CMP, X86_ECX, 0);
7158                         patch = code;
7159                         x86_branch8 (code, X86_CC_Z, 0, FALSE);
7160                         /* note that the call trampoline will preserve eax/edx */
7161                         x86_call_reg (code, X86_ECX);
7162                         x86_patch (patch, code);
7163                 } else {
7164                         /* FIXME: maybe save the jit tls in the prolog */
7165                 }
7166
7167                 code = emit_restore_lmf (cfg, code, lmf_offset);
7168
7169                 /* Restore caller saved regs */
7170                 if (cfg->used_int_regs & (1 << AMD64_RBP)) {
7171                         amd64_mov_reg_membase (code, AMD64_RBP, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbp), 8);
7172                 }
7173                 if (cfg->used_int_regs & (1 << AMD64_RBX)) {
7174                         amd64_mov_reg_membase (code, AMD64_RBX, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbx), 8);
7175                 }
7176                 if (cfg->used_int_regs & (1 << AMD64_R12)) {
7177                         amd64_mov_reg_membase (code, AMD64_R12, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r12), 8);
7178                 }
7179                 if (cfg->used_int_regs & (1 << AMD64_R13)) {
7180                         amd64_mov_reg_membase (code, AMD64_R13, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r13), 8);
7181                 }
7182                 if (cfg->used_int_regs & (1 << AMD64_R14)) {
7183                         amd64_mov_reg_membase (code, AMD64_R14, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r14), 8);
7184                 }
7185                 if (cfg->used_int_regs & (1 << AMD64_R15)) {
7186 #if defined(__default_codegen__)
7187                         amd64_mov_reg_membase (code, AMD64_R15, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r15), 8);
7188 #elif defined(__native_client_codegen__)
7189                         g_assert_not_reached();
7190 #endif
7191                 }
7192 #ifdef HOST_WIN32
7193                 if (cfg->used_int_regs & (1 << AMD64_RDI)) {
7194                         amd64_mov_reg_membase (code, AMD64_RDI, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rdi), 8);
7195                 }
7196                 if (cfg->used_int_regs & (1 << AMD64_RSI)) {
7197                         amd64_mov_reg_membase (code, AMD64_RSI, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rsi), 8);
7198                 }
7199 #endif
7200         } else {
7201
7202                 if (cfg->arch.omit_fp) {
7203                         gint32 save_area_offset = cfg->arch.reg_save_area_offset;
7204
7205                         for (i = 0; i < AMD64_NREG; ++i)
7206                                 if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
7207                                         amd64_mov_reg_membase (code, i, AMD64_RSP, save_area_offset, 8);
7208                                         save_area_offset += 8;
7209                                 }
7210                 }
7211                 else {
7212                         for (i = 0; i < AMD64_NREG; ++i)
7213                                 if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i)))
7214                                         pos -= sizeof(mgreg_t);
7215
7216                         if (pos) {
7217                                 if (pos == - sizeof(mgreg_t)) {
7218                                         /* Only one register, so avoid lea */
7219                                         for (i = AMD64_NREG - 1; i > 0; --i)
7220                                                 if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
7221                                                         amd64_mov_reg_membase (code, i, AMD64_RBP, pos, 8);
7222                                                 }
7223                                 }
7224                                 else {
7225                                         amd64_lea_membase (code, AMD64_RSP, AMD64_RBP, pos);
7226
7227                                         /* Pop registers in reverse order */
7228                                         for (i = AMD64_NREG - 1; i > 0; --i)
7229                                                 if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
7230                                                         amd64_pop_reg (code, i);
7231                                                 }
7232                                 }
7233                         }
7234                 }
7235         }
7236
7237         /* Load returned vtypes into registers if needed */
7238         cinfo = cfg->arch.cinfo;
7239         if (cinfo->ret.storage == ArgValuetypeInReg) {
7240                 ArgInfo *ainfo = &cinfo->ret;
7241                 MonoInst *inst = cfg->ret;
7242
7243                 for (quad = 0; quad < 2; quad ++) {
7244                         switch (ainfo->pair_storage [quad]) {
7245                         case ArgInIReg:
7246                                 amd64_mov_reg_membase (code, ainfo->pair_regs [quad], inst->inst_basereg, inst->inst_offset + (quad * sizeof(mgreg_t)), sizeof(mgreg_t));
7247                                 break;
7248                         case ArgInFloatSSEReg:
7249                                 amd64_movss_reg_membase (code, ainfo->pair_regs [quad], inst->inst_basereg, inst->inst_offset + (quad * sizeof(mgreg_t)));
7250                                 break;
7251                         case ArgInDoubleSSEReg:
7252                                 amd64_movsd_reg_membase (code, ainfo->pair_regs [quad], inst->inst_basereg, inst->inst_offset + (quad * sizeof(mgreg_t)));
7253                                 break;
7254                         case ArgNone:
7255                                 break;
7256                         default:
7257                                 g_assert_not_reached ();
7258                         }
7259                 }
7260         }
7261
7262         if (cfg->arch.omit_fp) {
7263                 if (cfg->arch.stack_alloc_size)
7264                         amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, cfg->arch.stack_alloc_size);
7265         } else {
7266                 amd64_leave (code);
7267         }
7268         async_exc_point (code);
7269         amd64_ret (code);
7270
7271         cfg->code_len = code - cfg->native_code;
7272
7273         g_assert (cfg->code_len < cfg->code_size);
7274 }
7275
7276 void
7277 mono_arch_emit_exceptions (MonoCompile *cfg)
7278 {
7279         MonoJumpInfo *patch_info;
7280         int nthrows, i;
7281         guint8 *code;
7282         MonoClass *exc_classes [16];
7283         guint8 *exc_throw_start [16], *exc_throw_end [16];
7284         guint32 code_size = 0;
7285
7286         /* Compute needed space */
7287         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7288                 if (patch_info->type == MONO_PATCH_INFO_EXC)
7289                         code_size += 40;
7290                 if (patch_info->type == MONO_PATCH_INFO_R8)
7291                         code_size += 8 + 15; /* sizeof (double) + alignment */
7292                 if (patch_info->type == MONO_PATCH_INFO_R4)
7293                         code_size += 4 + 15; /* sizeof (float) + alignment */
7294                 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR)
7295                         code_size += 8 + 7; /*sizeof (void*) + alignment */
7296         }
7297
7298 #ifdef __native_client_codegen__
7299         /* Give us extra room on Native Client.  This could be   */
7300         /* more carefully calculated, but bundle alignment makes */
7301         /* it much trickier, so *2 like other places is good.    */
7302         code_size *= 2;
7303 #endif
7304
7305         while (cfg->code_len + code_size > (cfg->code_size - 16)) {
7306                 cfg->code_size *= 2;
7307                 cfg->native_code = mono_realloc_native_code (cfg);
7308                 cfg->stat_code_reallocs++;
7309         }
7310
7311         code = cfg->native_code + cfg->code_len;
7312
7313         /* add code to raise exceptions */
7314         nthrows = 0;
7315         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7316                 switch (patch_info->type) {
7317                 case MONO_PATCH_INFO_EXC: {
7318                         MonoClass *exc_class;
7319                         guint8 *buf, *buf2;
7320                         guint32 throw_ip;
7321
7322                         amd64_patch (patch_info->ip.i + cfg->native_code, code);
7323
7324                         exc_class = mono_class_from_name (mono_defaults.corlib, "System", patch_info->data.name);
7325                         g_assert (exc_class);
7326                         throw_ip = patch_info->ip.i;
7327
7328                         //x86_breakpoint (code);
7329                         /* Find a throw sequence for the same exception class */
7330                         for (i = 0; i < nthrows; ++i)
7331                                 if (exc_classes [i] == exc_class)
7332                                         break;
7333                         if (i < nthrows) {
7334                                 amd64_mov_reg_imm (code, AMD64_ARG_REG2, (exc_throw_end [i] - cfg->native_code) - throw_ip);
7335                                 x86_jump_code (code, exc_throw_start [i]);
7336                                 patch_info->type = MONO_PATCH_INFO_NONE;
7337                         }
7338                         else {
7339                                 buf = code;
7340                                 amd64_mov_reg_imm_size (code, AMD64_ARG_REG2, 0xf0f0f0f0, 4);
7341                                 buf2 = code;
7342
7343                                 if (nthrows < 16) {
7344                                         exc_classes [nthrows] = exc_class;
7345                                         exc_throw_start [nthrows] = code;
7346                                 }
7347                                 amd64_mov_reg_imm (code, AMD64_ARG_REG1, exc_class->type_token - MONO_TOKEN_TYPE_DEF);
7348
7349                                 patch_info->type = MONO_PATCH_INFO_NONE;
7350
7351                                 code = emit_call_body (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD, "mono_arch_throw_corlib_exception");
7352
7353                                 amd64_mov_reg_imm (buf, AMD64_ARG_REG2, (code - cfg->native_code) - throw_ip);
7354                                 while (buf < buf2)
7355                                         x86_nop (buf);
7356
7357                                 if (nthrows < 16) {
7358                                         exc_throw_end [nthrows] = code;
7359                                         nthrows ++;
7360                                 }
7361                         }
7362                         break;
7363                 }
7364                 default:
7365                         /* do nothing */
7366                         break;
7367                 }
7368                 g_assert(code < cfg->native_code + cfg->code_size);
7369         }
7370
7371         /* Handle relocations with RIP relative addressing */
7372         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7373                 gboolean remove = FALSE;
7374                 guint8 *orig_code = code;
7375
7376                 switch (patch_info->type) {
7377                 case MONO_PATCH_INFO_R8:
7378                 case MONO_PATCH_INFO_R4: {
7379                         guint8 *pos, *patch_pos;
7380                         guint32 target_pos;
7381
7382                         /* The SSE opcodes require a 16 byte alignment */
7383 #if defined(__default_codegen__)
7384                         code = (guint8*)ALIGN_TO (code, 16);
7385 #elif defined(__native_client_codegen__)
7386                         {
7387                                 /* Pad this out with HLT instructions  */
7388                                 /* or we can get garbage bytes emitted */
7389                                 /* which will fail validation          */
7390                                 guint8 *aligned_code;
7391                                 /* extra align to make room for  */
7392                                 /* mov/push below                      */
7393                                 int extra_align = patch_info->type == MONO_PATCH_INFO_R8 ? 2 : 1;
7394                                 aligned_code = (guint8*)ALIGN_TO (code + extra_align, 16);
7395                                 /* The technique of hiding data in an  */
7396                                 /* instruction has a problem here: we  */
7397                                 /* need the data aligned to a 16-byte  */
7398                                 /* boundary but the instruction cannot */
7399                                 /* cross the bundle boundary. so only  */
7400                                 /* odd multiples of 16 can be used     */
7401                                 if ((intptr_t)aligned_code % kNaClAlignment == 0) {
7402                                         aligned_code += 16;
7403                                 }
7404                                 while (code < aligned_code) {
7405                                         *(code++) = 0xf4; /* hlt */
7406                                 }
7407                         }       
7408 #endif
7409
7410                         pos = cfg->native_code + patch_info->ip.i;
7411                         if (IS_REX (pos [1])) {
7412                                 patch_pos = pos + 5;
7413                                 target_pos = code - pos - 9;
7414                         }
7415                         else {
7416                                 patch_pos = pos + 4;
7417                                 target_pos = code - pos - 8;
7418                         }
7419
7420                         if (patch_info->type == MONO_PATCH_INFO_R8) {
7421 #ifdef __native_client_codegen__
7422                                 /* Hide 64-bit data in a         */
7423                                 /* "mov imm64, r11" instruction. */
7424                                 /* write it before the start of  */
7425                                 /* the data*/
7426                                 *(code-2) = 0x49; /* prefix      */
7427                                 *(code-1) = 0xbb; /* mov X, %r11 */
7428 #endif
7429                                 *(double*)code = *(double*)patch_info->data.target;
7430                                 code += sizeof (double);
7431                         } else {
7432 #ifdef __native_client_codegen__
7433                                 /* Hide 32-bit data in a        */
7434                                 /* "push imm32" instruction.    */
7435                                 *(code-1) = 0x68; /* push */
7436 #endif
7437                                 *(float*)code = *(float*)patch_info->data.target;
7438                                 code += sizeof (float);
7439                         }
7440
7441                         *(guint32*)(patch_pos) = target_pos;
7442
7443                         remove = TRUE;
7444                         break;
7445                 }
7446                 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR: {
7447                         guint8 *pos;
7448
7449                         if (cfg->compile_aot)
7450                                 continue;
7451
7452                         /*loading is faster against aligned addresses.*/
7453                         code = (guint8*)ALIGN_TO (code, 8);
7454                         memset (orig_code, 0, code - orig_code);
7455
7456                         pos = cfg->native_code + patch_info->ip.i;
7457
7458                         /*alu_op [rex] modr/m imm32 - 7 or 8 bytes */
7459                         if (IS_REX (pos [1]))
7460                                 *(guint32*)(pos + 4) = (guint8*)code - pos - 8;
7461                         else
7462                                 *(guint32*)(pos + 3) = (guint8*)code - pos - 7;
7463
7464                         *(gpointer*)code = (gpointer)patch_info->data.target;
7465                         code += sizeof (gpointer);
7466
7467                         remove = TRUE;
7468                         break;
7469                 }
7470                 default:
7471                         break;
7472                 }
7473
7474                 if (remove) {
7475                         if (patch_info == cfg->patch_info)
7476                                 cfg->patch_info = patch_info->next;
7477                         else {
7478                                 MonoJumpInfo *tmp;
7479
7480                                 for (tmp = cfg->patch_info; tmp->next != patch_info; tmp = tmp->next)
7481                                         ;
7482                                 tmp->next = patch_info->next;
7483                         }
7484                 }
7485                 g_assert (code < cfg->native_code + cfg->code_size);
7486         }
7487
7488         cfg->code_len = code - cfg->native_code;
7489
7490         g_assert (cfg->code_len < cfg->code_size);
7491
7492 }
7493
7494 #endif /* DISABLE_JIT */
7495
7496 void*
7497 mono_arch_instrument_prolog (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments)
7498 {
7499         guchar *code = p;
7500         CallInfo *cinfo = NULL;
7501         MonoMethodSignature *sig;
7502         MonoInst *inst;
7503         int i, n, stack_area = 0;
7504
7505         /* Keep this in sync with mono_arch_get_argument_info */
7506
7507         if (enable_arguments) {
7508                 /* Allocate a new area on the stack and save arguments there */
7509                 sig = mono_method_signature (cfg->method);
7510
7511                 cinfo = get_call_info (cfg->generic_sharing_context, cfg->mempool, sig);
7512
7513                 n = sig->param_count + sig->hasthis;
7514
7515                 stack_area = ALIGN_TO (n * 8, 16);
7516
7517                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, stack_area);
7518
7519                 for (i = 0; i < n; ++i) {
7520                         inst = cfg->args [i];
7521
7522                         if (inst->opcode == OP_REGVAR)
7523                                 amd64_mov_membase_reg (code, AMD64_RSP, (i * 8), inst->dreg, 8);
7524                         else {
7525                                 amd64_mov_reg_membase (code, AMD64_R11, inst->inst_basereg, inst->inst_offset, 8);
7526                                 amd64_mov_membase_reg (code, AMD64_RSP, (i * 8), AMD64_R11, 8);
7527                         }
7528                 }
7529         }
7530
7531         mono_add_patch_info (cfg, code-cfg->native_code, MONO_PATCH_INFO_METHODCONST, cfg->method);
7532         amd64_set_reg_template (code, AMD64_ARG_REG1);
7533         amd64_mov_reg_reg (code, AMD64_ARG_REG2, AMD64_RSP, 8);
7534         code = emit_call (cfg, code, MONO_PATCH_INFO_ABS, (gpointer)func, TRUE);
7535
7536         if (enable_arguments)
7537                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, stack_area);
7538
7539         return code;
7540 }
7541
7542 enum {
7543         SAVE_NONE,
7544         SAVE_STRUCT,
7545         SAVE_EAX,
7546         SAVE_EAX_EDX,
7547         SAVE_XMM
7548 };
7549
7550 void*
7551 mono_arch_instrument_epilog_full (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments, gboolean preserve_argument_registers)
7552 {
7553         guchar *code = p;
7554         int save_mode = SAVE_NONE;
7555         MonoMethod *method = cfg->method;
7556         MonoType *ret_type = mini_type_get_underlying_type (NULL, mono_method_signature (method)->ret);
7557         int i;
7558         
7559         switch (ret_type->type) {
7560         case MONO_TYPE_VOID:
7561                 /* special case string .ctor icall */
7562                 if (strcmp (".ctor", method->name) && method->klass == mono_defaults.string_class)
7563                         save_mode = SAVE_EAX;
7564                 else
7565                         save_mode = SAVE_NONE;
7566                 break;
7567         case MONO_TYPE_I8:
7568         case MONO_TYPE_U8:
7569                 save_mode = SAVE_EAX;
7570                 break;
7571         case MONO_TYPE_R4:
7572         case MONO_TYPE_R8:
7573                 save_mode = SAVE_XMM;
7574                 break;
7575         case MONO_TYPE_GENERICINST:
7576                 if (!mono_type_generic_inst_is_valuetype (ret_type)) {
7577                         save_mode = SAVE_EAX;
7578                         break;
7579                 }
7580                 /* Fall through */
7581         case MONO_TYPE_VALUETYPE:
7582                 save_mode = SAVE_STRUCT;
7583                 break;
7584         default:
7585                 save_mode = SAVE_EAX;
7586                 break;
7587         }
7588
7589         /* Save the result and copy it into the proper argument register */
7590         switch (save_mode) {
7591         case SAVE_EAX:
7592                 amd64_push_reg (code, AMD64_RAX);
7593                 /* Align stack */
7594                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
7595                 if (enable_arguments)
7596                         amd64_mov_reg_reg (code, AMD64_ARG_REG2, AMD64_RAX, 8);
7597                 break;
7598         case SAVE_STRUCT:
7599                 /* FIXME: */
7600                 if (enable_arguments)
7601                         amd64_mov_reg_imm (code, AMD64_ARG_REG2, 0);
7602                 break;
7603         case SAVE_XMM:
7604                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
7605                 amd64_movsd_membase_reg (code, AMD64_RSP, 0, AMD64_XMM0);
7606                 /* Align stack */
7607                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
7608                 /* 
7609                  * The result is already in the proper argument register so no copying
7610                  * needed.
7611                  */
7612                 break;
7613         case SAVE_NONE:
7614                 break;
7615         default:
7616                 g_assert_not_reached ();
7617         }
7618
7619         /* Set %al since this is a varargs call */
7620         if (save_mode == SAVE_XMM)
7621                 amd64_mov_reg_imm (code, AMD64_RAX, 1);
7622         else
7623                 amd64_mov_reg_imm (code, AMD64_RAX, 0);
7624
7625         if (preserve_argument_registers) {
7626                 for (i = 0; i < PARAM_REGS; ++i)
7627                         amd64_push_reg (code, param_regs [i]);
7628         }
7629
7630         mono_add_patch_info (cfg, code-cfg->native_code, MONO_PATCH_INFO_METHODCONST, method);
7631         amd64_set_reg_template (code, AMD64_ARG_REG1);
7632         code = emit_call (cfg, code, MONO_PATCH_INFO_ABS, (gpointer)func, TRUE);
7633
7634         if (preserve_argument_registers) {
7635                 for (i = PARAM_REGS - 1; i >= 0; --i)
7636                         amd64_pop_reg (code, param_regs [i]);
7637         }
7638
7639         /* Restore result */
7640         switch (save_mode) {
7641         case SAVE_EAX:
7642                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
7643                 amd64_pop_reg (code, AMD64_RAX);
7644                 break;
7645         case SAVE_STRUCT:
7646                 /* FIXME: */
7647                 break;
7648         case SAVE_XMM:
7649                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
7650                 amd64_movsd_reg_membase (code, AMD64_XMM0, AMD64_RSP, 0);
7651                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
7652                 break;
7653         case SAVE_NONE:
7654                 break;
7655         default:
7656                 g_assert_not_reached ();
7657         }
7658
7659         return code;
7660 }
7661
7662 void
7663 mono_arch_flush_icache (guint8 *code, gint size)
7664 {
7665         /* Not needed */
7666 }
7667
7668 void
7669 mono_arch_flush_register_windows (void)
7670 {
7671 }
7672
7673 gboolean 
7674 mono_arch_is_inst_imm (gint64 imm)
7675 {
7676         return amd64_is_imm32 (imm);
7677 }
7678
7679 /*
7680  * Determine whenever the trap whose info is in SIGINFO is caused by
7681  * integer overflow.
7682  */
7683 gboolean
7684 mono_arch_is_int_overflow (void *sigctx, void *info)
7685 {
7686         MonoContext ctx;
7687         guint8* rip;
7688         int reg;
7689         gint64 value;
7690
7691         mono_arch_sigctx_to_monoctx (sigctx, &ctx);
7692
7693         rip = (guint8*)ctx.rip;
7694
7695         if (IS_REX (rip [0])) {
7696                 reg = amd64_rex_b (rip [0]);
7697                 rip ++;
7698         }
7699         else
7700                 reg = 0;
7701
7702         if ((rip [0] == 0xf7) && (x86_modrm_mod (rip [1]) == 0x3) && (x86_modrm_reg (rip [1]) == 0x7)) {
7703                 /* idiv REG */
7704                 reg += x86_modrm_rm (rip [1]);
7705
7706                 switch (reg) {
7707                 case AMD64_RAX:
7708                         value = ctx.rax;
7709                         break;
7710                 case AMD64_RBX:
7711                         value = ctx.rbx;
7712                         break;
7713                 case AMD64_RCX:
7714                         value = ctx.rcx;
7715                         break;
7716                 case AMD64_RDX:
7717                         value = ctx.rdx;
7718                         break;
7719                 case AMD64_RBP:
7720                         value = ctx.rbp;
7721                         break;
7722                 case AMD64_RSP:
7723                         value = ctx.rsp;
7724                         break;
7725                 case AMD64_RSI:
7726                         value = ctx.rsi;
7727                         break;
7728                 case AMD64_RDI:
7729                         value = ctx.rdi;
7730                         break;
7731                 case AMD64_R12:
7732                         value = ctx.r12;
7733                         break;
7734                 case AMD64_R13:
7735                         value = ctx.r13;
7736                         break;
7737                 case AMD64_R14:
7738                         value = ctx.r14;
7739                         break;
7740                 case AMD64_R15:
7741                         value = ctx.r15;
7742                         break;
7743                 default:
7744                         g_assert_not_reached ();
7745                         reg = -1;
7746                 }                       
7747
7748                 if (value == -1)
7749                         return TRUE;
7750         }
7751
7752         return FALSE;
7753 }
7754
7755 guint32
7756 mono_arch_get_patch_offset (guint8 *code)
7757 {
7758         return 3;
7759 }
7760
7761 /**
7762  * mono_breakpoint_clean_code:
7763  *
7764  * Copy @size bytes from @code - @offset to the buffer @buf. If the debugger inserted software
7765  * breakpoints in the original code, they are removed in the copy.
7766  *
7767  * Returns TRUE if no sw breakpoint was present.
7768  */
7769 gboolean
7770 mono_breakpoint_clean_code (guint8 *method_start, guint8 *code, int offset, guint8 *buf, int size)
7771 {
7772         int i;
7773         gboolean can_write = TRUE;
7774         /*
7775          * If method_start is non-NULL we need to perform bound checks, since we access memory
7776          * at code - offset we could go before the start of the method and end up in a different
7777          * page of memory that is not mapped or read incorrect data anyway. We zero-fill the bytes
7778          * instead.
7779          */
7780         if (!method_start || code - offset >= method_start) {
7781                 memcpy (buf, code - offset, size);
7782         } else {
7783                 int diff = code - method_start;
7784                 memset (buf, 0, size);
7785                 memcpy (buf + offset - diff, method_start, diff + size - offset);
7786         }
7787         code -= offset;
7788         for (i = 0; i < MONO_BREAKPOINT_ARRAY_SIZE; ++i) {
7789                 int idx = mono_breakpoint_info_index [i];
7790                 guint8 *ptr;
7791                 if (idx < 1)
7792                         continue;
7793                 ptr = mono_breakpoint_info [idx].address;
7794                 if (ptr >= code && ptr < code + size) {
7795                         guint8 saved_byte = mono_breakpoint_info [idx].saved_byte;
7796                         can_write = FALSE;
7797                         /*g_print ("patching %p with 0x%02x (was: 0x%02x)\n", ptr, saved_byte, buf [ptr - code]);*/
7798                         buf [ptr - code] = saved_byte;
7799                 }
7800         }
7801         return can_write;
7802 }
7803
7804 #if defined(__native_client_codegen__)
7805 /* For membase calls, we want the base register. for Native Client,  */
7806 /* all indirect calls have the following sequence with the given sizes: */
7807 /* mov %eXX,%eXX                                [2-3]   */
7808 /* mov disp(%r15,%rXX,scale),%r11d              [4-8]   */
7809 /* and $0xffffffffffffffe0,%r11d                [4]     */
7810 /* add %r15,%r11                                [3]     */
7811 /* callq *%r11                                  [3]     */
7812
7813
7814 /* Determine if code points to a NaCl call-through-register sequence, */
7815 /* (i.e., the last 3 instructions listed above) */
7816 int
7817 is_nacl_call_reg_sequence(guint8* code)
7818 {
7819         const char *sequence = "\x41\x83\xe3\xe0" /* and */
7820                                "\x4d\x03\xdf"     /* add */
7821                                "\x41\xff\xd3";   /* call */
7822         return memcmp(code, sequence, 10) == 0;
7823 }
7824
7825 /* Determine if code points to the first opcode of the mov membase component */
7826 /* of an indirect call sequence (i.e. the first 2 instructions listed above) */
7827 /* (there could be a REX prefix before the opcode but it is ignored) */
7828 static int
7829 is_nacl_indirect_call_membase_sequence(guint8* code)
7830 {
7831                /* Check for mov opcode, reg-reg addressing mode (mod = 3), */
7832         return code[0] == 0x8b && amd64_modrm_mod(code[1]) == 3 &&
7833                /* and that src reg = dest reg */
7834                amd64_modrm_reg(code[1]) == amd64_modrm_rm(code[1]) &&
7835                /* Check that next inst is mov, uses SIB byte (rm = 4), */
7836                IS_REX(code[2]) &&
7837                code[3] == 0x8b && amd64_modrm_rm(code[4]) == 4 &&
7838                /* and has dst of r11 and base of r15 */
7839                (amd64_modrm_reg(code[4]) + amd64_rex_r(code[2])) == AMD64_R11 &&
7840                (amd64_sib_base(code[5]) + amd64_rex_b(code[2])) == AMD64_R15;
7841 }
7842 #endif /* __native_client_codegen__ */
7843
7844 int
7845 mono_arch_get_this_arg_reg (guint8 *code)
7846 {
7847         return AMD64_ARG_REG1;
7848 }
7849
7850 gpointer
7851 mono_arch_get_this_arg_from_call (mgreg_t *regs, guint8 *code)
7852 {
7853         return (gpointer)regs [mono_arch_get_this_arg_reg (code)];
7854 }
7855
7856 #define MAX_ARCH_DELEGATE_PARAMS 10
7857
7858 static gpointer
7859 get_delegate_invoke_impl (gboolean has_target, guint32 param_count, guint32 *code_len)
7860 {
7861         guint8 *code, *start;
7862         int i;
7863
7864         if (has_target) {
7865                 start = code = mono_global_codeman_reserve (64);
7866
7867                 /* Replace the this argument with the target */
7868                 amd64_mov_reg_reg (code, AMD64_RAX, AMD64_ARG_REG1, 8);
7869                 amd64_mov_reg_membase (code, AMD64_ARG_REG1, AMD64_RAX, G_STRUCT_OFFSET (MonoDelegate, target), 8);
7870                 amd64_jump_membase (code, AMD64_RAX, G_STRUCT_OFFSET (MonoDelegate, method_ptr));
7871
7872                 g_assert ((code - start) < 64);
7873         } else {
7874                 start = code = mono_global_codeman_reserve (64);
7875
7876                 if (param_count == 0) {
7877                         amd64_jump_membase (code, AMD64_ARG_REG1, G_STRUCT_OFFSET (MonoDelegate, method_ptr));
7878                 } else {
7879                         /* We have to shift the arguments left */
7880                         amd64_mov_reg_reg (code, AMD64_RAX, AMD64_ARG_REG1, 8);
7881                         for (i = 0; i < param_count; ++i) {
7882 #ifdef HOST_WIN32
7883                                 if (i < 3)
7884                                         amd64_mov_reg_reg (code, param_regs [i], param_regs [i + 1], 8);
7885                                 else
7886                                         amd64_mov_reg_membase (code, param_regs [i], AMD64_RSP, 0x28, 8);
7887 #else
7888                                 amd64_mov_reg_reg (code, param_regs [i], param_regs [i + 1], 8);
7889 #endif
7890                         }
7891
7892                         amd64_jump_membase (code, AMD64_RAX, G_STRUCT_OFFSET (MonoDelegate, method_ptr));
7893                 }
7894                 g_assert ((code - start) < 64);
7895         }
7896
7897         nacl_global_codeman_validate(&start, 64, &code);
7898
7899         mono_debug_add_delegate_trampoline (start, code - start);
7900
7901         if (code_len)
7902                 *code_len = code - start;
7903
7904
7905         if (mono_jit_map_is_enabled ()) {
7906                 char *buff;
7907                 if (has_target)
7908                         buff = (char*)"delegate_invoke_has_target";
7909                 else
7910                         buff = g_strdup_printf ("delegate_invoke_no_target_%d", param_count);
7911                 mono_emit_jit_tramp (start, code - start, buff);
7912                 if (!has_target)
7913                         g_free (buff);
7914         }
7915
7916         return start;
7917 }
7918
7919 /*
7920  * mono_arch_get_delegate_invoke_impls:
7921  *
7922  *   Return a list of MonoTrampInfo structures for the delegate invoke impl
7923  * trampolines.
7924  */
7925 GSList*
7926 mono_arch_get_delegate_invoke_impls (void)
7927 {
7928         GSList *res = NULL;
7929         guint8 *code;
7930         guint32 code_len;
7931         int i;
7932
7933         code = get_delegate_invoke_impl (TRUE, 0, &code_len);
7934         res = g_slist_prepend (res, mono_tramp_info_create (g_strdup ("delegate_invoke_impl_has_target"), code, code_len, NULL, NULL));
7935
7936         for (i = 0; i < MAX_ARCH_DELEGATE_PARAMS; ++i) {
7937                 code = get_delegate_invoke_impl (FALSE, i, &code_len);
7938                 res = g_slist_prepend (res, mono_tramp_info_create (g_strdup_printf ("delegate_invoke_impl_target_%d", i), code, code_len, NULL, NULL));
7939         }
7940
7941         return res;
7942 }
7943
7944 gpointer
7945 mono_arch_get_delegate_invoke_impl (MonoMethodSignature *sig, gboolean has_target)
7946 {
7947         guint8 *code, *start;
7948         int i;
7949
7950         if (sig->param_count > MAX_ARCH_DELEGATE_PARAMS)
7951                 return NULL;
7952
7953         /* FIXME: Support more cases */
7954         if (MONO_TYPE_ISSTRUCT (sig->ret))
7955                 return NULL;
7956
7957         if (has_target) {
7958                 static guint8* cached = NULL;
7959
7960                 if (cached)
7961                         return cached;
7962
7963                 if (mono_aot_only)
7964                         start = mono_aot_get_trampoline ("delegate_invoke_impl_has_target");
7965                 else
7966                         start = get_delegate_invoke_impl (TRUE, 0, NULL);
7967
7968                 mono_memory_barrier ();
7969
7970                 cached = start;
7971         } else {
7972                 static guint8* cache [MAX_ARCH_DELEGATE_PARAMS + 1] = {NULL};
7973                 for (i = 0; i < sig->param_count; ++i)
7974                         if (!mono_is_regsize_var (sig->params [i]))
7975                                 return NULL;
7976                 if (sig->param_count > 4)
7977                         return NULL;
7978
7979                 code = cache [sig->param_count];
7980                 if (code)
7981                         return code;
7982
7983                 if (mono_aot_only) {
7984                         char *name = g_strdup_printf ("delegate_invoke_impl_target_%d", sig->param_count);
7985                         start = mono_aot_get_trampoline (name);
7986                         g_free (name);
7987                 } else {
7988                         start = get_delegate_invoke_impl (FALSE, sig->param_count, NULL);
7989                 }
7990
7991                 mono_memory_barrier ();
7992
7993                 cache [sig->param_count] = start;
7994         }
7995
7996         return start;
7997 }
7998 void
7999 mono_arch_finish_init (void)
8000 {
8001 #ifdef HOST_WIN32
8002         /* 
8003          * We need to init this multiple times, since when we are first called, the key might not
8004          * be initialized yet.
8005          */
8006         appdomain_tls_offset = mono_domain_get_tls_key ();
8007         lmf_tls_offset = mono_get_jit_tls_key ();
8008         lmf_addr_tls_offset = mono_get_jit_tls_key ();
8009
8010         /* Only 64 tls entries can be accessed using inline code */
8011         if (appdomain_tls_offset >= 64)
8012                 appdomain_tls_offset = -1;
8013         if (lmf_tls_offset >= 64)
8014                 lmf_tls_offset = -1;
8015         if (lmf_addr_tls_offset >= 64)
8016                 lmf_addr_tls_offset = -1;
8017 #else
8018 #ifdef MONO_XEN_OPT
8019         optimize_for_xen = access ("/proc/xen", F_OK) == 0;
8020 #endif
8021         appdomain_tls_offset = mono_domain_get_tls_offset ();
8022         lmf_tls_offset = mono_get_lmf_tls_offset ();
8023         lmf_addr_tls_offset = mono_get_lmf_addr_tls_offset ();
8024 #endif
8025 }
8026
8027 void
8028 mono_arch_free_jit_tls_data (MonoJitTlsData *tls)
8029 {
8030 }
8031
8032 #ifdef MONO_ARCH_HAVE_IMT
8033
8034 #if defined(__default_codegen__)
8035 #define CMP_SIZE (6 + 1)
8036 #define CMP_REG_REG_SIZE (4 + 1)
8037 #define BR_SMALL_SIZE 2
8038 #define BR_LARGE_SIZE 6
8039 #define MOV_REG_IMM_SIZE 10
8040 #define MOV_REG_IMM_32BIT_SIZE 6
8041 #define JUMP_REG_SIZE (2 + 1)
8042 #elif defined(__native_client_codegen__)
8043 /* NaCl N-byte instructions can be padded up to N-1 bytes */
8044 #define CMP_SIZE ((6 + 1) * 2 - 1)
8045 #define CMP_REG_REG_SIZE ((4 + 1) * 2 - 1)
8046 #define BR_SMALL_SIZE (2 * 2 - 1)
8047 #define BR_LARGE_SIZE (6 * 2 - 1)
8048 #define MOV_REG_IMM_SIZE (10 * 2 - 1)
8049 #define MOV_REG_IMM_32BIT_SIZE (6 * 2 - 1)
8050 /* Jump reg for NaCl adds a mask (+4) and add (+3) */
8051 #define JUMP_REG_SIZE ((2 + 1 + 4 + 3) * 2 - 1)
8052 /* Jump membase's size is large and unpredictable    */
8053 /* in native client, just pad it out a whole bundle. */
8054 #define JUMP_MEMBASE_SIZE (kNaClAlignment)
8055 #endif
8056
8057 static int
8058 imt_branch_distance (MonoIMTCheckItem **imt_entries, int start, int target)
8059 {
8060         int i, distance = 0;
8061         for (i = start; i < target; ++i)
8062                 distance += imt_entries [i]->chunk_size;
8063         return distance;
8064 }
8065
8066 /*
8067  * LOCKING: called with the domain lock held
8068  */
8069 gpointer
8070 mono_arch_build_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count,
8071         gpointer fail_tramp)
8072 {
8073         int i;
8074         int size = 0;
8075         guint8 *code, *start;
8076         gboolean vtable_is_32bit = ((gsize)(vtable) == (gsize)(int)(gsize)(vtable));
8077
8078         for (i = 0; i < count; ++i) {
8079                 MonoIMTCheckItem *item = imt_entries [i];
8080                 if (item->is_equals) {
8081                         if (item->check_target_idx) {
8082                                 if (!item->compare_done) {
8083                                         if (amd64_is_imm32 (item->key))
8084                                                 item->chunk_size += CMP_SIZE;
8085                                         else
8086                                                 item->chunk_size += MOV_REG_IMM_SIZE + CMP_REG_REG_SIZE;
8087                                 }
8088                                 if (item->has_target_code) {
8089                                         item->chunk_size += MOV_REG_IMM_SIZE;
8090                                 } else {
8091                                         if (vtable_is_32bit)
8092                                                 item->chunk_size += MOV_REG_IMM_32BIT_SIZE;
8093                                         else
8094                                                 item->chunk_size += MOV_REG_IMM_SIZE;
8095 #ifdef __native_client_codegen__
8096                                         item->chunk_size += JUMP_MEMBASE_SIZE;
8097 #endif
8098                                 }
8099                                 item->chunk_size += BR_SMALL_SIZE + JUMP_REG_SIZE;
8100                         } else {
8101                                 if (fail_tramp) {
8102                                         item->chunk_size += MOV_REG_IMM_SIZE * 3 + CMP_REG_REG_SIZE +
8103                                                 BR_SMALL_SIZE + JUMP_REG_SIZE * 2;
8104                                 } else {
8105                                         if (vtable_is_32bit)
8106                                                 item->chunk_size += MOV_REG_IMM_32BIT_SIZE;
8107                                         else
8108                                                 item->chunk_size += MOV_REG_IMM_SIZE;
8109                                         item->chunk_size += JUMP_REG_SIZE;
8110                                         /* with assert below:
8111                                          * item->chunk_size += CMP_SIZE + BR_SMALL_SIZE + 1;
8112                                          */
8113 #ifdef __native_client_codegen__
8114                                         item->chunk_size += JUMP_MEMBASE_SIZE;
8115 #endif
8116                                 }
8117                         }
8118                 } else {
8119                         if (amd64_is_imm32 (item->key))
8120                                 item->chunk_size += CMP_SIZE;
8121                         else
8122                                 item->chunk_size += MOV_REG_IMM_SIZE + CMP_REG_REG_SIZE;
8123                         item->chunk_size += BR_LARGE_SIZE;
8124                         imt_entries [item->check_target_idx]->compare_done = TRUE;
8125                 }
8126                 size += item->chunk_size;
8127         }
8128 #if defined(__native_client__) && defined(__native_client_codegen__)
8129         /* In Native Client, we don't re-use thunks, allocate from the */
8130         /* normal code manager paths. */
8131         code = mono_domain_code_reserve (domain, size);
8132 #else
8133         if (fail_tramp)
8134                 code = mono_method_alloc_generic_virtual_thunk (domain, size);
8135         else
8136                 code = mono_domain_code_reserve (domain, size);
8137 #endif
8138         start = code;
8139         for (i = 0; i < count; ++i) {
8140                 MonoIMTCheckItem *item = imt_entries [i];
8141                 item->code_target = code;
8142                 if (item->is_equals) {
8143                         gboolean fail_case = !item->check_target_idx && fail_tramp;
8144
8145                         if (item->check_target_idx || fail_case) {
8146                                 if (!item->compare_done || fail_case) {
8147                                         if (amd64_is_imm32 (item->key))
8148                                                 amd64_alu_reg_imm (code, X86_CMP, MONO_ARCH_IMT_REG, (guint32)(gssize)item->key);
8149                                         else {
8150                                                 amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, item->key);
8151                                                 amd64_alu_reg_reg (code, X86_CMP, MONO_ARCH_IMT_REG, MONO_ARCH_IMT_SCRATCH_REG);
8152                                         }
8153                                 }
8154                                 item->jmp_code = code;
8155                                 amd64_branch8 (code, X86_CC_NE, 0, FALSE);
8156                                 if (item->has_target_code) {
8157                                         amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, item->value.target_code);
8158                                         amd64_jump_reg (code, MONO_ARCH_IMT_SCRATCH_REG);
8159                                 } else {
8160                                         amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, & (vtable->vtable [item->value.vtable_slot]));
8161                                         amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
8162                                 }
8163
8164                                 if (fail_case) {
8165                                         amd64_patch (item->jmp_code, code);
8166                                         amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, fail_tramp);
8167                                         amd64_jump_reg (code, MONO_ARCH_IMT_SCRATCH_REG);
8168                                         item->jmp_code = NULL;
8169                                 }
8170                         } else {
8171                                 /* enable the commented code to assert on wrong method */
8172 #if 0
8173                                 if (amd64_is_imm32 (item->key))
8174                                         amd64_alu_reg_imm (code, X86_CMP, MONO_ARCH_IMT_REG, (guint32)(gssize)item->key);
8175                                 else {
8176                                         amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, item->key);
8177                                         amd64_alu_reg_reg (code, X86_CMP, MONO_ARCH_IMT_REG, MONO_ARCH_IMT_SCRATCH_REG);
8178                                 }
8179                                 item->jmp_code = code;
8180                                 amd64_branch8 (code, X86_CC_NE, 0, FALSE);
8181                                 /* See the comment below about R10 */
8182                                 amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, & (vtable->vtable [item->value.vtable_slot]));
8183                                 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
8184                                 amd64_patch (item->jmp_code, code);
8185                                 amd64_breakpoint (code);
8186                                 item->jmp_code = NULL;
8187 #else
8188                                 /* We're using R10 (MONO_ARCH_IMT_SCRATCH_REG) here because R11 (MONO_ARCH_IMT_REG)
8189                                    needs to be preserved.  R10 needs
8190                                    to be preserved for calls which
8191                                    require a runtime generic context,
8192                                    but interface calls don't. */
8193                                 amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, & (vtable->vtable [item->value.vtable_slot]));
8194                                 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
8195 #endif
8196                         }
8197                 } else {
8198                         if (amd64_is_imm32 (item->key))
8199                                 amd64_alu_reg_imm (code, X86_CMP, MONO_ARCH_IMT_REG, (guint32)(gssize)item->key);
8200                         else {
8201                                 amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, item->key);
8202                                 amd64_alu_reg_reg (code, X86_CMP, MONO_ARCH_IMT_REG, MONO_ARCH_IMT_SCRATCH_REG);
8203                         }
8204                         item->jmp_code = code;
8205                         if (x86_is_imm8 (imt_branch_distance (imt_entries, i, item->check_target_idx)))
8206                                 x86_branch8 (code, X86_CC_GE, 0, FALSE);
8207                         else
8208                                 x86_branch32 (code, X86_CC_GE, 0, FALSE);
8209                 }
8210                 g_assert (code - item->code_target <= item->chunk_size);
8211         }
8212         /* patch the branches to get to the target items */
8213         for (i = 0; i < count; ++i) {
8214                 MonoIMTCheckItem *item = imt_entries [i];
8215                 if (item->jmp_code) {
8216                         if (item->check_target_idx) {
8217                                 amd64_patch (item->jmp_code, imt_entries [item->check_target_idx]->code_target);
8218                         }
8219                 }
8220         }
8221
8222         if (!fail_tramp)
8223                 mono_stats.imt_thunks_size += code - start;
8224         g_assert (code - start <= size);
8225
8226         nacl_domain_code_validate(domain, &start, size, &code);
8227
8228         return start;
8229 }
8230
8231 MonoMethod*
8232 mono_arch_find_imt_method (mgreg_t *regs, guint8 *code)
8233 {
8234         return (MonoMethod*)regs [MONO_ARCH_IMT_REG];
8235 }
8236 #endif
8237
8238 MonoVTable*
8239 mono_arch_find_static_call_vtable (mgreg_t *regs, guint8 *code)
8240 {
8241         return (MonoVTable*) regs [MONO_ARCH_RGCTX_REG];
8242 }
8243
8244 GSList*
8245 mono_arch_get_cie_program (void)
8246 {
8247         GSList *l = NULL;
8248
8249         mono_add_unwind_op_def_cfa (l, (guint8*)NULL, (guint8*)NULL, AMD64_RSP, 8);
8250         mono_add_unwind_op_offset (l, (guint8*)NULL, (guint8*)NULL, AMD64_RIP, -8);
8251
8252         return l;
8253 }
8254
8255 MonoInst*
8256 mono_arch_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
8257 {
8258         MonoInst *ins = NULL;
8259         int opcode = 0;
8260
8261         if (cmethod->klass == mono_defaults.math_class) {
8262                 if (strcmp (cmethod->name, "Sin") == 0) {
8263                         opcode = OP_SIN;
8264                 } else if (strcmp (cmethod->name, "Cos") == 0) {
8265                         opcode = OP_COS;
8266                 } else if (strcmp (cmethod->name, "Sqrt") == 0) {
8267                         opcode = OP_SQRT;
8268                 } else if (strcmp (cmethod->name, "Abs") == 0 && fsig->params [0]->type == MONO_TYPE_R8) {
8269                         opcode = OP_ABS;
8270                 }
8271                 
8272                 if (opcode) {
8273                         MONO_INST_NEW (cfg, ins, opcode);
8274                         ins->type = STACK_R8;
8275                         ins->dreg = mono_alloc_freg (cfg);
8276                         ins->sreg1 = args [0]->dreg;
8277                         MONO_ADD_INS (cfg->cbb, ins);
8278                 }
8279
8280                 opcode = 0;
8281                 if (cfg->opt & MONO_OPT_CMOV) {
8282                         if (strcmp (cmethod->name, "Min") == 0) {
8283                                 if (fsig->params [0]->type == MONO_TYPE_I4)
8284                                         opcode = OP_IMIN;
8285                                 if (fsig->params [0]->type == MONO_TYPE_U4)
8286                                         opcode = OP_IMIN_UN;
8287                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
8288                                         opcode = OP_LMIN;
8289                                 else if (fsig->params [0]->type == MONO_TYPE_U8)
8290                                         opcode = OP_LMIN_UN;
8291                         } else if (strcmp (cmethod->name, "Max") == 0) {
8292                                 if (fsig->params [0]->type == MONO_TYPE_I4)
8293                                         opcode = OP_IMAX;
8294                                 if (fsig->params [0]->type == MONO_TYPE_U4)
8295                                         opcode = OP_IMAX_UN;
8296                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
8297                                         opcode = OP_LMAX;
8298                                 else if (fsig->params [0]->type == MONO_TYPE_U8)
8299                                         opcode = OP_LMAX_UN;
8300                         }
8301                 }
8302                 
8303                 if (opcode) {
8304                         MONO_INST_NEW (cfg, ins, opcode);
8305                         ins->type = fsig->params [0]->type == MONO_TYPE_I4 ? STACK_I4 : STACK_I8;
8306                         ins->dreg = mono_alloc_ireg (cfg);
8307                         ins->sreg1 = args [0]->dreg;
8308                         ins->sreg2 = args [1]->dreg;
8309                         MONO_ADD_INS (cfg->cbb, ins);
8310                 }
8311
8312 #if 0
8313                 /* OP_FREM is not IEEE compatible */
8314                 else if (strcmp (cmethod->name, "IEEERemainder") == 0) {
8315                         MONO_INST_NEW (cfg, ins, OP_FREM);
8316                         ins->inst_i0 = args [0];
8317                         ins->inst_i1 = args [1];
8318                 }
8319 #endif
8320         }
8321
8322         /* 
8323          * Can't implement CompareExchange methods this way since they have
8324          * three arguments.
8325          */
8326
8327         return ins;
8328 }
8329
8330 gboolean
8331 mono_arch_print_tree (MonoInst *tree, int arity)
8332 {
8333         return 0;
8334 }
8335
8336 MonoInst* mono_arch_get_domain_intrinsic (MonoCompile* cfg)
8337 {
8338         MonoInst* ins;
8339         
8340         if (appdomain_tls_offset == -1)
8341                 return NULL;
8342         
8343         MONO_INST_NEW (cfg, ins, OP_TLS_GET);
8344         ins->inst_offset = appdomain_tls_offset;
8345         return ins;
8346 }
8347
8348 #define _CTX_REG(ctx,fld,i) ((&ctx->fld)[i])
8349
8350 mgreg_t
8351 mono_arch_context_get_int_reg (MonoContext *ctx, int reg)
8352 {
8353         switch (reg) {
8354         case AMD64_RCX: return ctx->rcx;
8355         case AMD64_RDX: return ctx->rdx;
8356         case AMD64_RBX: return ctx->rbx;
8357         case AMD64_RBP: return ctx->rbp;
8358         case AMD64_RSP: return ctx->rsp;
8359         default:
8360                 if (reg < 8)
8361                         return _CTX_REG (ctx, rax, reg);
8362                 else if (reg >= 12)
8363                         return _CTX_REG (ctx, r12, reg - 12);
8364                 else
8365                         g_assert_not_reached ();
8366         }
8367 }
8368
8369 void
8370 mono_arch_context_set_int_reg (MonoContext *ctx, int reg, mgreg_t val)
8371 {
8372         switch (reg) {
8373         case AMD64_RCX:
8374                 ctx->rcx = val;
8375                 break;
8376         case AMD64_RDX: 
8377                 ctx->rdx = val;
8378                 break;
8379         case AMD64_RBX:
8380                 ctx->rbx = val;
8381                 break;
8382         case AMD64_RBP:
8383                 ctx->rbp = val;
8384                 break;
8385         case AMD64_RSP:
8386                 ctx->rsp = val;
8387                 break;
8388         default:
8389                 if (reg < 8)
8390                         _CTX_REG (ctx, rax, reg) = val;
8391                 else if (reg >= 12)
8392                         _CTX_REG (ctx, r12, reg - 12) = val;
8393                 else
8394                         g_assert_not_reached ();
8395         }
8396 }
8397
8398 /*MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD*/
8399 gpointer
8400 mono_arch_install_handler_block_guard (MonoJitInfo *ji, MonoJitExceptionInfo *clause, MonoContext *ctx, gpointer new_value)
8401 {
8402         int offset;
8403         gpointer *sp, old_value;
8404         char *bp;
8405         const unsigned char *handler;
8406
8407         /*Decode the first instruction to figure out where did we store the spvar*/
8408         /*Our jit MUST generate the following:
8409          mov    %rsp, ?(%rbp)
8410
8411          Which is encoded as: REX.W 0x89 mod_rm
8412          mod_rm (rsp, rbp, imm) which can be: (imm will never be zero)
8413                 mod (reg + imm8):  01 reg(rsp): 100 rm(rbp): 101 -> 01100101 (0x65)
8414                 mod (reg + imm32): 10 reg(rsp): 100 rm(rbp): 101 -> 10100101 (0xA5)
8415
8416         FIXME can we generate frameless methods on this case?
8417
8418         */
8419         handler = clause->handler_start;
8420
8421         /*REX.W*/
8422         if (*handler != 0x48)
8423                 return NULL;
8424         ++handler;
8425
8426         /*mov r, r/m */
8427         if (*handler != 0x89)
8428                 return NULL;
8429         ++handler;
8430
8431         if (*handler == 0x65)
8432                 offset = *(signed char*)(handler + 1);
8433         else if (*handler == 0xA5)
8434                 offset = *(int*)(handler + 1);
8435         else
8436                 return NULL;
8437
8438         /*Load the spvar*/
8439         bp = MONO_CONTEXT_GET_BP (ctx);
8440         sp = *(gpointer*)(bp + offset);
8441
8442         old_value = *sp;
8443         if (old_value < ji->code_start || (char*)old_value > ((char*)ji->code_start + ji->code_size))
8444                 return old_value;
8445
8446         *sp = new_value;
8447
8448         return old_value;
8449 }
8450
8451 /*
8452  * mono_arch_emit_load_aotconst:
8453  *
8454  *   Emit code to load the contents of the GOT slot identified by TRAMP_TYPE and
8455  * TARGET from the mscorlib GOT in full-aot code.
8456  * On AMD64, the result is placed into R11.
8457  */
8458 guint8*
8459 mono_arch_emit_load_aotconst (guint8 *start, guint8 *code, MonoJumpInfo **ji, int tramp_type, gconstpointer target)
8460 {
8461         *ji = mono_patch_info_list_prepend (*ji, code - start, tramp_type, target);
8462         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, 8);
8463
8464         return code;
8465 }
8466
8467 /*
8468  * mono_arch_get_trampolines:
8469  *
8470  *   Return a list of MonoTrampInfo structures describing arch specific trampolines
8471  * for AOT.
8472  */
8473 GSList *
8474 mono_arch_get_trampolines (gboolean aot)
8475 {
8476         return mono_amd64_get_exception_trampolines (aot);
8477 }
8478
8479 /* Soft Debug support */
8480 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
8481
8482 /*
8483  * mono_arch_set_breakpoint:
8484  *
8485  *   Set a breakpoint at the native code corresponding to JI at NATIVE_OFFSET.
8486  * The location should contain code emitted by OP_SEQ_POINT.
8487  */
8488 void
8489 mono_arch_set_breakpoint (MonoJitInfo *ji, guint8 *ip)
8490 {
8491         guint8 *code = ip;
8492         guint8 *orig_code = code;
8493
8494         if (ji->from_aot) {
8495                 guint32 native_offset = ip - (guint8*)ji->code_start;
8496                 SeqPointInfo *info = mono_arch_get_seq_point_info (mono_domain_get (), ji->code_start);
8497
8498                 g_assert (info->bp_addrs [native_offset] == 0);
8499                 info->bp_addrs [native_offset] = bp_trigger_page;
8500         } else {
8501                 /* 
8502                  * In production, we will use int3 (has to fix the size in the md 
8503                  * file). But that could confuse gdb, so during development, we emit a SIGSEGV
8504                  * instead.
8505                  */
8506                 g_assert (code [0] == 0x90);
8507                 if (breakpoint_size == 8) {
8508                         amd64_mov_reg_mem (code, AMD64_R11, (guint64)bp_trigger_page, 4);
8509                 } else {
8510                         amd64_mov_reg_imm_size (code, AMD64_R11, (guint64)bp_trigger_page, 8);
8511                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 0, 4);
8512                 }
8513
8514                 g_assert (code - orig_code == breakpoint_size);
8515         }
8516 }
8517
8518 /*
8519  * mono_arch_clear_breakpoint:
8520  *
8521  *   Clear the breakpoint at IP.
8522  */
8523 void
8524 mono_arch_clear_breakpoint (MonoJitInfo *ji, guint8 *ip)
8525 {
8526         guint8 *code = ip;
8527         int i;
8528
8529         if (ji->from_aot) {
8530                 guint32 native_offset = ip - (guint8*)ji->code_start;
8531                 SeqPointInfo *info = mono_arch_get_seq_point_info (mono_domain_get (), ji->code_start);
8532
8533                 g_assert (info->bp_addrs [native_offset] == 0);
8534                 info->bp_addrs [native_offset] = info;
8535         } else {
8536                 for (i = 0; i < breakpoint_size; ++i)
8537                         x86_nop (code);
8538         }
8539 }
8540
8541 gboolean
8542 mono_arch_is_breakpoint_event (void *info, void *sigctx)
8543 {
8544 #ifdef HOST_WIN32
8545         EXCEPTION_RECORD* einfo = (EXCEPTION_RECORD*)info;
8546         return FALSE;
8547 #else
8548         siginfo_t* sinfo = (siginfo_t*) info;
8549         /* Sometimes the address is off by 4 */
8550         if (sinfo->si_addr >= bp_trigger_page && (guint8*)sinfo->si_addr <= (guint8*)bp_trigger_page + 128)
8551                 return TRUE;
8552         else
8553                 return FALSE;
8554 #endif
8555 }
8556
8557 /*
8558  * mono_arch_skip_breakpoint:
8559  *
8560  *   Modify CTX so the ip is placed after the breakpoint instruction, so when
8561  * we resume, the instruction is not executed again.
8562  */
8563 void
8564 mono_arch_skip_breakpoint (MonoContext *ctx, MonoJitInfo *ji)
8565 {
8566         if (ji->from_aot) {
8567                 /* amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 0, 8) */
8568                 MONO_CONTEXT_SET_IP (ctx, (guint8*)MONO_CONTEXT_GET_IP (ctx) + 3);
8569         } else {
8570                 MONO_CONTEXT_SET_IP (ctx, (guint8*)MONO_CONTEXT_GET_IP (ctx) + breakpoint_fault_size);
8571         }
8572 }
8573         
8574 /*
8575  * mono_arch_start_single_stepping:
8576  *
8577  *   Start single stepping.
8578  */
8579 void
8580 mono_arch_start_single_stepping (void)
8581 {
8582         mono_mprotect (ss_trigger_page, mono_pagesize (), 0);
8583 }
8584         
8585 /*
8586  * mono_arch_stop_single_stepping:
8587  *
8588  *   Stop single stepping.
8589  */
8590 void
8591 mono_arch_stop_single_stepping (void)
8592 {
8593         mono_mprotect (ss_trigger_page, mono_pagesize (), MONO_MMAP_READ);
8594 }
8595
8596 /*
8597  * mono_arch_is_single_step_event:
8598  *
8599  *   Return whenever the machine state in SIGCTX corresponds to a single
8600  * step event.
8601  */
8602 gboolean
8603 mono_arch_is_single_step_event (void *info, void *sigctx)
8604 {
8605 #ifdef HOST_WIN32
8606         EXCEPTION_RECORD* einfo = (EXCEPTION_RECORD*)info;
8607         return FALSE;
8608 #else
8609         siginfo_t* sinfo = (siginfo_t*) info;
8610         /* Sometimes the address is off by 4 */
8611         if (sinfo->si_addr >= ss_trigger_page && (guint8*)sinfo->si_addr <= (guint8*)ss_trigger_page + 128)
8612                 return TRUE;
8613         else
8614                 return FALSE;
8615 #endif
8616 }
8617
8618 /*
8619  * mono_arch_skip_single_step:
8620  *
8621  *   Modify CTX so the ip is placed after the single step trigger instruction,
8622  * we resume, the instruction is not executed again.
8623  */
8624 void
8625 mono_arch_skip_single_step (MonoContext *ctx)
8626 {
8627         MONO_CONTEXT_SET_IP (ctx, (guint8*)MONO_CONTEXT_GET_IP (ctx) + single_step_fault_size);
8628 }
8629
8630 /*
8631  * mono_arch_create_seq_point_info:
8632  *
8633  *   Return a pointer to a data structure which is used by the sequence
8634  * point implementation in AOTed code.
8635  */
8636 gpointer
8637 mono_arch_get_seq_point_info (MonoDomain *domain, guint8 *code)
8638 {
8639         SeqPointInfo *info;
8640         MonoJitInfo *ji;
8641         int i;
8642
8643         // FIXME: Add a free function
8644
8645         mono_domain_lock (domain);
8646         info = g_hash_table_lookup (domain_jit_info (domain)->arch_seq_points,
8647                                                                 code);
8648         mono_domain_unlock (domain);
8649
8650         if (!info) {
8651                 ji = mono_jit_info_table_find (domain, (char*)code);
8652                 g_assert (ji);
8653
8654                 // FIXME: Optimize the size
8655                 info = g_malloc0 (sizeof (SeqPointInfo) + (ji->code_size * sizeof (gpointer)));
8656
8657                 info->ss_trigger_page = ss_trigger_page;
8658                 info->bp_trigger_page = bp_trigger_page;
8659                 /* Initialize to a valid address */
8660                 for (i = 0; i < ji->code_size; ++i)
8661                         info->bp_addrs [i] = info;
8662
8663                 mono_domain_lock (domain);
8664                 g_hash_table_insert (domain_jit_info (domain)->arch_seq_points,
8665                                                          code, info);
8666                 mono_domain_unlock (domain);
8667         }
8668
8669         return info;
8670 }
8671
8672 #endif