Merge pull request #194 from QuickJack/master
[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         MonoInst *sig_arg;
2138
2139         if (call->tail_call)
2140                 NOT_IMPLEMENTED;
2141
2142         /* FIXME: Add support for signature tokens to AOT */
2143         cfg->disable_aot = TRUE;
2144
2145         g_assert (cinfo->sig_cookie.storage == ArgOnStack);
2146                         
2147         /*
2148          * mono_ArgIterator_Setup assumes the signature cookie is 
2149          * passed first and all the arguments which were before it are
2150          * passed on the stack after the signature. So compensate by 
2151          * passing a different signature.
2152          */
2153         tmp_sig = mono_metadata_signature_dup_full (cfg->method->klass->image, call->signature);
2154         tmp_sig->param_count -= call->signature->sentinelpos;
2155         tmp_sig->sentinelpos = 0;
2156         memcpy (tmp_sig->params, call->signature->params + call->signature->sentinelpos, tmp_sig->param_count * sizeof (MonoType*));
2157
2158         MONO_INST_NEW (cfg, sig_arg, OP_ICONST);
2159         sig_arg->dreg = mono_alloc_ireg (cfg);
2160         sig_arg->inst_p0 = tmp_sig;
2161         MONO_ADD_INS (cfg->cbb, sig_arg);
2162
2163         if (cfg->arch.no_pushes) {
2164                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, AMD64_RSP, cinfo->sig_cookie.offset, sig_arg->dreg);
2165         } else {
2166                 MONO_INST_NEW (cfg, arg, OP_X86_PUSH);
2167                 arg->sreg1 = sig_arg->dreg;
2168                 MONO_ADD_INS (cfg->cbb, arg);
2169         }
2170 }
2171
2172 static inline LLVMArgStorage
2173 arg_storage_to_llvm_arg_storage (MonoCompile *cfg, ArgStorage storage)
2174 {
2175         switch (storage) {
2176         case ArgInIReg:
2177                 return LLVMArgInIReg;
2178         case ArgNone:
2179                 return LLVMArgNone;
2180         default:
2181                 g_assert_not_reached ();
2182                 return LLVMArgNone;
2183         }
2184 }
2185
2186 #ifdef ENABLE_LLVM
2187 LLVMCallInfo*
2188 mono_arch_get_llvm_call_info (MonoCompile *cfg, MonoMethodSignature *sig)
2189 {
2190         int i, n;
2191         CallInfo *cinfo;
2192         ArgInfo *ainfo;
2193         int j;
2194         LLVMCallInfo *linfo;
2195         MonoType *t;
2196
2197         n = sig->param_count + sig->hasthis;
2198
2199         cinfo = get_call_info (cfg->generic_sharing_context, cfg->mempool, sig);
2200
2201         linfo = mono_mempool_alloc0 (cfg->mempool, sizeof (LLVMCallInfo) + (sizeof (LLVMArgInfo) * n));
2202
2203         /*
2204          * LLVM always uses the native ABI while we use our own ABI, the
2205          * only difference is the handling of vtypes:
2206          * - we only pass/receive them in registers in some cases, and only 
2207          *   in 1 or 2 integer registers.
2208          */
2209         if (cinfo->ret.storage == ArgValuetypeInReg) {
2210                 if (sig->pinvoke) {
2211                         cfg->exception_message = g_strdup ("pinvoke + vtypes");
2212                         cfg->disable_llvm = TRUE;
2213                         return linfo;
2214                 }
2215
2216                 linfo->ret.storage = LLVMArgVtypeInReg;
2217                 for (j = 0; j < 2; ++j)
2218                         linfo->ret.pair_storage [j] = arg_storage_to_llvm_arg_storage (cfg, cinfo->ret.pair_storage [j]);
2219         }
2220
2221         if (MONO_TYPE_ISSTRUCT (sig->ret) && cinfo->ret.storage == ArgInIReg) {
2222                 /* Vtype returned using a hidden argument */
2223                 linfo->ret.storage = LLVMArgVtypeRetAddr;
2224                 linfo->vret_arg_index = cinfo->vret_arg_index;
2225         }
2226
2227         for (i = 0; i < n; ++i) {
2228                 ainfo = cinfo->args + i;
2229
2230                 if (i >= sig->hasthis)
2231                         t = sig->params [i - sig->hasthis];
2232                 else
2233                         t = &mono_defaults.int_class->byval_arg;
2234
2235                 linfo->args [i].storage = LLVMArgNone;
2236
2237                 switch (ainfo->storage) {
2238                 case ArgInIReg:
2239                         linfo->args [i].storage = LLVMArgInIReg;
2240                         break;
2241                 case ArgInDoubleSSEReg:
2242                 case ArgInFloatSSEReg:
2243                         linfo->args [i].storage = LLVMArgInFPReg;
2244                         break;
2245                 case ArgOnStack:
2246                         if (MONO_TYPE_ISSTRUCT (t)) {
2247                                 linfo->args [i].storage = LLVMArgVtypeByVal;
2248                         } else {
2249                                 linfo->args [i].storage = LLVMArgInIReg;
2250                                 if (!t->byref) {
2251                                         if (t->type == MONO_TYPE_R4)
2252                                                 linfo->args [i].storage = LLVMArgInFPReg;
2253                                         else if (t->type == MONO_TYPE_R8)
2254                                                 linfo->args [i].storage = LLVMArgInFPReg;
2255                                 }
2256                         }
2257                         break;
2258                 case ArgValuetypeInReg:
2259                         if (sig->pinvoke) {
2260                                 cfg->exception_message = g_strdup ("pinvoke + vtypes");
2261                                 cfg->disable_llvm = TRUE;
2262                                 return linfo;
2263                         }
2264
2265                         linfo->args [i].storage = LLVMArgVtypeInReg;
2266                         for (j = 0; j < 2; ++j)
2267                                 linfo->args [i].pair_storage [j] = arg_storage_to_llvm_arg_storage (cfg, ainfo->pair_storage [j]);
2268                         break;
2269                 default:
2270                         cfg->exception_message = g_strdup ("ainfo->storage");
2271                         cfg->disable_llvm = TRUE;
2272                         break;
2273                 }
2274         }
2275
2276         return linfo;
2277 }
2278 #endif
2279
2280 void
2281 mono_arch_emit_call (MonoCompile *cfg, MonoCallInst *call)
2282 {
2283         MonoInst *arg, *in;
2284         MonoMethodSignature *sig;
2285         int i, n, stack_size;
2286         CallInfo *cinfo;
2287         ArgInfo *ainfo;
2288
2289         stack_size = 0;
2290
2291         sig = call->signature;
2292         n = sig->param_count + sig->hasthis;
2293
2294         cinfo = get_call_info (cfg->generic_sharing_context, cfg->mempool, sig);
2295
2296         if (COMPILE_LLVM (cfg)) {
2297                 /* We shouldn't be called in the llvm case */
2298                 cfg->disable_llvm = TRUE;
2299                 return;
2300         }
2301
2302         if (cinfo->need_stack_align) {
2303                 if (!cfg->arch.no_pushes)
2304                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SUB_IMM, X86_ESP, X86_ESP, 8);
2305         }
2306
2307         /* 
2308          * Emit all arguments which are passed on the stack to prevent register
2309          * allocation problems.
2310          */
2311         if (cfg->arch.no_pushes) {
2312                 for (i = 0; i < n; ++i) {
2313                         MonoType *t;
2314                         ainfo = cinfo->args + i;
2315
2316                         in = call->args [i];
2317
2318                         if (sig->hasthis && i == 0)
2319                                 t = &mono_defaults.object_class->byval_arg;
2320                         else
2321                                 t = sig->params [i - sig->hasthis];
2322
2323                         if (ainfo->storage == ArgOnStack && !MONO_TYPE_ISSTRUCT (t) && !call->tail_call) {
2324                                 if (!t->byref) {
2325                                         if (t->type == MONO_TYPE_R4)
2326                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORER4_MEMBASE_REG, AMD64_RSP, ainfo->offset, in->dreg);
2327                                         else if (t->type == MONO_TYPE_R8)
2328                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORER8_MEMBASE_REG, AMD64_RSP, ainfo->offset, in->dreg);
2329                                         else
2330                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, AMD64_RSP, ainfo->offset, in->dreg);
2331                                 } else {
2332                                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, AMD64_RSP, ainfo->offset, in->dreg);
2333                                 }
2334                                 if (cfg->compute_gc_maps) {
2335                                         MonoInst *def;
2336
2337                                         EMIT_NEW_GC_PARAM_SLOT_LIVENESS_DEF (cfg, def, ainfo->offset, t);
2338                                 }
2339                         }
2340                 }
2341         }
2342
2343         /*
2344          * Emit all parameters passed in registers in non-reverse order for better readability
2345          * and to help the optimization in emit_prolog ().
2346          */
2347         for (i = 0; i < n; ++i) {
2348                 ainfo = cinfo->args + i;
2349
2350                 in = call->args [i];
2351
2352                 if (ainfo->storage == ArgInIReg)
2353                         add_outarg_reg (cfg, call, ainfo->storage, ainfo->reg, in);
2354         }
2355
2356         for (i = n - 1; i >= 0; --i) {
2357                 ainfo = cinfo->args + i;
2358
2359                 in = call->args [i];
2360
2361                 switch (ainfo->storage) {
2362                 case ArgInIReg:
2363                         /* Already done */
2364                         break;
2365                 case ArgInFloatSSEReg:
2366                 case ArgInDoubleSSEReg:
2367                         add_outarg_reg (cfg, call, ainfo->storage, ainfo->reg, in);
2368                         break;
2369                 case ArgOnStack:
2370                 case ArgValuetypeInReg:
2371                 case ArgValuetypeAddrInIReg:
2372                         if (ainfo->storage == ArgOnStack && call->tail_call) {
2373                                 MonoInst *call_inst = (MonoInst*)call;
2374                                 cfg->args [i]->flags |= MONO_INST_VOLATILE;
2375                                 EMIT_NEW_ARGSTORE (cfg, call_inst, i, in);
2376                         } else if ((i >= sig->hasthis) && (MONO_TYPE_ISSTRUCT(sig->params [i - sig->hasthis]))) {
2377                                 guint32 align;
2378                                 guint32 size;
2379
2380                                 if (sig->params [i - sig->hasthis]->type == MONO_TYPE_TYPEDBYREF) {
2381                                         size = sizeof (MonoTypedRef);
2382                                         align = sizeof (gpointer);
2383                                 }
2384                                 else {
2385                                         if (sig->pinvoke)
2386                                                 size = mono_type_native_stack_size (&in->klass->byval_arg, &align);
2387                                         else {
2388                                                 /* 
2389                                                  * Other backends use mono_type_stack_size (), but that
2390                                                  * aligns the size to 8, which is larger than the size of
2391                                                  * the source, leading to reads of invalid memory if the
2392                                                  * source is at the end of address space.
2393                                                  */
2394                                                 size = mono_class_value_size (in->klass, &align);
2395                                         }
2396                                 }
2397                                 g_assert (in->klass);
2398
2399                                 if (ainfo->storage == ArgOnStack && size >= 10000) {
2400                                         /* Avoid asserts in emit_memcpy () */
2401                                         cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
2402                                         cfg->exception_message = g_strdup_printf ("Passing an argument of size '%d'.", size);
2403                                         /* Continue normally */
2404                                 }
2405
2406                                 if (size > 0) {
2407                                         MONO_INST_NEW (cfg, arg, OP_OUTARG_VT);
2408                                         arg->sreg1 = in->dreg;
2409                                         arg->klass = in->klass;
2410                                         arg->backend.size = size;
2411                                         arg->inst_p0 = call;
2412                                         arg->inst_p1 = mono_mempool_alloc (cfg->mempool, sizeof (ArgInfo));
2413                                         memcpy (arg->inst_p1, ainfo, sizeof (ArgInfo));
2414
2415                                         MONO_ADD_INS (cfg->cbb, arg);
2416                                 }
2417                         } else {
2418                                 if (cfg->arch.no_pushes) {
2419                                         /* Already done */
2420                                 } else {
2421                                         MONO_INST_NEW (cfg, arg, OP_X86_PUSH);
2422                                         arg->sreg1 = in->dreg;
2423                                         if (!sig->params [i - sig->hasthis]->byref) {
2424                                                 if (sig->params [i - sig->hasthis]->type == MONO_TYPE_R4) {
2425                                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SUB_IMM, X86_ESP, X86_ESP, 8);
2426                                                         arg->opcode = OP_STORER4_MEMBASE_REG;
2427                                                         arg->inst_destbasereg = X86_ESP;
2428                                                         arg->inst_offset = 0;
2429                                                 } else if (sig->params [i - sig->hasthis]->type == MONO_TYPE_R8) {
2430                                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SUB_IMM, X86_ESP, X86_ESP, 8);
2431                                                         arg->opcode = OP_STORER8_MEMBASE_REG;
2432                                                         arg->inst_destbasereg = X86_ESP;
2433                                                         arg->inst_offset = 0;
2434                                                 }
2435                                         }
2436                                         MONO_ADD_INS (cfg->cbb, arg);
2437                                 }
2438                         }
2439                         break;
2440                 default:
2441                         g_assert_not_reached ();
2442                 }
2443
2444                 if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG) && (i == sig->sentinelpos))
2445                         /* Emit the signature cookie just before the implicit arguments */
2446                         emit_sig_cookie (cfg, call, cinfo);
2447         }
2448
2449         /* Handle the case where there are no implicit arguments */
2450         if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG) && (n == sig->sentinelpos))
2451                 emit_sig_cookie (cfg, call, cinfo);
2452
2453         if (sig->ret && MONO_TYPE_ISSTRUCT (sig->ret)) {
2454                 MonoInst *vtarg;
2455
2456                 if (cinfo->ret.storage == ArgValuetypeInReg) {
2457                         if (cinfo->ret.pair_storage [0] == ArgInIReg && cinfo->ret.pair_storage [1] == ArgNone) {
2458                                 /*
2459                                  * Tell the JIT to use a more efficient calling convention: call using
2460                                  * OP_CALL, compute the result location after the call, and save the 
2461                                  * result there.
2462                                  */
2463                                 call->vret_in_reg = TRUE;
2464                                 /* 
2465                                  * Nullify the instruction computing the vret addr to enable 
2466                                  * future optimizations.
2467                                  */
2468                                 if (call->vret_var)
2469                                         NULLIFY_INS (call->vret_var);
2470                         } else {
2471                                 if (call->tail_call)
2472                                         NOT_IMPLEMENTED;
2473                                 /*
2474                                  * The valuetype is in RAX:RDX after the call, need to be copied to
2475                                  * the stack. Push the address here, so the call instruction can
2476                                  * access it.
2477                                  */
2478                                 if (!cfg->arch.vret_addr_loc) {
2479                                         cfg->arch.vret_addr_loc = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
2480                                         /* Prevent it from being register allocated or optimized away */
2481                                         ((MonoInst*)cfg->arch.vret_addr_loc)->flags |= MONO_INST_VOLATILE;
2482                                 }
2483
2484                                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, ((MonoInst*)cfg->arch.vret_addr_loc)->dreg, call->vret_var->dreg);
2485                         }
2486                 }
2487                 else {
2488                         MONO_INST_NEW (cfg, vtarg, OP_MOVE);
2489                         vtarg->sreg1 = call->vret_var->dreg;
2490                         vtarg->dreg = mono_alloc_preg (cfg);
2491                         MONO_ADD_INS (cfg->cbb, vtarg);
2492
2493                         mono_call_inst_add_outarg_reg (cfg, call, vtarg->dreg, cinfo->ret.reg, FALSE);
2494                 }
2495         }
2496
2497 #ifdef HOST_WIN32
2498         if (call->inst.opcode != OP_JMP && OP_TAILCALL != call->inst.opcode) {
2499                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SUB_IMM, X86_ESP, X86_ESP, 0x20);
2500         }
2501 #endif
2502
2503         if (cfg->method->save_lmf) {
2504                 MONO_INST_NEW (cfg, arg, OP_AMD64_SAVE_SP_TO_LMF);
2505                 MONO_ADD_INS (cfg->cbb, arg);
2506         }
2507
2508         call->stack_usage = cinfo->stack_usage;
2509 }
2510
2511 void
2512 mono_arch_emit_outarg_vt (MonoCompile *cfg, MonoInst *ins, MonoInst *src)
2513 {
2514         MonoInst *arg;
2515         MonoCallInst *call = (MonoCallInst*)ins->inst_p0;
2516         ArgInfo *ainfo = (ArgInfo*)ins->inst_p1;
2517         int size = ins->backend.size;
2518
2519         if (ainfo->storage == ArgValuetypeInReg) {
2520                 MonoInst *load;
2521                 int part;
2522
2523                 for (part = 0; part < 2; ++part) {
2524                         if (ainfo->pair_storage [part] == ArgNone)
2525                                 continue;
2526
2527                         MONO_INST_NEW (cfg, load, arg_storage_to_load_membase (ainfo->pair_storage [part]));
2528                         load->inst_basereg = src->dreg;
2529                         load->inst_offset = part * sizeof(mgreg_t);
2530
2531                         switch (ainfo->pair_storage [part]) {
2532                         case ArgInIReg:
2533                                 load->dreg = mono_alloc_ireg (cfg);
2534                                 break;
2535                         case ArgInDoubleSSEReg:
2536                         case ArgInFloatSSEReg:
2537                                 load->dreg = mono_alloc_freg (cfg);
2538                                 break;
2539                         default:
2540                                 g_assert_not_reached ();
2541                         }
2542                         MONO_ADD_INS (cfg->cbb, load);
2543
2544                         add_outarg_reg (cfg, call, ainfo->pair_storage [part], ainfo->pair_regs [part], load);
2545                 }
2546         } else if (ainfo->storage == ArgValuetypeAddrInIReg) {
2547                 MonoInst *vtaddr, *load;
2548                 vtaddr = mono_compile_create_var (cfg, &ins->klass->byval_arg, OP_LOCAL);
2549                 
2550                 g_assert (!cfg->arch.no_pushes);
2551
2552                 MONO_INST_NEW (cfg, load, OP_LDADDR);
2553                 load->inst_p0 = vtaddr;
2554                 vtaddr->flags |= MONO_INST_INDIRECT;
2555                 load->type = STACK_MP;
2556                 load->klass = vtaddr->klass;
2557                 load->dreg = mono_alloc_ireg (cfg);
2558                 MONO_ADD_INS (cfg->cbb, load);
2559                 mini_emit_memcpy (cfg, load->dreg, 0, src->dreg, 0, size, 4);
2560
2561                 if (ainfo->pair_storage [0] == ArgInIReg) {
2562                         MONO_INST_NEW (cfg, arg, OP_X86_LEA_MEMBASE);
2563                         arg->dreg = mono_alloc_ireg (cfg);
2564                         arg->sreg1 = load->dreg;
2565                         arg->inst_imm = 0;
2566                         MONO_ADD_INS (cfg->cbb, arg);
2567                         mono_call_inst_add_outarg_reg (cfg, call, arg->dreg, ainfo->pair_regs [0], FALSE);
2568                 } else {
2569                         MONO_INST_NEW (cfg, arg, OP_X86_PUSH);
2570                         arg->sreg1 = load->dreg;
2571                         MONO_ADD_INS (cfg->cbb, arg);
2572                 }
2573         } else {
2574                 if (size == 8) {
2575                         if (cfg->arch.no_pushes) {
2576                                 int dreg = mono_alloc_ireg (cfg);
2577
2578                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, src->dreg, 0);
2579                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, AMD64_RSP, ainfo->offset, dreg);
2580                         } else {
2581                                 /* Can't use this for < 8 since it does an 8 byte memory load */
2582                                 MONO_INST_NEW (cfg, arg, OP_X86_PUSH_MEMBASE);
2583                                 arg->inst_basereg = src->dreg;
2584                                 arg->inst_offset = 0;
2585                                 MONO_ADD_INS (cfg->cbb, arg);
2586                         }
2587                 } else if (size <= 40) {
2588                         if (cfg->arch.no_pushes) {
2589                                 mini_emit_memcpy (cfg, AMD64_RSP, ainfo->offset, src->dreg, 0, size, 4);
2590                         } else {
2591                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SUB_IMM, X86_ESP, X86_ESP, ALIGN_TO (size, 8));
2592                                 mini_emit_memcpy (cfg, X86_ESP, 0, src->dreg, 0, size, 4);
2593                         }
2594                 } else {
2595                         if (cfg->arch.no_pushes) {
2596                                 // FIXME: Code growth
2597                                 mini_emit_memcpy (cfg, AMD64_RSP, ainfo->offset, src->dreg, 0, size, 4);
2598                         } else {
2599                                 MONO_INST_NEW (cfg, arg, OP_X86_PUSH_OBJ);
2600                                 arg->inst_basereg = src->dreg;
2601                                 arg->inst_offset = 0;
2602                                 arg->inst_imm = size;
2603                                 MONO_ADD_INS (cfg->cbb, arg);
2604                         }
2605                 }
2606
2607                 if (cfg->compute_gc_maps) {
2608                         MonoInst *def;
2609                         EMIT_NEW_GC_PARAM_SLOT_LIVENESS_DEF (cfg, def, ainfo->offset, &ins->klass->byval_arg);
2610                 }
2611         }
2612 }
2613
2614 void
2615 mono_arch_emit_setret (MonoCompile *cfg, MonoMethod *method, MonoInst *val)
2616 {
2617         MonoType *ret = mini_type_get_underlying_type (NULL, mono_method_signature (method)->ret);
2618
2619         if (ret->type == MONO_TYPE_R4) {
2620                 if (COMPILE_LLVM (cfg))
2621                         MONO_EMIT_NEW_UNALU (cfg, OP_FMOVE, cfg->ret->dreg, val->dreg);
2622                 else
2623                         MONO_EMIT_NEW_UNALU (cfg, OP_AMD64_SET_XMMREG_R4, cfg->ret->dreg, val->dreg);
2624                 return;
2625         } else if (ret->type == MONO_TYPE_R8) {
2626                 MONO_EMIT_NEW_UNALU (cfg, OP_FMOVE, cfg->ret->dreg, val->dreg);
2627                 return;
2628         }
2629                         
2630         MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->ret->dreg, val->dreg);
2631 }
2632
2633 #endif /* DISABLE_JIT */
2634
2635 #define EMIT_COND_BRANCH(ins,cond,sign) \
2636         if (ins->inst_true_bb->native_offset) { \
2637                 x86_branch (code, cond, cfg->native_code + ins->inst_true_bb->native_offset, sign); \
2638         } else { \
2639                 mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_BB, ins->inst_true_bb); \
2640                 if ((cfg->opt & MONO_OPT_BRANCH) && \
2641             x86_is_imm8 (ins->inst_true_bb->max_offset - offset)) \
2642                         x86_branch8 (code, cond, 0, sign); \
2643                 else \
2644                         x86_branch32 (code, cond, 0, sign); \
2645 }
2646
2647 typedef struct {
2648         MonoMethodSignature *sig;
2649         CallInfo *cinfo;
2650 } ArchDynCallInfo;
2651
2652 typedef struct {
2653         mgreg_t regs [PARAM_REGS];
2654         mgreg_t res;
2655         guint8 *ret;
2656 } DynCallArgs;
2657
2658 static gboolean
2659 dyn_call_supported (MonoMethodSignature *sig, CallInfo *cinfo)
2660 {
2661         int i;
2662
2663 #ifdef HOST_WIN32
2664         return FALSE;
2665 #endif
2666
2667         switch (cinfo->ret.storage) {
2668         case ArgNone:
2669         case ArgInIReg:
2670                 break;
2671         case ArgValuetypeInReg: {
2672                 ArgInfo *ainfo = &cinfo->ret;
2673
2674                 if (ainfo->pair_storage [0] != ArgNone && ainfo->pair_storage [0] != ArgInIReg)
2675                         return FALSE;
2676                 if (ainfo->pair_storage [1] != ArgNone && ainfo->pair_storage [1] != ArgInIReg)
2677                         return FALSE;
2678                 break;
2679         }
2680         default:
2681                 return FALSE;
2682         }
2683
2684         for (i = 0; i < cinfo->nargs; ++i) {
2685                 ArgInfo *ainfo = &cinfo->args [i];
2686                 switch (ainfo->storage) {
2687                 case ArgInIReg:
2688                         break;
2689                 case ArgValuetypeInReg:
2690                         if (ainfo->pair_storage [0] != ArgNone && ainfo->pair_storage [0] != ArgInIReg)
2691                                 return FALSE;
2692                         if (ainfo->pair_storage [1] != ArgNone && ainfo->pair_storage [1] != ArgInIReg)
2693                                 return FALSE;
2694                         break;
2695                 default:
2696                         return FALSE;
2697                 }
2698         }
2699
2700         return TRUE;
2701 }
2702
2703 /*
2704  * mono_arch_dyn_call_prepare:
2705  *
2706  *   Return a pointer to an arch-specific structure which contains information 
2707  * needed by mono_arch_get_dyn_call_args (). Return NULL if OP_DYN_CALL is not
2708  * supported for SIG.
2709  * This function is equivalent to ffi_prep_cif in libffi.
2710  */
2711 MonoDynCallInfo*
2712 mono_arch_dyn_call_prepare (MonoMethodSignature *sig)
2713 {
2714         ArchDynCallInfo *info;
2715         CallInfo *cinfo;
2716
2717         cinfo = get_call_info (NULL, NULL, sig);
2718
2719         if (!dyn_call_supported (sig, cinfo)) {
2720                 g_free (cinfo);
2721                 return NULL;
2722         }
2723
2724         info = g_new0 (ArchDynCallInfo, 1);
2725         // FIXME: Preprocess the info to speed up get_dyn_call_args ().
2726         info->sig = sig;
2727         info->cinfo = cinfo;
2728         
2729         return (MonoDynCallInfo*)info;
2730 }
2731
2732 /*
2733  * mono_arch_dyn_call_free:
2734  *
2735  *   Free a MonoDynCallInfo structure.
2736  */
2737 void
2738 mono_arch_dyn_call_free (MonoDynCallInfo *info)
2739 {
2740         ArchDynCallInfo *ainfo = (ArchDynCallInfo*)info;
2741
2742         g_free (ainfo->cinfo);
2743         g_free (ainfo);
2744 }
2745
2746 #if !defined(__native_client__)
2747 #define PTR_TO_GREG(ptr) (mgreg_t)(ptr)
2748 #define GREG_TO_PTR(greg) (gpointer)(greg)
2749 #else
2750 /* Correctly handle casts to/from 32-bit pointers without compiler warnings */
2751 #define PTR_TO_GREG(ptr) (mgreg_t)(uintptr_t)(ptr)
2752 #define GREG_TO_PTR(greg) (gpointer)(guint32)(greg)
2753 #endif
2754
2755 /*
2756  * mono_arch_get_start_dyn_call:
2757  *
2758  *   Convert the arguments ARGS to a format which can be passed to OP_DYN_CALL, and
2759  * store the result into BUF.
2760  * ARGS should be an array of pointers pointing to the arguments.
2761  * RET should point to a memory buffer large enought to hold the result of the
2762  * call.
2763  * This function should be as fast as possible, any work which does not depend
2764  * on the actual values of the arguments should be done in 
2765  * mono_arch_dyn_call_prepare ().
2766  * start_dyn_call + OP_DYN_CALL + finish_dyn_call is equivalent to ffi_call in
2767  * libffi.
2768  */
2769 void
2770 mono_arch_start_dyn_call (MonoDynCallInfo *info, gpointer **args, guint8 *ret, guint8 *buf, int buf_len)
2771 {
2772         ArchDynCallInfo *dinfo = (ArchDynCallInfo*)info;
2773         DynCallArgs *p = (DynCallArgs*)buf;
2774         int arg_index, greg, i, pindex;
2775         MonoMethodSignature *sig = dinfo->sig;
2776
2777         g_assert (buf_len >= sizeof (DynCallArgs));
2778
2779         p->res = 0;
2780         p->ret = ret;
2781
2782         arg_index = 0;
2783         greg = 0;
2784         pindex = 0;
2785
2786         if (sig->hasthis || dinfo->cinfo->vret_arg_index == 1) {
2787                 p->regs [greg ++] = PTR_TO_GREG(*(args [arg_index ++]));
2788                 if (!sig->hasthis)
2789                         pindex = 1;
2790         }
2791
2792         if (dinfo->cinfo->vtype_retaddr)
2793                 p->regs [greg ++] = PTR_TO_GREG(ret);
2794
2795         for (i = pindex; i < sig->param_count; i++) {
2796                 MonoType *t = mono_type_get_underlying_type (sig->params [i]);
2797                 gpointer *arg = args [arg_index ++];
2798
2799                 if (t->byref) {
2800                         p->regs [greg ++] = PTR_TO_GREG(*(arg));
2801                         continue;
2802                 }
2803
2804                 switch (t->type) {
2805                 case MONO_TYPE_STRING:
2806                 case MONO_TYPE_CLASS:  
2807                 case MONO_TYPE_ARRAY:
2808                 case MONO_TYPE_SZARRAY:
2809                 case MONO_TYPE_OBJECT:
2810                 case MONO_TYPE_PTR:
2811                 case MONO_TYPE_I:
2812                 case MONO_TYPE_U:
2813 #if !defined(__mono_ilp32__)
2814                 case MONO_TYPE_I8:
2815                 case MONO_TYPE_U8:
2816 #endif
2817                         g_assert (dinfo->cinfo->args [i + sig->hasthis].reg == param_regs [greg]);
2818                         p->regs [greg ++] = PTR_TO_GREG(*(arg));
2819                         break;
2820 #if defined(__mono_ilp32__)
2821                 case MONO_TYPE_I8:
2822                 case MONO_TYPE_U8:
2823                         g_assert (dinfo->cinfo->args [i + sig->hasthis].reg == param_regs [greg]);
2824                         p->regs [greg ++] = *(guint64*)(arg);
2825                         break;
2826 #endif
2827                 case MONO_TYPE_BOOLEAN:
2828                 case MONO_TYPE_U1:
2829                         p->regs [greg ++] = *(guint8*)(arg);
2830                         break;
2831                 case MONO_TYPE_I1:
2832                         p->regs [greg ++] = *(gint8*)(arg);
2833                         break;
2834                 case MONO_TYPE_I2:
2835                         p->regs [greg ++] = *(gint16*)(arg);
2836                         break;
2837                 case MONO_TYPE_U2:
2838                 case MONO_TYPE_CHAR:
2839                         p->regs [greg ++] = *(guint16*)(arg);
2840                         break;
2841                 case MONO_TYPE_I4:
2842                         p->regs [greg ++] = *(gint32*)(arg);
2843                         break;
2844                 case MONO_TYPE_U4:
2845                         p->regs [greg ++] = *(guint32*)(arg);
2846                         break;
2847                 case MONO_TYPE_GENERICINST:
2848                     if (MONO_TYPE_IS_REFERENCE (t)) {
2849                                 p->regs [greg ++] = PTR_TO_GREG(*(arg));
2850                                 break;
2851                         } else {
2852                                 /* Fall through */
2853                         }
2854                 case MONO_TYPE_VALUETYPE: {
2855                         ArgInfo *ainfo = &dinfo->cinfo->args [i + sig->hasthis];
2856
2857                         g_assert (ainfo->storage == ArgValuetypeInReg);
2858                         if (ainfo->pair_storage [0] != ArgNone) {
2859                                 g_assert (ainfo->pair_storage [0] == ArgInIReg);
2860                                 p->regs [greg ++] = ((mgreg_t*)(arg))[0];
2861                         }
2862                         if (ainfo->pair_storage [1] != ArgNone) {
2863                                 g_assert (ainfo->pair_storage [1] == ArgInIReg);
2864                                 p->regs [greg ++] = ((mgreg_t*)(arg))[1];
2865                         }
2866                         break;
2867                 }
2868                 default:
2869                         g_assert_not_reached ();
2870                 }
2871         }
2872
2873         g_assert (greg <= PARAM_REGS);
2874 }
2875
2876 /*
2877  * mono_arch_finish_dyn_call:
2878  *
2879  *   Store the result of a dyn call into the return value buffer passed to
2880  * start_dyn_call ().
2881  * This function should be as fast as possible, any work which does not depend
2882  * on the actual values of the arguments should be done in 
2883  * mono_arch_dyn_call_prepare ().
2884  */
2885 void
2886 mono_arch_finish_dyn_call (MonoDynCallInfo *info, guint8 *buf)
2887 {
2888         ArchDynCallInfo *dinfo = (ArchDynCallInfo*)info;
2889         MonoMethodSignature *sig = dinfo->sig;
2890         guint8 *ret = ((DynCallArgs*)buf)->ret;
2891         mgreg_t res = ((DynCallArgs*)buf)->res;
2892
2893         switch (mono_type_get_underlying_type (sig->ret)->type) {
2894         case MONO_TYPE_VOID:
2895                 *(gpointer*)ret = NULL;
2896                 break;
2897         case MONO_TYPE_STRING:
2898         case MONO_TYPE_CLASS:  
2899         case MONO_TYPE_ARRAY:
2900         case MONO_TYPE_SZARRAY:
2901         case MONO_TYPE_OBJECT:
2902         case MONO_TYPE_I:
2903         case MONO_TYPE_U:
2904         case MONO_TYPE_PTR:
2905                 *(gpointer*)ret = GREG_TO_PTR(res);
2906                 break;
2907         case MONO_TYPE_I1:
2908                 *(gint8*)ret = res;
2909                 break;
2910         case MONO_TYPE_U1:
2911         case MONO_TYPE_BOOLEAN:
2912                 *(guint8*)ret = res;
2913                 break;
2914         case MONO_TYPE_I2:
2915                 *(gint16*)ret = res;
2916                 break;
2917         case MONO_TYPE_U2:
2918         case MONO_TYPE_CHAR:
2919                 *(guint16*)ret = res;
2920                 break;
2921         case MONO_TYPE_I4:
2922                 *(gint32*)ret = res;
2923                 break;
2924         case MONO_TYPE_U4:
2925                 *(guint32*)ret = res;
2926                 break;
2927         case MONO_TYPE_I8:
2928                 *(gint64*)ret = res;
2929                 break;
2930         case MONO_TYPE_U8:
2931                 *(guint64*)ret = res;
2932                 break;
2933         case MONO_TYPE_GENERICINST:
2934                 if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
2935                         *(gpointer*)ret = GREG_TO_PTR(res);
2936                         break;
2937                 } else {
2938                         /* Fall through */
2939                 }
2940         case MONO_TYPE_VALUETYPE:
2941                 if (dinfo->cinfo->vtype_retaddr) {
2942                         /* Nothing to do */
2943                 } else {
2944                         ArgInfo *ainfo = &dinfo->cinfo->ret;
2945
2946                         g_assert (ainfo->storage == ArgValuetypeInReg);
2947
2948                         if (ainfo->pair_storage [0] != ArgNone) {
2949                                 g_assert (ainfo->pair_storage [0] == ArgInIReg);
2950                                 ((mgreg_t*)ret)[0] = res;
2951                         }
2952
2953                         g_assert (ainfo->pair_storage [1] == ArgNone);
2954                 }
2955                 break;
2956         default:
2957                 g_assert_not_reached ();
2958         }
2959 }
2960
2961 /* emit an exception if condition is fail */
2962 #define EMIT_COND_SYSTEM_EXCEPTION(cond,signed,exc_name)            \
2963         do {                                                        \
2964                 MonoInst *tins = mono_branch_optimize_exception_target (cfg, bb, exc_name); \
2965                 if (tins == NULL) {                                                                             \
2966                         mono_add_patch_info (cfg, code - cfg->native_code,   \
2967                                         MONO_PATCH_INFO_EXC, exc_name);  \
2968                         x86_branch32 (code, cond, 0, signed);               \
2969                 } else {        \
2970                         EMIT_COND_BRANCH (tins, cond, signed);  \
2971                 }                       \
2972         } while (0); 
2973
2974 #define EMIT_FPCOMPARE(code) do { \
2975         amd64_fcompp (code); \
2976         amd64_fnstsw (code); \
2977 } while (0); 
2978
2979 #define EMIT_SSE2_FPFUNC(code, op, dreg, sreg1) do { \
2980     amd64_movsd_membase_reg (code, AMD64_RSP, -8, (sreg1)); \
2981         amd64_fld_membase (code, AMD64_RSP, -8, TRUE); \
2982         amd64_ ##op (code); \
2983         amd64_fst_membase (code, AMD64_RSP, -8, TRUE, TRUE); \
2984         amd64_movsd_reg_membase (code, (dreg), AMD64_RSP, -8); \
2985 } while (0);
2986
2987 static guint8*
2988 emit_call_body (MonoCompile *cfg, guint8 *code, guint32 patch_type, gconstpointer data)
2989 {
2990         gboolean no_patch = FALSE;
2991
2992         /* 
2993          * FIXME: Add support for thunks
2994          */
2995         {
2996                 gboolean near_call = FALSE;
2997
2998                 /*
2999                  * Indirect calls are expensive so try to make a near call if possible.
3000                  * The caller memory is allocated by the code manager so it is 
3001                  * guaranteed to be at a 32 bit offset.
3002                  */
3003
3004                 if (patch_type != MONO_PATCH_INFO_ABS) {
3005                         /* The target is in memory allocated using the code manager */
3006                         near_call = TRUE;
3007
3008                         if ((patch_type == MONO_PATCH_INFO_METHOD) || (patch_type == MONO_PATCH_INFO_METHOD_JUMP)) {
3009                                 if (((MonoMethod*)data)->klass->image->aot_module)
3010                                         /* The callee might be an AOT method */
3011                                         near_call = FALSE;
3012                                 if (((MonoMethod*)data)->dynamic)
3013                                         /* The target is in malloc-ed memory */
3014                                         near_call = FALSE;
3015                         }
3016
3017                         if (patch_type == MONO_PATCH_INFO_INTERNAL_METHOD) {
3018                                 /* 
3019                                  * The call might go directly to a native function without
3020                                  * the wrapper.
3021                                  */
3022                                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (data);
3023                                 if (mi) {
3024                                         gconstpointer target = mono_icall_get_wrapper (mi);
3025                                         if ((((guint64)target) >> 32) != 0)
3026                                                 near_call = FALSE;
3027                                 }
3028                         }
3029                 }
3030                 else {
3031                         if (cfg->abs_patches && g_hash_table_lookup (cfg->abs_patches, data)) {
3032                                 /* 
3033                                  * This is not really an optimization, but required because the
3034                                  * generic class init trampolines use R11 to pass the vtable.
3035                                  */
3036                                 near_call = TRUE;
3037                         } else {
3038                                 MonoJitICallInfo *info = mono_find_jit_icall_by_addr (data);
3039                                 if (info) {
3040                                         if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && 
3041                                                 strstr (cfg->method->name, info->name)) {
3042                                                 /* A call to the wrapped function */
3043                                                 if ((((guint64)data) >> 32) == 0)
3044                                                         near_call = TRUE;
3045                                                 no_patch = TRUE;
3046                                         }
3047                                         else if (info->func == info->wrapper) {
3048                                                 /* No wrapper */
3049                                                 if ((((guint64)info->func) >> 32) == 0)
3050                                                         near_call = TRUE;
3051                                         }
3052                                         else {
3053                                                 /* See the comment in mono_codegen () */
3054                                                 if ((info->name [0] != 'v') || (strstr (info->name, "ves_array_new_va_") == NULL && strstr (info->name, "ves_array_element_address_") == NULL))
3055                                                         near_call = TRUE;
3056                                         }
3057                                 }
3058                                 else if ((((guint64)data) >> 32) == 0) {
3059                                         near_call = TRUE;
3060                                         no_patch = TRUE;
3061                                 }
3062                         }
3063                 }
3064
3065                 if (cfg->method->dynamic)
3066                         /* These methods are allocated using malloc */
3067                         near_call = FALSE;
3068
3069 #ifdef MONO_ARCH_NOMAP32BIT
3070                 near_call = FALSE;
3071 #endif
3072
3073                 /* The 64bit XEN kernel does not honour the MAP_32BIT flag. (#522894) */
3074                 if (optimize_for_xen)
3075                         near_call = FALSE;
3076
3077                 if (cfg->compile_aot) {
3078                         near_call = TRUE;
3079                         no_patch = TRUE;
3080                 }
3081
3082                 if (near_call) {
3083                         /* 
3084                          * Align the call displacement to an address divisible by 4 so it does
3085                          * not span cache lines. This is required for code patching to work on SMP
3086                          * systems.
3087                          */
3088                         if (!no_patch && ((guint32)(code + 1 - cfg->native_code) % 4) != 0) {
3089                                 guint32 pad_size = 4 - ((guint32)(code + 1 - cfg->native_code) % 4);
3090                                 amd64_padding (code, pad_size);
3091                         }
3092                         mono_add_patch_info (cfg, code - cfg->native_code, patch_type, data);
3093                         amd64_call_code (code, 0);
3094                 }
3095                 else {
3096                         mono_add_patch_info (cfg, code - cfg->native_code, patch_type, data);
3097                         amd64_set_reg_template (code, GP_SCRATCH_REG);
3098                         amd64_call_reg (code, GP_SCRATCH_REG);
3099                 }
3100         }
3101
3102         return code;
3103 }
3104
3105 static inline guint8*
3106 emit_call (MonoCompile *cfg, guint8 *code, guint32 patch_type, gconstpointer data, gboolean win64_adjust_stack)
3107 {
3108 #ifdef HOST_WIN32
3109         if (win64_adjust_stack)
3110                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 32);
3111 #endif
3112         code = emit_call_body (cfg, code, patch_type, data);
3113 #ifdef HOST_WIN32
3114         if (win64_adjust_stack)
3115                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 32);
3116 #endif  
3117         
3118         return code;
3119 }
3120
3121 static inline int
3122 store_membase_imm_to_store_membase_reg (int opcode)
3123 {
3124         switch (opcode) {
3125         case OP_STORE_MEMBASE_IMM:
3126                 return OP_STORE_MEMBASE_REG;
3127         case OP_STOREI4_MEMBASE_IMM:
3128                 return OP_STOREI4_MEMBASE_REG;
3129         case OP_STOREI8_MEMBASE_IMM:
3130                 return OP_STOREI8_MEMBASE_REG;
3131         }
3132
3133         return -1;
3134 }
3135
3136 #ifndef DISABLE_JIT
3137
3138 #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)))
3139
3140 /*
3141  * mono_arch_peephole_pass_1:
3142  *
3143  *   Perform peephole opts which should/can be performed before local regalloc
3144  */
3145 void
3146 mono_arch_peephole_pass_1 (MonoCompile *cfg, MonoBasicBlock *bb)
3147 {
3148         MonoInst *ins, *n;
3149
3150         MONO_BB_FOR_EACH_INS_SAFE (bb, n, ins) {
3151                 MonoInst *last_ins = ins->prev;
3152
3153                 switch (ins->opcode) {
3154                 case OP_ADD_IMM:
3155                 case OP_IADD_IMM:
3156                 case OP_LADD_IMM:
3157                         if ((ins->sreg1 < MONO_MAX_IREGS) && (ins->dreg >= MONO_MAX_IREGS) && (ins->inst_imm > 0)) {
3158                                 /* 
3159                                  * X86_LEA is like ADD, but doesn't have the
3160                                  * sreg1==dreg restriction. inst_imm > 0 is needed since LEA sign-extends 
3161                                  * its operand to 64 bit.
3162                                  */
3163                                 ins->opcode = OP_X86_LEA_MEMBASE;
3164                                 ins->inst_basereg = ins->sreg1;
3165                         }
3166                         break;
3167                 case OP_LXOR:
3168                 case OP_IXOR:
3169                         if ((ins->sreg1 == ins->sreg2) && (ins->sreg1 == ins->dreg)) {
3170                                 MonoInst *ins2;
3171
3172                                 /* 
3173                                  * Replace STORE_MEMBASE_IMM 0 with STORE_MEMBASE_REG since 
3174                                  * the latter has length 2-3 instead of 6 (reverse constant
3175                                  * propagation). These instruction sequences are very common
3176                                  * in the initlocals bblock.
3177                                  */
3178                                 for (ins2 = ins->next; ins2; ins2 = ins2->next) {
3179                                         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)) {
3180                                                 ins2->opcode = store_membase_imm_to_store_membase_reg (ins2->opcode);
3181                                                 ins2->sreg1 = ins->dreg;
3182                                         } 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)) {
3183                                                 /* Continue */
3184                                         } else if (((ins2->opcode == OP_ICONST) || (ins2->opcode == OP_I8CONST)) && (ins2->dreg == ins->dreg) && (ins2->inst_c0 == 0)) {
3185                                                 NULLIFY_INS (ins2);
3186                                                 /* Continue */
3187                                         } else {
3188                                                 break;
3189                                         }
3190                                 }
3191                         }
3192                         break;
3193                 case OP_COMPARE_IMM:
3194                 case OP_LCOMPARE_IMM:
3195                         /* OP_COMPARE_IMM (reg, 0) 
3196                          * --> 
3197                          * OP_AMD64_TEST_NULL (reg) 
3198                          */
3199                         if (!ins->inst_imm)
3200                                 ins->opcode = OP_AMD64_TEST_NULL;
3201                         break;
3202                 case OP_ICOMPARE_IMM:
3203                         if (!ins->inst_imm)
3204                                 ins->opcode = OP_X86_TEST_NULL;
3205                         break;
3206                 case OP_AMD64_ICOMPARE_MEMBASE_IMM:
3207                         /* 
3208                          * OP_STORE_MEMBASE_REG reg, offset(basereg)
3209                          * OP_X86_COMPARE_MEMBASE_IMM offset(basereg), imm
3210                          * -->
3211                          * OP_STORE_MEMBASE_REG reg, offset(basereg)
3212                          * OP_COMPARE_IMM reg, imm
3213                          *
3214                          * Note: if imm = 0 then OP_COMPARE_IMM replaced with OP_X86_TEST_NULL
3215                          */
3216                         if (last_ins && (last_ins->opcode == OP_STOREI4_MEMBASE_REG) &&
3217                             ins->inst_basereg == last_ins->inst_destbasereg &&
3218                             ins->inst_offset == last_ins->inst_offset) {
3219                                         ins->opcode = OP_ICOMPARE_IMM;
3220                                         ins->sreg1 = last_ins->sreg1;
3221
3222                                         /* check if we can remove cmp reg,0 with test null */
3223                                         if (!ins->inst_imm)
3224                                                 ins->opcode = OP_X86_TEST_NULL;
3225                                 }
3226
3227                         break;
3228                 }
3229
3230                 mono_peephole_ins (bb, ins);
3231         }
3232 }
3233
3234 void
3235 mono_arch_peephole_pass_2 (MonoCompile *cfg, MonoBasicBlock *bb)
3236 {
3237         MonoInst *ins, *n;
3238
3239         MONO_BB_FOR_EACH_INS_SAFE (bb, n, ins) {
3240                 switch (ins->opcode) {
3241                 case OP_ICONST:
3242                 case OP_I8CONST: {
3243                         /* reg = 0 -> XOR (reg, reg) */
3244                         /* XOR sets cflags on x86, so we cant do it always */
3245                         if (ins->inst_c0 == 0 && (!ins->next || (ins->next && INST_IGNORES_CFLAGS (ins->next->opcode)))) {
3246                                 ins->opcode = OP_LXOR;
3247                                 ins->sreg1 = ins->dreg;
3248                                 ins->sreg2 = ins->dreg;
3249                                 /* Fall through */
3250                         } else {
3251                                 break;
3252                         }
3253                 }
3254                 case OP_LXOR:
3255                         /*
3256                          * Use IXOR to avoid a rex prefix if possible. The cpu will sign extend the 
3257                          * 0 result into 64 bits.
3258                          */
3259                         if ((ins->sreg1 == ins->sreg2) && (ins->sreg1 == ins->dreg)) {
3260                                 ins->opcode = OP_IXOR;
3261                         }
3262                         /* Fall through */
3263                 case OP_IXOR:
3264                         if ((ins->sreg1 == ins->sreg2) && (ins->sreg1 == ins->dreg)) {
3265                                 MonoInst *ins2;
3266
3267                                 /* 
3268                                  * Replace STORE_MEMBASE_IMM 0 with STORE_MEMBASE_REG since 
3269                                  * the latter has length 2-3 instead of 6 (reverse constant
3270                                  * propagation). These instruction sequences are very common
3271                                  * in the initlocals bblock.
3272                                  */
3273                                 for (ins2 = ins->next; ins2; ins2 = ins2->next) {
3274                                         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)) {
3275                                                 ins2->opcode = store_membase_imm_to_store_membase_reg (ins2->opcode);
3276                                                 ins2->sreg1 = ins->dreg;
3277                                         } 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)) {
3278                                                 /* Continue */
3279                                         } else if (((ins2->opcode == OP_ICONST) || (ins2->opcode == OP_I8CONST)) && (ins2->dreg == ins->dreg) && (ins2->inst_c0 == 0)) {
3280                                                 NULLIFY_INS (ins2);
3281                                                 /* Continue */
3282                                         } else {
3283                                                 break;
3284                                         }
3285                                 }
3286                         }
3287                         break;
3288                 case OP_IADD_IMM:
3289                         if ((ins->inst_imm == 1) && (ins->dreg == ins->sreg1))
3290                                 ins->opcode = OP_X86_INC_REG;
3291                         break;
3292                 case OP_ISUB_IMM:
3293                         if ((ins->inst_imm == 1) && (ins->dreg == ins->sreg1))
3294                                 ins->opcode = OP_X86_DEC_REG;
3295                         break;
3296                 }
3297
3298                 mono_peephole_ins (bb, ins);
3299         }
3300 }
3301
3302 #define NEW_INS(cfg,ins,dest,op) do {   \
3303                 MONO_INST_NEW ((cfg), (dest), (op)); \
3304         (dest)->cil_code = (ins)->cil_code; \
3305         mono_bblock_insert_before_ins (bb, ins, (dest)); \
3306         } while (0)
3307
3308 /*
3309  * mono_arch_lowering_pass:
3310  *
3311  *  Converts complex opcodes into simpler ones so that each IR instruction
3312  * corresponds to one machine instruction.
3313  */
3314 void
3315 mono_arch_lowering_pass (MonoCompile *cfg, MonoBasicBlock *bb)
3316 {
3317         MonoInst *ins, *n, *temp;
3318
3319         /*
3320          * FIXME: Need to add more instructions, but the current machine 
3321          * description can't model some parts of the composite instructions like
3322          * cdq.
3323          */
3324         MONO_BB_FOR_EACH_INS_SAFE (bb, n, ins) {
3325                 switch (ins->opcode) {
3326                 case OP_DIV_IMM:
3327                 case OP_REM_IMM:
3328                 case OP_IDIV_IMM:
3329                 case OP_IDIV_UN_IMM:
3330                 case OP_IREM_UN_IMM:
3331                         mono_decompose_op_imm (cfg, bb, ins);
3332                         break;
3333                 case OP_IREM_IMM:
3334                         /* Keep the opcode if we can implement it efficiently */
3335                         if (!((ins->inst_imm > 0) && (mono_is_power_of_two (ins->inst_imm) != -1)))
3336                                 mono_decompose_op_imm (cfg, bb, ins);
3337                         break;
3338                 case OP_COMPARE_IMM:
3339                 case OP_LCOMPARE_IMM:
3340                         if (!amd64_is_imm32 (ins->inst_imm)) {
3341                                 NEW_INS (cfg, ins, temp, OP_I8CONST);
3342                                 temp->inst_c0 = ins->inst_imm;
3343                                 temp->dreg = mono_alloc_ireg (cfg);
3344                                 ins->opcode = OP_COMPARE;
3345                                 ins->sreg2 = temp->dreg;
3346                         }
3347                         break;
3348 #ifndef __mono_ilp32__
3349                 case OP_LOAD_MEMBASE:
3350 #endif
3351                 case OP_LOADI8_MEMBASE:
3352 #ifndef __native_client_codegen__
3353                 /*  Don't generate memindex opcodes (to simplify */
3354                 /*  read sandboxing) */
3355                         if (!amd64_is_imm32 (ins->inst_offset)) {
3356                                 NEW_INS (cfg, ins, temp, OP_I8CONST);
3357                                 temp->inst_c0 = ins->inst_offset;
3358                                 temp->dreg = mono_alloc_ireg (cfg);
3359                                 ins->opcode = OP_AMD64_LOADI8_MEMINDEX;
3360                                 ins->inst_indexreg = temp->dreg;
3361                         }
3362 #endif
3363                         break;
3364 #ifndef __mono_ilp32__
3365                 case OP_STORE_MEMBASE_IMM:
3366 #endif
3367                 case OP_STOREI8_MEMBASE_IMM:
3368                         if (!amd64_is_imm32 (ins->inst_imm)) {
3369                                 NEW_INS (cfg, ins, temp, OP_I8CONST);
3370                                 temp->inst_c0 = ins->inst_imm;
3371                                 temp->dreg = mono_alloc_ireg (cfg);
3372                                 ins->opcode = OP_STOREI8_MEMBASE_REG;
3373                                 ins->sreg1 = temp->dreg;
3374                         }
3375                         break;
3376 #ifdef MONO_ARCH_SIMD_INTRINSICS
3377                 case OP_EXPAND_I1: {
3378                                 int temp_reg1 = mono_alloc_ireg (cfg);
3379                                 int temp_reg2 = mono_alloc_ireg (cfg);
3380                                 int original_reg = ins->sreg1;
3381
3382                                 NEW_INS (cfg, ins, temp, OP_ICONV_TO_U1);
3383                                 temp->sreg1 = original_reg;
3384                                 temp->dreg = temp_reg1;
3385
3386                                 NEW_INS (cfg, ins, temp, OP_SHL_IMM);
3387                                 temp->sreg1 = temp_reg1;
3388                                 temp->dreg = temp_reg2;
3389                                 temp->inst_imm = 8;
3390
3391                                 NEW_INS (cfg, ins, temp, OP_LOR);
3392                                 temp->sreg1 = temp->dreg = temp_reg2;
3393                                 temp->sreg2 = temp_reg1;
3394
3395                                 ins->opcode = OP_EXPAND_I2;
3396                                 ins->sreg1 = temp_reg2;
3397                         }
3398                         break;
3399 #endif
3400                 default:
3401                         break;
3402                 }
3403         }
3404
3405         bb->max_vreg = cfg->next_vreg;
3406 }
3407
3408 static const int 
3409 branch_cc_table [] = {
3410         X86_CC_EQ, X86_CC_GE, X86_CC_GT, X86_CC_LE, X86_CC_LT,
3411         X86_CC_NE, X86_CC_GE, X86_CC_GT, X86_CC_LE, X86_CC_LT,
3412         X86_CC_O, X86_CC_NO, X86_CC_C, X86_CC_NC
3413 };
3414
3415 /* Maps CMP_... constants to X86_CC_... constants */
3416 static const int
3417 cc_table [] = {
3418         X86_CC_EQ, X86_CC_NE, X86_CC_LE, X86_CC_GE, X86_CC_LT, X86_CC_GT,
3419         X86_CC_LE, X86_CC_GE, X86_CC_LT, X86_CC_GT
3420 };
3421
3422 static const int
3423 cc_signed_table [] = {
3424         TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
3425         FALSE, FALSE, FALSE, FALSE
3426 };
3427
3428 /*#include "cprop.c"*/
3429
3430 static unsigned char*
3431 emit_float_to_int (MonoCompile *cfg, guchar *code, int dreg, int sreg, int size, gboolean is_signed)
3432 {
3433         amd64_sse_cvttsd2si_reg_reg (code, dreg, sreg);
3434
3435         if (size == 1)
3436                 amd64_widen_reg (code, dreg, dreg, is_signed, FALSE);
3437         else if (size == 2)
3438                 amd64_widen_reg (code, dreg, dreg, is_signed, TRUE);
3439         return code;
3440 }
3441
3442 static unsigned char*
3443 mono_emit_stack_alloc (MonoCompile *cfg, guchar *code, MonoInst* tree)
3444 {
3445         int sreg = tree->sreg1;
3446         int need_touch = FALSE;
3447
3448 #if defined(HOST_WIN32) || defined(MONO_ARCH_SIGSEGV_ON_ALTSTACK)
3449         if (!tree->flags & MONO_INST_INIT)
3450                 need_touch = TRUE;
3451 #endif
3452
3453         if (need_touch) {
3454                 guint8* br[5];
3455
3456                 /*
3457                  * Under Windows:
3458                  * If requested stack size is larger than one page,
3459                  * perform stack-touch operation
3460                  */
3461                 /*
3462                  * Generate stack probe code.
3463                  * Under Windows, it is necessary to allocate one page at a time,
3464                  * "touching" stack after each successful sub-allocation. This is
3465                  * because of the way stack growth is implemented - there is a
3466                  * guard page before the lowest stack page that is currently commited.
3467                  * Stack normally grows sequentially so OS traps access to the
3468                  * guard page and commits more pages when needed.
3469                  */
3470                 amd64_test_reg_imm (code, sreg, ~0xFFF);
3471                 br[0] = code; x86_branch8 (code, X86_CC_Z, 0, FALSE);
3472
3473                 br[2] = code; /* loop */
3474                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 0x1000);
3475                 amd64_test_membase_reg (code, AMD64_RSP, 0, AMD64_RSP);
3476                 amd64_alu_reg_imm (code, X86_SUB, sreg, 0x1000);
3477                 amd64_alu_reg_imm (code, X86_CMP, sreg, 0x1000);
3478                 br[3] = code; x86_branch8 (code, X86_CC_AE, 0, FALSE);
3479                 amd64_patch (br[3], br[2]);
3480                 amd64_test_reg_reg (code, sreg, sreg);
3481                 br[4] = code; x86_branch8 (code, X86_CC_Z, 0, FALSE);
3482                 amd64_alu_reg_reg (code, X86_SUB, AMD64_RSP, sreg);
3483
3484                 br[1] = code; x86_jump8 (code, 0);
3485
3486                 amd64_patch (br[0], code);
3487                 amd64_alu_reg_reg (code, X86_SUB, AMD64_RSP, sreg);
3488                 amd64_patch (br[1], code);
3489                 amd64_patch (br[4], code);
3490         }
3491         else
3492                 amd64_alu_reg_reg (code, X86_SUB, AMD64_RSP, tree->sreg1);
3493
3494         if (tree->flags & MONO_INST_INIT) {
3495                 int offset = 0;
3496                 if (tree->dreg != AMD64_RAX && sreg != AMD64_RAX) {
3497                         amd64_push_reg (code, AMD64_RAX);
3498                         offset += 8;
3499                 }
3500                 if (tree->dreg != AMD64_RCX && sreg != AMD64_RCX) {
3501                         amd64_push_reg (code, AMD64_RCX);
3502                         offset += 8;
3503                 }
3504                 if (tree->dreg != AMD64_RDI && sreg != AMD64_RDI) {
3505                         amd64_push_reg (code, AMD64_RDI);
3506                         offset += 8;
3507                 }
3508                 
3509                 amd64_shift_reg_imm (code, X86_SHR, sreg, 3);
3510                 if (sreg != AMD64_RCX)
3511                         amd64_mov_reg_reg (code, AMD64_RCX, sreg, 8);
3512                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
3513                                 
3514                 amd64_lea_membase (code, AMD64_RDI, AMD64_RSP, offset);
3515                 if (cfg->param_area && cfg->arch.no_pushes)
3516                         amd64_alu_reg_imm (code, X86_ADD, AMD64_RDI, cfg->param_area);
3517                 amd64_cld (code);
3518 #if defined(__default_codegen__)
3519                 amd64_prefix (code, X86_REP_PREFIX);
3520                 amd64_stosl (code);
3521 #elif defined(__native_client_codegen__)
3522                 /* NaCl stos pseudo-instruction */
3523                 amd64_codegen_pre(code);
3524                 /* First, clear the upper 32 bits of RDI (mov %edi, %edi)  */
3525                 amd64_mov_reg_reg (code, AMD64_RDI, AMD64_RDI, 4);
3526                 /* Add %r15 to %rdi using lea, condition flags unaffected. */
3527                 amd64_lea_memindex_size (code, AMD64_RDI, AMD64_R15, 0, AMD64_RDI, 0, 8);
3528                 amd64_prefix (code, X86_REP_PREFIX);
3529                 amd64_stosl (code);
3530                 amd64_codegen_post(code);
3531 #endif /* __native_client_codegen__ */
3532                 
3533                 if (tree->dreg != AMD64_RDI && sreg != AMD64_RDI)
3534                         amd64_pop_reg (code, AMD64_RDI);
3535                 if (tree->dreg != AMD64_RCX && sreg != AMD64_RCX)
3536                         amd64_pop_reg (code, AMD64_RCX);
3537                 if (tree->dreg != AMD64_RAX && sreg != AMD64_RAX)
3538                         amd64_pop_reg (code, AMD64_RAX);
3539         }
3540         return code;
3541 }
3542
3543 static guint8*
3544 emit_move_return_value (MonoCompile *cfg, MonoInst *ins, guint8 *code)
3545 {
3546         CallInfo *cinfo;
3547         guint32 quad;
3548
3549         /* Move return value to the target register */
3550         /* FIXME: do this in the local reg allocator */
3551         switch (ins->opcode) {
3552         case OP_CALL:
3553         case OP_CALL_REG:
3554         case OP_CALL_MEMBASE:
3555         case OP_LCALL:
3556         case OP_LCALL_REG:
3557         case OP_LCALL_MEMBASE:
3558                 g_assert (ins->dreg == AMD64_RAX);
3559                 break;
3560         case OP_FCALL:
3561         case OP_FCALL_REG:
3562         case OP_FCALL_MEMBASE:
3563                 if (((MonoCallInst*)ins)->signature->ret->type == MONO_TYPE_R4) {
3564                         amd64_sse_cvtss2sd_reg_reg (code, ins->dreg, AMD64_XMM0);
3565                 }
3566                 else {
3567                         if (ins->dreg != AMD64_XMM0)
3568                                 amd64_sse_movsd_reg_reg (code, ins->dreg, AMD64_XMM0);
3569                 }
3570                 break;
3571         case OP_VCALL:
3572         case OP_VCALL_REG:
3573         case OP_VCALL_MEMBASE:
3574         case OP_VCALL2:
3575         case OP_VCALL2_REG:
3576         case OP_VCALL2_MEMBASE:
3577                 cinfo = get_call_info (cfg->generic_sharing_context, cfg->mempool, ((MonoCallInst*)ins)->signature);
3578                 if (cinfo->ret.storage == ArgValuetypeInReg) {
3579                         MonoInst *loc = cfg->arch.vret_addr_loc;
3580
3581                         /* Load the destination address */
3582                         g_assert (loc->opcode == OP_REGOFFSET);
3583                         amd64_mov_reg_membase (code, AMD64_RCX, loc->inst_basereg, loc->inst_offset, sizeof(gpointer));
3584
3585                         for (quad = 0; quad < 2; quad ++) {
3586                                 switch (cinfo->ret.pair_storage [quad]) {
3587                                 case ArgInIReg:
3588                                         amd64_mov_membase_reg (code, AMD64_RCX, (quad * sizeof(mgreg_t)), cinfo->ret.pair_regs [quad], sizeof(mgreg_t));
3589                                         break;
3590                                 case ArgInFloatSSEReg:
3591                                         amd64_movss_membase_reg (code, AMD64_RCX, (quad * 8), cinfo->ret.pair_regs [quad]);
3592                                         break;
3593                                 case ArgInDoubleSSEReg:
3594                                         amd64_movsd_membase_reg (code, AMD64_RCX, (quad * 8), cinfo->ret.pair_regs [quad]);
3595                                         break;
3596                                 case ArgNone:
3597                                         break;
3598                                 default:
3599                                         NOT_IMPLEMENTED;
3600                                 }
3601                         }
3602                 }
3603                 break;
3604         }
3605
3606         return code;
3607 }
3608
3609 #endif /* DISABLE_JIT */
3610
3611 #ifdef __APPLE__
3612 static int tls_gs_offset;
3613 #endif
3614
3615 gboolean
3616 mono_amd64_have_tls_get (void)
3617 {
3618 #ifdef __APPLE__
3619         static gboolean have_tls_get = FALSE;
3620         static gboolean inited = FALSE;
3621
3622         if (inited)
3623                 return have_tls_get;
3624
3625         guint8 *ins = (guint8*)pthread_getspecific;
3626
3627         /*
3628          * We're looking for these two instructions:
3629          *
3630          * mov    %gs:[offset](,%rdi,8),%rax
3631          * retq
3632          */
3633         have_tls_get = ins [0] == 0x65 &&
3634                        ins [1] == 0x48 &&
3635                        ins [2] == 0x8b &&
3636                        ins [3] == 0x04 &&
3637                        ins [4] == 0xfd &&
3638                        ins [6] == 0x00 &&
3639                        ins [7] == 0x00 &&
3640                        ins [8] == 0x00 &&
3641                        ins [9] == 0xc3;
3642
3643         inited = TRUE;
3644
3645         tls_gs_offset = ins[5];
3646
3647         return have_tls_get;
3648 #else
3649         return TRUE;
3650 #endif
3651 }
3652
3653 /*
3654  * mono_amd64_emit_tls_get:
3655  * @code: buffer to store code to
3656  * @dreg: hard register where to place the result
3657  * @tls_offset: offset info
3658  *
3659  * mono_amd64_emit_tls_get emits in @code the native code that puts in
3660  * the dreg register the item in the thread local storage identified
3661  * by tls_offset.
3662  *
3663  * Returns: a pointer to the end of the stored code
3664  */
3665 guint8*
3666 mono_amd64_emit_tls_get (guint8* code, int dreg, int tls_offset)
3667 {
3668 #ifdef HOST_WIN32
3669         g_assert (tls_offset < 64);
3670         x86_prefix (code, X86_GS_PREFIX);
3671         amd64_mov_reg_mem (code, dreg, (tls_offset * 8) + 0x1480, 8);
3672 #elif defined(__APPLE__)
3673         x86_prefix (code, X86_GS_PREFIX);
3674         amd64_mov_reg_mem (code, dreg, tls_gs_offset + (tls_offset * 8), 8);
3675 #else
3676         if (optimize_for_xen) {
3677                 x86_prefix (code, X86_FS_PREFIX);
3678                 amd64_mov_reg_mem (code, dreg, 0, 8);
3679                 amd64_mov_reg_membase (code, dreg, dreg, tls_offset, 8);
3680         } else {
3681                 x86_prefix (code, X86_FS_PREFIX);
3682                 amd64_mov_reg_mem (code, dreg, tls_offset, 8);
3683         }
3684 #endif
3685         return code;
3686 }
3687
3688 /*
3689  * emit_setup_lmf:
3690  *
3691  *   Emit code to initialize an LMF structure at LMF_OFFSET.
3692  */
3693 static guint8*
3694 emit_setup_lmf (MonoCompile *cfg, guint8 *code, gint32 lmf_offset, int cfa_offset)
3695 {
3696         int i;
3697
3698         /* 
3699          * The ip field is not set, the exception handling code will obtain it from the stack location pointed to by the sp field.
3700          */
3701         /* 
3702          * sp is saved right before calls but we need to save it here too so
3703          * async stack walks would work.
3704          */
3705         amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rsp), AMD64_RSP, 8);
3706         /* Skip method (only needed for trampoline LMF frames) */
3707         /* Save callee saved regs */
3708         for (i = 0; i < MONO_MAX_IREGS; ++i) {
3709                 int offset;
3710
3711                 switch (i) {
3712                 case AMD64_RBX: offset = G_STRUCT_OFFSET (MonoLMF, rbx); break;
3713                 case AMD64_RBP: offset = G_STRUCT_OFFSET (MonoLMF, rbp); break;
3714                 case AMD64_R12: offset = G_STRUCT_OFFSET (MonoLMF, r12); break;
3715                 case AMD64_R13: offset = G_STRUCT_OFFSET (MonoLMF, r13); break;
3716                 case AMD64_R14: offset = G_STRUCT_OFFSET (MonoLMF, r14); break;
3717 #ifndef __native_client_codegen__
3718                 case AMD64_R15: offset = G_STRUCT_OFFSET (MonoLMF, r15); break;
3719 #endif
3720 #ifdef HOST_WIN32
3721                 case AMD64_RDI: offset = G_STRUCT_OFFSET (MonoLMF, rdi); break;
3722                 case AMD64_RSI: offset = G_STRUCT_OFFSET (MonoLMF, rsi); break;
3723 #endif
3724                 default:
3725                         offset = -1;
3726                         break;
3727                 }
3728
3729                 if (offset != -1) {
3730                         amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + offset, i, 8);
3731                         if ((cfg->arch.omit_fp || (i != AMD64_RBP)) && cfa_offset != -1)
3732                                 mono_emit_unwind_op_offset (cfg, code, i, - (cfa_offset - (lmf_offset + offset)));
3733                 }
3734         }
3735
3736         /* These can't contain refs */
3737         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), SLOT_NOREF);
3738         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, lmf_addr), SLOT_NOREF);
3739         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, method), SLOT_NOREF);
3740         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rip), SLOT_NOREF);
3741         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rsp), SLOT_NOREF);
3742
3743         /* These are handled automatically by the stack marking code */
3744         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbx), SLOT_NOREF);
3745         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbp), SLOT_NOREF);
3746         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r12), SLOT_NOREF);
3747         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r13), SLOT_NOREF);
3748         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r14), SLOT_NOREF);
3749         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r15), SLOT_NOREF);
3750 #ifdef HOST_WIN32
3751         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rdi), SLOT_NOREF);
3752         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rsi), SLOT_NOREF);
3753 #endif
3754
3755         return code;
3756 }
3757
3758 /*
3759  * emit_save_lmf:
3760  *
3761  *   Emit code to push an LMF structure on the LMF stack.
3762  */
3763 static guint8*
3764 emit_save_lmf (MonoCompile *cfg, guint8 *code, gint32 lmf_offset, gboolean *args_clobbered)
3765 {
3766         if ((lmf_tls_offset != -1) && !optimize_for_xen) {
3767                 /*
3768                  * Optimized version which uses the mono_lmf TLS variable instead of 
3769                  * indirection through the mono_lmf_addr TLS variable.
3770                  */
3771                 /* %rax = previous_lmf */
3772                 x86_prefix (code, X86_FS_PREFIX);
3773                 amd64_mov_reg_mem (code, AMD64_RAX, lmf_tls_offset, 8);
3774
3775                 /* Save previous_lmf */
3776                 amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), AMD64_RAX, 8);
3777                 /* Set new lmf */
3778                 if (lmf_offset == 0) {
3779                         x86_prefix (code, X86_FS_PREFIX);
3780                         amd64_mov_mem_reg (code, lmf_tls_offset, cfg->frame_reg, 8);
3781                 } else {
3782                         amd64_lea_membase (code, AMD64_R11, cfg->frame_reg, lmf_offset);
3783                         x86_prefix (code, X86_FS_PREFIX);
3784                         amd64_mov_mem_reg (code, lmf_tls_offset, AMD64_R11, 8);
3785                 }
3786         } else {
3787                 if (lmf_addr_tls_offset != -1) {
3788                         /* Load lmf quicky using the FS register */
3789                         code = mono_amd64_emit_tls_get (code, AMD64_RAX, lmf_addr_tls_offset);
3790 #ifdef HOST_WIN32
3791                         /* The TLS key actually contains a pointer to the MonoJitTlsData structure */
3792                         /* FIXME: Add a separate key for LMF to avoid this */
3793                         amd64_alu_reg_imm (code, X86_ADD, AMD64_RAX, G_STRUCT_OFFSET (MonoJitTlsData, lmf));
3794 #endif
3795                 }
3796                 else {
3797                         /* 
3798                          * The call might clobber argument registers, but they are already
3799                          * saved to the stack/global regs.
3800                          */
3801                         if (args_clobbered)
3802                                 *args_clobbered = TRUE;
3803                         code = emit_call (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD, 
3804                                                           (gpointer)"mono_get_lmf_addr", TRUE);         
3805                 }
3806
3807                 /* Save lmf_addr */
3808                 amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, lmf_addr), AMD64_RAX, sizeof(gpointer));
3809                 /* Save previous_lmf */
3810                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RAX, 0, sizeof(gpointer));
3811                 amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), AMD64_R11, sizeof(gpointer));
3812                 /* Set new lmf */
3813                 amd64_lea_membase (code, AMD64_R11, cfg->frame_reg, lmf_offset);
3814                 amd64_mov_membase_reg (code, AMD64_RAX, 0, AMD64_R11, sizeof(gpointer));
3815         }
3816
3817         return code;
3818 }
3819
3820 /*
3821  * emit_save_lmf:
3822  *
3823  *   Emit code to pop an LMF structure from the LMF stack.
3824  */
3825 static guint8*
3826 emit_restore_lmf (MonoCompile *cfg, guint8 *code, gint32 lmf_offset)
3827 {
3828         if ((lmf_tls_offset != -1) && !optimize_for_xen) {
3829                 /*
3830                  * Optimized version which uses the mono_lmf TLS variable instead of indirection
3831                  * through the mono_lmf_addr TLS variable.
3832                  */
3833                 /* reg = previous_lmf */
3834                 amd64_mov_reg_membase (code, AMD64_R11, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), sizeof(gpointer));
3835                 x86_prefix (code, X86_FS_PREFIX);
3836                 amd64_mov_mem_reg (code, lmf_tls_offset, AMD64_R11, 8);
3837         } else {
3838                 /* Restore previous lmf */
3839                 amd64_mov_reg_membase (code, AMD64_RCX, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), sizeof(gpointer));
3840                 amd64_mov_reg_membase (code, AMD64_R11, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, lmf_addr), sizeof(gpointer));
3841                 amd64_mov_membase_reg (code, AMD64_R11, 0, AMD64_RCX, sizeof(gpointer));
3842         }
3843
3844         return code;
3845 }
3846
3847 #define REAL_PRINT_REG(text,reg) \
3848 mono_assert (reg >= 0); \
3849 amd64_push_reg (code, AMD64_RAX); \
3850 amd64_push_reg (code, AMD64_RDX); \
3851 amd64_push_reg (code, AMD64_RCX); \
3852 amd64_push_reg (code, reg); \
3853 amd64_push_imm (code, reg); \
3854 amd64_push_imm (code, text " %d %p\n"); \
3855 amd64_mov_reg_imm (code, AMD64_RAX, printf); \
3856 amd64_call_reg (code, AMD64_RAX); \
3857 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 3*4); \
3858 amd64_pop_reg (code, AMD64_RCX); \
3859 amd64_pop_reg (code, AMD64_RDX); \
3860 amd64_pop_reg (code, AMD64_RAX);
3861
3862 /* benchmark and set based on cpu */
3863 #define LOOP_ALIGNMENT 8
3864 #define bb_is_loop_start(bb) ((bb)->loop_body_start && (bb)->nesting)
3865
3866 #ifndef DISABLE_JIT
3867
3868 #if defined(__native_client__) || defined(__native_client_codegen__)
3869 void mono_nacl_gc()
3870 {
3871 #ifdef __native_client_gc__
3872         __nacl_suspend_thread_if_needed();
3873 #endif
3874 }
3875 #endif
3876
3877 void
3878 mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb)
3879 {
3880         MonoInst *ins;
3881         MonoCallInst *call;
3882         guint offset;
3883         guint8 *code = cfg->native_code + cfg->code_len;
3884         MonoInst *last_ins = NULL;
3885         guint last_offset = 0;
3886         int max_len;
3887
3888         /* Fix max_offset estimate for each successor bb */
3889         if (cfg->opt & MONO_OPT_BRANCH) {
3890                 int current_offset = cfg->code_len;
3891                 MonoBasicBlock *current_bb;
3892                 for (current_bb = bb; current_bb != NULL; current_bb = current_bb->next_bb) {
3893                         current_bb->max_offset = current_offset;
3894                         current_offset += current_bb->max_length;
3895                 }
3896         }
3897
3898         if (cfg->opt & MONO_OPT_LOOP) {
3899                 int pad, align = LOOP_ALIGNMENT;
3900                 /* set alignment depending on cpu */
3901                 if (bb_is_loop_start (bb) && (pad = (cfg->code_len & (align - 1)))) {
3902                         pad = align - pad;
3903                         /*g_print ("adding %d pad at %x to loop in %s\n", pad, cfg->code_len, cfg->method->name);*/
3904                         amd64_padding (code, pad);
3905                         cfg->code_len += pad;
3906                         bb->native_offset = cfg->code_len;
3907                 }
3908         }
3909
3910 #if defined(__native_client_codegen__)
3911         /* For Native Client, all indirect call/jump targets must be */
3912         /* 32-byte aligned.  Exception handler blocks are jumped to  */
3913         /* indirectly as well.                                       */
3914         gboolean bb_needs_alignment = (bb->flags & BB_INDIRECT_JUMP_TARGET) ||
3915                                       (bb->flags & BB_EXCEPTION_HANDLER);
3916
3917         if ( bb_needs_alignment && ((cfg->code_len & kNaClAlignmentMask) != 0)) {
3918                 int pad = kNaClAlignment - (cfg->code_len & kNaClAlignmentMask);
3919                 if (pad != kNaClAlignment) code = mono_arch_nacl_pad(code, pad);
3920                 cfg->code_len += pad;
3921                 bb->native_offset = cfg->code_len;
3922         }
3923 #endif  /*__native_client_codegen__*/
3924
3925         if (cfg->verbose_level > 2)
3926                 g_print ("Basic block %d starting at offset 0x%x\n", bb->block_num, bb->native_offset);
3927
3928         if (cfg->prof_options & MONO_PROFILE_COVERAGE) {
3929                 MonoProfileCoverageInfo *cov = cfg->coverage_info;
3930                 g_assert (!cfg->compile_aot);
3931
3932                 cov->data [bb->dfn].cil_code = bb->cil_code;
3933                 amd64_mov_reg_imm (code, AMD64_R11, (guint64)&cov->data [bb->dfn].count);
3934                 /* this is not thread save, but good enough */
3935                 amd64_inc_membase (code, AMD64_R11, 0);
3936         }
3937
3938         offset = code - cfg->native_code;
3939
3940         mono_debug_open_block (cfg, bb, offset);
3941
3942     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)
3943                 x86_breakpoint (code);
3944
3945         MONO_BB_FOR_EACH_INS (bb, ins) {
3946                 offset = code - cfg->native_code;
3947
3948                 max_len = ((guint8 *)ins_get_spec (ins->opcode))[MONO_INST_LEN];
3949
3950 #define EXTRA_CODE_SPACE (NACL_SIZE (16, 16 + kNaClAlignment))
3951
3952                 if (G_UNLIKELY (offset > (cfg->code_size - max_len - EXTRA_CODE_SPACE))) {
3953                         cfg->code_size *= 2;
3954                         cfg->native_code = mono_realloc_native_code(cfg);
3955                         code = cfg->native_code + offset;
3956                         cfg->stat_code_reallocs++;
3957                 }
3958
3959                 if (cfg->debug_info)
3960                         mono_debug_record_line_number (cfg, ins, offset);
3961
3962                 switch (ins->opcode) {
3963                 case OP_BIGMUL:
3964                         amd64_mul_reg (code, ins->sreg2, TRUE);
3965                         break;
3966                 case OP_BIGMUL_UN:
3967                         amd64_mul_reg (code, ins->sreg2, FALSE);
3968                         break;
3969                 case OP_X86_SETEQ_MEMBASE:
3970                         amd64_set_membase (code, X86_CC_EQ, ins->inst_basereg, ins->inst_offset, TRUE);
3971                         break;
3972                 case OP_STOREI1_MEMBASE_IMM:
3973                         amd64_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 1);
3974                         break;
3975                 case OP_STOREI2_MEMBASE_IMM:
3976                         amd64_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 2);
3977                         break;
3978                 case OP_STOREI4_MEMBASE_IMM:
3979                         amd64_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 4);
3980                         break;
3981                 case OP_STOREI1_MEMBASE_REG:
3982                         amd64_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 1);
3983                         break;
3984                 case OP_STOREI2_MEMBASE_REG:
3985                         amd64_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 2);
3986                         break;
3987                 /* In AMD64 NaCl, pointers are 4 bytes, */
3988                 /*  so STORE_* != STOREI8_*. Likewise below. */
3989                 case OP_STORE_MEMBASE_REG:
3990                         amd64_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, sizeof(gpointer));
3991                         break;
3992                 case OP_STOREI8_MEMBASE_REG:
3993                         amd64_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 8);
3994                         break;
3995                 case OP_STOREI4_MEMBASE_REG:
3996                         amd64_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 4);
3997                         break;
3998                 case OP_STORE_MEMBASE_IMM:
3999 #ifndef __native_client_codegen__
4000                         /* In NaCl, this could be a PCONST type, which could */
4001                         /* mean a pointer type was copied directly into the  */
4002                         /* lower 32-bits of inst_imm, so for InvalidPtr==-1  */
4003                         /* the value would be 0x00000000FFFFFFFF which is    */
4004                         /* not proper for an imm32 unless you cast it.       */
4005                         g_assert (amd64_is_imm32 (ins->inst_imm));
4006 #endif
4007                         amd64_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, (gint32)ins->inst_imm, sizeof(gpointer));
4008                         break;
4009                 case OP_STOREI8_MEMBASE_IMM:
4010                         g_assert (amd64_is_imm32 (ins->inst_imm));
4011                         amd64_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 8);
4012                         break;
4013                 case OP_LOAD_MEM:
4014 #ifdef __mono_ilp32__
4015                         /* In ILP32, pointers are 4 bytes, so separate these */
4016                         /* cases, use literal 8 below where we really want 8 */
4017                         amd64_mov_reg_imm (code, ins->dreg, ins->inst_imm);
4018                         amd64_mov_reg_membase (code, ins->dreg, ins->dreg, 0, sizeof(gpointer));
4019                         break;
4020 #endif
4021                 case OP_LOADI8_MEM:
4022                         // FIXME: Decompose this earlier
4023                         if (amd64_is_imm32 (ins->inst_imm))
4024                                 amd64_mov_reg_mem (code, ins->dreg, ins->inst_imm, 8);
4025                         else {
4026                                 amd64_mov_reg_imm (code, ins->dreg, ins->inst_imm);
4027                                 amd64_mov_reg_membase (code, ins->dreg, ins->dreg, 0, 8);
4028                         }
4029                         break;
4030                 case OP_LOADI4_MEM:
4031                         amd64_mov_reg_imm (code, ins->dreg, ins->inst_imm);
4032                         amd64_movsxd_reg_membase (code, ins->dreg, ins->dreg, 0);
4033                         break;
4034                 case OP_LOADU4_MEM:
4035                         // FIXME: Decompose this earlier
4036                         if (amd64_is_imm32 (ins->inst_imm))
4037                                 amd64_mov_reg_mem (code, ins->dreg, ins->inst_imm, 4);
4038                         else {
4039                                 amd64_mov_reg_imm (code, ins->dreg, ins->inst_imm);
4040                                 amd64_mov_reg_membase (code, ins->dreg, ins->dreg, 0, 4);
4041                         }
4042                         break;
4043                 case OP_LOADU1_MEM:
4044                         amd64_mov_reg_imm (code, ins->dreg, ins->inst_imm);
4045                         amd64_widen_membase (code, ins->dreg, ins->dreg, 0, FALSE, FALSE);
4046                         break;
4047                 case OP_LOADU2_MEM:
4048                         /* For NaCl, pointers are 4 bytes, so separate these */
4049                         /* cases, use literal 8 below where we really want 8 */
4050                         amd64_mov_reg_imm (code, ins->dreg, ins->inst_imm);
4051                         amd64_widen_membase (code, ins->dreg, ins->dreg, 0, FALSE, TRUE);
4052                         break;
4053                 case OP_LOAD_MEMBASE:
4054                         g_assert (amd64_is_imm32 (ins->inst_offset));
4055                         amd64_mov_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, sizeof(gpointer));
4056                         break;
4057                 case OP_LOADI8_MEMBASE:
4058                         /* Use literal 8 instead of sizeof pointer or */
4059                         /* register, we really want 8 for this opcode */
4060                         g_assert (amd64_is_imm32 (ins->inst_offset));
4061                         amd64_mov_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, 8);
4062                         break;
4063                 case OP_LOADI4_MEMBASE:
4064                         amd64_movsxd_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset);
4065                         break;
4066                 case OP_LOADU4_MEMBASE:
4067                         amd64_mov_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, 4);
4068                         break;
4069                 case OP_LOADU1_MEMBASE:
4070                         /* The cpu zero extends the result into 64 bits */
4071                         amd64_widen_membase_size (code, ins->dreg, ins->inst_basereg, ins->inst_offset, FALSE, FALSE, 4);
4072                         break;
4073                 case OP_LOADI1_MEMBASE:
4074                         amd64_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, TRUE, FALSE);
4075                         break;
4076                 case OP_LOADU2_MEMBASE:
4077                         /* The cpu zero extends the result into 64 bits */
4078                         amd64_widen_membase_size (code, ins->dreg, ins->inst_basereg, ins->inst_offset, FALSE, TRUE, 4);
4079                         break;
4080                 case OP_LOADI2_MEMBASE:
4081                         amd64_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, TRUE, TRUE);
4082                         break;
4083                 case OP_AMD64_LOADI8_MEMINDEX:
4084                         amd64_mov_reg_memindex_size (code, ins->dreg, ins->inst_basereg, 0, ins->inst_indexreg, 0, 8);
4085                         break;
4086                 case OP_LCONV_TO_I1:
4087                 case OP_ICONV_TO_I1:
4088                 case OP_SEXT_I1:
4089                         amd64_widen_reg (code, ins->dreg, ins->sreg1, TRUE, FALSE);
4090                         break;
4091                 case OP_LCONV_TO_I2:
4092                 case OP_ICONV_TO_I2:
4093                 case OP_SEXT_I2:
4094                         amd64_widen_reg (code, ins->dreg, ins->sreg1, TRUE, TRUE);
4095                         break;
4096                 case OP_LCONV_TO_U1:
4097                 case OP_ICONV_TO_U1:
4098                         amd64_widen_reg (code, ins->dreg, ins->sreg1, FALSE, FALSE);
4099                         break;
4100                 case OP_LCONV_TO_U2:
4101                 case OP_ICONV_TO_U2:
4102                         amd64_widen_reg (code, ins->dreg, ins->sreg1, FALSE, TRUE);
4103                         break;
4104                 case OP_ZEXT_I4:
4105                         /* Clean out the upper word */
4106                         amd64_mov_reg_reg_size (code, ins->dreg, ins->sreg1, 4);
4107                         break;
4108                 case OP_SEXT_I4:
4109                         amd64_movsxd_reg_reg (code, ins->dreg, ins->sreg1);
4110                         break;
4111                 case OP_COMPARE:
4112                 case OP_LCOMPARE:
4113                         amd64_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2);
4114                         break;
4115                 case OP_COMPARE_IMM:
4116                 case OP_LCOMPARE_IMM:
4117                         g_assert (amd64_is_imm32 (ins->inst_imm));
4118                         amd64_alu_reg_imm (code, X86_CMP, ins->sreg1, ins->inst_imm);
4119                         break;
4120                 case OP_X86_COMPARE_REG_MEMBASE:
4121                         amd64_alu_reg_membase (code, X86_CMP, ins->sreg1, ins->sreg2, ins->inst_offset);
4122                         break;
4123                 case OP_X86_TEST_NULL:
4124                         amd64_test_reg_reg_size (code, ins->sreg1, ins->sreg1, 4);
4125                         break;
4126                 case OP_AMD64_TEST_NULL:
4127                         amd64_test_reg_reg (code, ins->sreg1, ins->sreg1);
4128                         break;
4129
4130                 case OP_X86_ADD_REG_MEMBASE:
4131                         amd64_alu_reg_membase_size (code, X86_ADD, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
4132                         break;
4133                 case OP_X86_SUB_REG_MEMBASE:
4134                         amd64_alu_reg_membase_size (code, X86_SUB, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
4135                         break;
4136                 case OP_X86_AND_REG_MEMBASE:
4137                         amd64_alu_reg_membase_size (code, X86_AND, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
4138                         break;
4139                 case OP_X86_OR_REG_MEMBASE:
4140                         amd64_alu_reg_membase_size (code, X86_OR, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
4141                         break;
4142                 case OP_X86_XOR_REG_MEMBASE:
4143                         amd64_alu_reg_membase_size (code, X86_XOR, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
4144                         break;
4145
4146                 case OP_X86_ADD_MEMBASE_IMM:
4147                         /* FIXME: Make a 64 version too */
4148                         amd64_alu_membase_imm_size (code, X86_ADD, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
4149                         break;
4150                 case OP_X86_SUB_MEMBASE_IMM:
4151                         g_assert (amd64_is_imm32 (ins->inst_imm));
4152                         amd64_alu_membase_imm_size (code, X86_SUB, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
4153                         break;
4154                 case OP_X86_AND_MEMBASE_IMM:
4155                         g_assert (amd64_is_imm32 (ins->inst_imm));
4156                         amd64_alu_membase_imm_size (code, X86_AND, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
4157                         break;
4158                 case OP_X86_OR_MEMBASE_IMM:
4159                         g_assert (amd64_is_imm32 (ins->inst_imm));
4160                         amd64_alu_membase_imm_size (code, X86_OR, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
4161                         break;
4162                 case OP_X86_XOR_MEMBASE_IMM:
4163                         g_assert (amd64_is_imm32 (ins->inst_imm));
4164                         amd64_alu_membase_imm_size (code, X86_XOR, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
4165                         break;
4166                 case OP_X86_ADD_MEMBASE_REG:
4167                         amd64_alu_membase_reg_size (code, X86_ADD, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
4168                         break;
4169                 case OP_X86_SUB_MEMBASE_REG:
4170                         amd64_alu_membase_reg_size (code, X86_SUB, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
4171                         break;
4172                 case OP_X86_AND_MEMBASE_REG:
4173                         amd64_alu_membase_reg_size (code, X86_AND, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
4174                         break;
4175                 case OP_X86_OR_MEMBASE_REG:
4176                         amd64_alu_membase_reg_size (code, X86_OR, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
4177                         break;
4178                 case OP_X86_XOR_MEMBASE_REG:
4179                         amd64_alu_membase_reg_size (code, X86_XOR, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
4180                         break;
4181                 case OP_X86_INC_MEMBASE:
4182                         amd64_inc_membase_size (code, ins->inst_basereg, ins->inst_offset, 4);
4183                         break;
4184                 case OP_X86_INC_REG:
4185                         amd64_inc_reg_size (code, ins->dreg, 4);
4186                         break;
4187                 case OP_X86_DEC_MEMBASE:
4188                         amd64_dec_membase_size (code, ins->inst_basereg, ins->inst_offset, 4);
4189                         break;
4190                 case OP_X86_DEC_REG:
4191                         amd64_dec_reg_size (code, ins->dreg, 4);
4192                         break;
4193                 case OP_X86_MUL_REG_MEMBASE:
4194                 case OP_X86_MUL_MEMBASE_REG:
4195                         amd64_imul_reg_membase_size (code, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
4196                         break;
4197                 case OP_AMD64_ICOMPARE_MEMBASE_REG:
4198                         amd64_alu_membase_reg_size (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
4199                         break;
4200                 case OP_AMD64_ICOMPARE_MEMBASE_IMM:
4201                         amd64_alu_membase_imm_size (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
4202                         break;
4203                 case OP_AMD64_COMPARE_MEMBASE_REG:
4204                         amd64_alu_membase_reg_size (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
4205                         break;
4206                 case OP_AMD64_COMPARE_MEMBASE_IMM:
4207                         g_assert (amd64_is_imm32 (ins->inst_imm));
4208                         amd64_alu_membase_imm_size (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
4209                         break;
4210                 case OP_X86_COMPARE_MEMBASE8_IMM:
4211                         amd64_alu_membase8_imm_size (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
4212                         break;
4213                 case OP_AMD64_ICOMPARE_REG_MEMBASE:
4214                         amd64_alu_reg_membase_size (code, X86_CMP, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
4215                         break;
4216                 case OP_AMD64_COMPARE_REG_MEMBASE:
4217                         amd64_alu_reg_membase_size (code, X86_CMP, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
4218                         break;
4219
4220                 case OP_AMD64_ADD_REG_MEMBASE:
4221                         amd64_alu_reg_membase_size (code, X86_ADD, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
4222                         break;
4223                 case OP_AMD64_SUB_REG_MEMBASE:
4224                         amd64_alu_reg_membase_size (code, X86_SUB, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
4225                         break;
4226                 case OP_AMD64_AND_REG_MEMBASE:
4227                         amd64_alu_reg_membase_size (code, X86_AND, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
4228                         break;
4229                 case OP_AMD64_OR_REG_MEMBASE:
4230                         amd64_alu_reg_membase_size (code, X86_OR, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
4231                         break;
4232                 case OP_AMD64_XOR_REG_MEMBASE:
4233                         amd64_alu_reg_membase_size (code, X86_XOR, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
4234                         break;
4235
4236                 case OP_AMD64_ADD_MEMBASE_REG:
4237                         amd64_alu_membase_reg_size (code, X86_ADD, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
4238                         break;
4239                 case OP_AMD64_SUB_MEMBASE_REG:
4240                         amd64_alu_membase_reg_size (code, X86_SUB, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
4241                         break;
4242                 case OP_AMD64_AND_MEMBASE_REG:
4243                         amd64_alu_membase_reg_size (code, X86_AND, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
4244                         break;
4245                 case OP_AMD64_OR_MEMBASE_REG:
4246                         amd64_alu_membase_reg_size (code, X86_OR, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
4247                         break;
4248                 case OP_AMD64_XOR_MEMBASE_REG:
4249                         amd64_alu_membase_reg_size (code, X86_XOR, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
4250                         break;
4251
4252                 case OP_AMD64_ADD_MEMBASE_IMM:
4253                         g_assert (amd64_is_imm32 (ins->inst_imm));
4254                         amd64_alu_membase_imm_size (code, X86_ADD, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
4255                         break;
4256                 case OP_AMD64_SUB_MEMBASE_IMM:
4257                         g_assert (amd64_is_imm32 (ins->inst_imm));
4258                         amd64_alu_membase_imm_size (code, X86_SUB, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
4259                         break;
4260                 case OP_AMD64_AND_MEMBASE_IMM:
4261                         g_assert (amd64_is_imm32 (ins->inst_imm));
4262                         amd64_alu_membase_imm_size (code, X86_AND, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
4263                         break;
4264                 case OP_AMD64_OR_MEMBASE_IMM:
4265                         g_assert (amd64_is_imm32 (ins->inst_imm));
4266                         amd64_alu_membase_imm_size (code, X86_OR, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
4267                         break;
4268                 case OP_AMD64_XOR_MEMBASE_IMM:
4269                         g_assert (amd64_is_imm32 (ins->inst_imm));
4270                         amd64_alu_membase_imm_size (code, X86_XOR, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
4271                         break;
4272
4273                 case OP_BREAK:
4274                         amd64_breakpoint (code);
4275                         break;
4276                 case OP_RELAXED_NOP:
4277                         x86_prefix (code, X86_REP_PREFIX);
4278                         x86_nop (code);
4279                         break;
4280                 case OP_HARD_NOP:
4281                         x86_nop (code);
4282                         break;
4283                 case OP_NOP:
4284                 case OP_DUMMY_USE:
4285                 case OP_DUMMY_STORE:
4286                 case OP_NOT_REACHED:
4287                 case OP_NOT_NULL:
4288                         break;
4289                 case OP_SEQ_POINT: {
4290                         int i;
4291
4292                         /* 
4293                          * Read from the single stepping trigger page. This will cause a
4294                          * SIGSEGV when single stepping is enabled.
4295                          * We do this _before_ the breakpoint, so single stepping after
4296                          * a breakpoint is hit will step to the next IL offset.
4297                          */
4298                         if (ins->flags & MONO_INST_SINGLE_STEP_LOC) {
4299                                 MonoInst *var = cfg->arch.ss_trigger_page_var;
4300
4301                                 amd64_mov_reg_membase (code, AMD64_R11, var->inst_basereg, var->inst_offset, 8);
4302                                 amd64_alu_membase_imm_size (code, X86_CMP, AMD64_R11, 0, 0, 4);
4303                         }
4304
4305                         /* 
4306                          * This is the address which is saved in seq points, 
4307                          */
4308                         mono_add_seq_point (cfg, bb, ins, code - cfg->native_code);
4309
4310                         if (cfg->compile_aot) {
4311                                 guint32 offset = code - cfg->native_code;
4312                                 guint32 val;
4313                                 MonoInst *info_var = cfg->arch.seq_point_info_var;
4314
4315                                 /* Load info var */
4316                                 amd64_mov_reg_membase (code, AMD64_R11, info_var->inst_basereg, info_var->inst_offset, 8);
4317                                 val = ((offset) * sizeof (guint8*)) + G_STRUCT_OFFSET (SeqPointInfo, bp_addrs);
4318                                 /* Load the info->bp_addrs [offset], which is either a valid address or the address of a trigger page */
4319                                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, val, 8);
4320                                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 0, 8);
4321                         } else {
4322                                 /* 
4323                                  * A placeholder for a possible breakpoint inserted by
4324                                  * mono_arch_set_breakpoint ().
4325                                  */
4326                                 for (i = 0; i < breakpoint_size; ++i)
4327                                         x86_nop (code);
4328                         }
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
6823         /* compute max_length in order to use short forward jumps */
6824         max_epilog_size = get_max_epilog_size (cfg);
6825         if (cfg->opt & MONO_OPT_BRANCH) {
6826                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
6827                         MonoInst *ins;
6828                         int max_length = 0;
6829
6830                         if (cfg->prof_options & MONO_PROFILE_COVERAGE)
6831                                 max_length += 6;
6832                         /* max alignment for loops */
6833                         if ((cfg->opt & MONO_OPT_LOOP) && bb_is_loop_start (bb))
6834                                 max_length += LOOP_ALIGNMENT;
6835 #ifdef __native_client_codegen__
6836                         /* max alignment for native client */
6837                         max_length += kNaClAlignment;
6838 #endif
6839
6840                         MONO_BB_FOR_EACH_INS (bb, ins) {
6841 #ifdef __native_client_codegen__
6842                                 {
6843                                         int space_in_block = kNaClAlignment -
6844                                                 ((max_length + cfg->code_len) & kNaClAlignmentMask);
6845                                         int max_len = ((guint8 *)ins_get_spec (ins->opcode))[MONO_INST_LEN];
6846                                         if (space_in_block < max_len && max_len < kNaClAlignment) {
6847                                                 max_length += space_in_block;
6848                                         }
6849                                 }
6850 #endif  /*__native_client_codegen__*/
6851                                 max_length += ((guint8 *)ins_get_spec (ins->opcode))[MONO_INST_LEN];
6852                         }
6853
6854                         /* Take prolog and epilog instrumentation into account */
6855                         if (bb == cfg->bb_entry || bb == cfg->bb_exit)
6856                                 max_length += max_epilog_size;
6857                         
6858                         bb->max_length = max_length;
6859                 }
6860         }
6861
6862         sig = mono_method_signature (method);
6863         pos = 0;
6864
6865         cinfo = cfg->arch.cinfo;
6866
6867         if (sig->ret->type != MONO_TYPE_VOID) {
6868                 /* Save volatile arguments to the stack */
6869                 if (cfg->vret_addr && (cfg->vret_addr->opcode != OP_REGVAR))
6870                         amd64_mov_membase_reg (code, cfg->vret_addr->inst_basereg, cfg->vret_addr->inst_offset, cinfo->ret.reg, 8);
6871         }
6872
6873         /* Keep this in sync with emit_load_volatile_arguments */
6874         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6875                 ArgInfo *ainfo = cinfo->args + i;
6876                 gint32 stack_offset;
6877                 MonoType *arg_type;
6878
6879                 ins = cfg->args [i];
6880
6881                 if ((ins->flags & MONO_INST_IS_DEAD) && !trace)
6882                         /* Unused arguments */
6883                         continue;
6884
6885                 if (sig->hasthis && (i == 0))
6886                         arg_type = &mono_defaults.object_class->byval_arg;
6887                 else
6888                         arg_type = sig->params [i - sig->hasthis];
6889
6890                 stack_offset = ainfo->offset + ARGS_OFFSET;
6891
6892                 if (cfg->globalra) {
6893                         /* All the other moves are done by the register allocator */
6894                         switch (ainfo->storage) {
6895                         case ArgInFloatSSEReg:
6896                                 amd64_sse_cvtss2sd_reg_reg (code, ainfo->reg, ainfo->reg);
6897                                 break;
6898                         case ArgValuetypeInReg:
6899                                 for (quad = 0; quad < 2; quad ++) {
6900                                         switch (ainfo->pair_storage [quad]) {
6901                                         case ArgInIReg:
6902                                                 amd64_mov_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof(mgreg_t)), ainfo->pair_regs [quad], sizeof(mgreg_t));
6903                                                 break;
6904                                         case ArgInFloatSSEReg:
6905                                                 amd64_movss_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof(mgreg_t)), ainfo->pair_regs [quad]);
6906                                                 break;
6907                                         case ArgInDoubleSSEReg:
6908                                                 amd64_movsd_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof(mgreg_t)), ainfo->pair_regs [quad]);
6909                                                 break;
6910                                         case ArgNone:
6911                                                 break;
6912                                         default:
6913                                                 g_assert_not_reached ();
6914                                         }
6915                                 }
6916                                 break;
6917                         default:
6918                                 break;
6919                         }
6920
6921                         continue;
6922                 }
6923
6924                 /* Save volatile arguments to the stack */
6925                 if (ins->opcode != OP_REGVAR) {
6926                         switch (ainfo->storage) {
6927                         case ArgInIReg: {
6928                                 guint32 size = 8;
6929
6930                                 /* FIXME: I1 etc */
6931                                 /*
6932                                 if (stack_offset & 0x1)
6933                                         size = 1;
6934                                 else if (stack_offset & 0x2)
6935                                         size = 2;
6936                                 else if (stack_offset & 0x4)
6937                                         size = 4;
6938                                 else
6939                                         size = 8;
6940                                 */
6941                                 amd64_mov_membase_reg (code, ins->inst_basereg, ins->inst_offset, ainfo->reg, size);
6942                                 break;
6943                         }
6944                         case ArgInFloatSSEReg:
6945                                 amd64_movss_membase_reg (code, ins->inst_basereg, ins->inst_offset, ainfo->reg);
6946                                 break;
6947                         case ArgInDoubleSSEReg:
6948                                 amd64_movsd_membase_reg (code, ins->inst_basereg, ins->inst_offset, ainfo->reg);
6949                                 break;
6950                         case ArgValuetypeInReg:
6951                                 for (quad = 0; quad < 2; quad ++) {
6952                                         switch (ainfo->pair_storage [quad]) {
6953                                         case ArgInIReg:
6954                                                 amd64_mov_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof(mgreg_t)), ainfo->pair_regs [quad], sizeof(mgreg_t));
6955                                                 break;
6956                                         case ArgInFloatSSEReg:
6957                                                 amd64_movss_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof(mgreg_t)), ainfo->pair_regs [quad]);
6958                                                 break;
6959                                         case ArgInDoubleSSEReg:
6960                                                 amd64_movsd_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof(mgreg_t)), ainfo->pair_regs [quad]);
6961                                                 break;
6962                                         case ArgNone:
6963                                                 break;
6964                                         default:
6965                                                 g_assert_not_reached ();
6966                                         }
6967                                 }
6968                                 break;
6969                         case ArgValuetypeAddrInIReg:
6970                                 if (ainfo->pair_storage [0] == ArgInIReg)
6971                                         amd64_mov_membase_reg (code, ins->inst_left->inst_basereg, ins->inst_left->inst_offset, ainfo->pair_regs [0],  sizeof (gpointer));
6972                                 break;
6973                         default:
6974                                 break;
6975                         }
6976                 } else {
6977                         /* Argument allocated to (non-volatile) register */
6978                         switch (ainfo->storage) {
6979                         case ArgInIReg:
6980                                 amd64_mov_reg_reg (code, ins->dreg, ainfo->reg, 8);
6981                                 break;
6982                         case ArgOnStack:
6983                                 amd64_mov_reg_membase (code, ins->dreg, AMD64_RBP, ARGS_OFFSET + ainfo->offset, 8);
6984                                 break;
6985                         default:
6986                                 g_assert_not_reached ();
6987                         }
6988                 }
6989         }
6990
6991         /* Might need to attach the thread to the JIT  or change the domain for the callback */
6992         if (method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
6993                 guint64 domain = (guint64)cfg->domain;
6994
6995                 args_clobbered = TRUE;
6996
6997                 /* 
6998                  * The call might clobber argument registers, but they are already
6999                  * saved to the stack/global regs.
7000                  */
7001                 if (appdomain_tls_offset != -1 && lmf_tls_offset != -1) {
7002                         guint8 *buf, *no_domain_branch;
7003
7004                         code = mono_amd64_emit_tls_get (code, AMD64_RAX, appdomain_tls_offset);
7005                         if (cfg->compile_aot) {
7006                                 /* AOT code is only used in the root domain */
7007                                 amd64_mov_reg_imm (code, AMD64_ARG_REG1, 0);
7008                         } else {
7009                                 if ((domain >> 32) == 0)
7010                                         amd64_mov_reg_imm_size (code, AMD64_ARG_REG1, domain, 4);
7011                                 else
7012                                         amd64_mov_reg_imm_size (code, AMD64_ARG_REG1, domain, 8);
7013                         }
7014                         amd64_alu_reg_reg (code, X86_CMP, AMD64_RAX, AMD64_ARG_REG1);
7015                         no_domain_branch = code;
7016                         x86_branch8 (code, X86_CC_NE, 0, 0);
7017                         code = mono_amd64_emit_tls_get ( code, AMD64_RAX, lmf_addr_tls_offset);
7018                         amd64_test_reg_reg (code, AMD64_RAX, AMD64_RAX);
7019                         buf = code;
7020                         x86_branch8 (code, X86_CC_NE, 0, 0);
7021                         amd64_patch (no_domain_branch, code);
7022                         code = emit_call (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD, 
7023                                           (gpointer)"mono_jit_thread_attach", TRUE);
7024                         amd64_patch (buf, code);
7025 #ifdef HOST_WIN32
7026                         /* The TLS key actually contains a pointer to the MonoJitTlsData structure */
7027                         /* FIXME: Add a separate key for LMF to avoid this */
7028                         amd64_alu_reg_imm (code, X86_ADD, AMD64_RAX, G_STRUCT_OFFSET (MonoJitTlsData, lmf));
7029 #endif
7030                 } else {
7031                         g_assert (!cfg->compile_aot);
7032                         if (cfg->compile_aot) {
7033                                 /* AOT code is only used in the root domain */
7034                                 amd64_mov_reg_imm (code, AMD64_ARG_REG1, 0);
7035                         } else {
7036                                 if ((domain >> 32) == 0)
7037                                         amd64_mov_reg_imm_size (code, AMD64_ARG_REG1, domain, 4);
7038                                 else
7039                                         amd64_mov_reg_imm_size (code, AMD64_ARG_REG1, domain, 8);
7040                         }
7041                         code = emit_call (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD,
7042                                           (gpointer)"mono_jit_thread_attach", TRUE);
7043                 }
7044         }
7045
7046         if (method->save_lmf) {
7047                 code = emit_save_lmf (cfg, code, lmf_var->inst_offset, &args_clobbered);
7048         }
7049
7050         if (trace) {
7051                 args_clobbered = TRUE;
7052                 code = mono_arch_instrument_prolog (cfg, mono_trace_enter_method, code, TRUE);
7053         }
7054
7055         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
7056                 args_clobbered = TRUE;
7057
7058         /*
7059          * Optimize the common case of the first bblock making a call with the same
7060          * arguments as the method. This works because the arguments are still in their
7061          * original argument registers.
7062          * FIXME: Generalize this
7063          */
7064         if (!args_clobbered) {
7065                 MonoBasicBlock *first_bb = cfg->bb_entry;
7066                 MonoInst *next;
7067
7068                 next = mono_bb_first_ins (first_bb);
7069                 if (!next && first_bb->next_bb) {
7070                         first_bb = first_bb->next_bb;
7071                         next = mono_bb_first_ins (first_bb);
7072                 }
7073
7074                 if (first_bb->in_count > 1)
7075                         next = NULL;
7076
7077                 for (i = 0; next && i < sig->param_count + sig->hasthis; ++i) {
7078                         ArgInfo *ainfo = cinfo->args + i;
7079                         gboolean match = FALSE;
7080                         
7081                         ins = cfg->args [i];
7082                         if (ins->opcode != OP_REGVAR) {
7083                                 switch (ainfo->storage) {
7084                                 case ArgInIReg: {
7085                                         if (((next->opcode == OP_LOAD_MEMBASE) || (next->opcode == OP_LOADI4_MEMBASE)) && next->inst_basereg == ins->inst_basereg && next->inst_offset == ins->inst_offset) {
7086                                                 if (next->dreg == ainfo->reg) {
7087                                                         NULLIFY_INS (next);
7088                                                         match = TRUE;
7089                                                 } else {
7090                                                         next->opcode = OP_MOVE;
7091                                                         next->sreg1 = ainfo->reg;
7092                                                         /* Only continue if the instruction doesn't change argument regs */
7093                                                         if (next->dreg == ainfo->reg || next->dreg == AMD64_RAX)
7094                                                                 match = TRUE;
7095                                                 }
7096                                         }
7097                                         break;
7098                                 }
7099                                 default:
7100                                         break;
7101                                 }
7102                         } else {
7103                                 /* Argument allocated to (non-volatile) register */
7104                                 switch (ainfo->storage) {
7105                                 case ArgInIReg:
7106                                         if (next->opcode == OP_MOVE && next->sreg1 == ins->dreg && next->dreg == ainfo->reg) {
7107                                                 NULLIFY_INS (next);
7108                                                 match = TRUE;
7109                                         }
7110                                         break;
7111                                 default:
7112                                         break;
7113                                 }
7114                         }
7115
7116                         if (match) {
7117                                 next = next->next;
7118                                 //next = mono_inst_list_next (&next->node, &first_bb->ins_list);
7119                                 if (!next)
7120                                         break;
7121                         }
7122                 }
7123         }
7124
7125         if (cfg->gen_seq_points) {
7126                 MonoInst *info_var = cfg->arch.seq_point_info_var;
7127
7128                 /* Initialize seq_point_info_var */
7129                 if (cfg->compile_aot) {
7130                         /* Initialize the variable from a GOT slot */
7131                         /* Same as OP_AOTCONST */
7132                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_SEQ_POINT_INFO, cfg->method);
7133                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, sizeof(gpointer));
7134                         g_assert (info_var->opcode == OP_REGOFFSET);
7135                         amd64_mov_membase_reg (code, info_var->inst_basereg, info_var->inst_offset, AMD64_R11, 8);
7136                 }
7137
7138                 /* Initialize ss_trigger_page_var */
7139                 ins = cfg->arch.ss_trigger_page_var;
7140
7141                 g_assert (ins->opcode == OP_REGOFFSET);
7142
7143                 if (cfg->compile_aot) {
7144                         amd64_mov_reg_membase (code, AMD64_R11, info_var->inst_basereg, info_var->inst_offset, 8);
7145                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, G_STRUCT_OFFSET (SeqPointInfo, ss_trigger_page), 8);
7146                 } else {
7147                         amd64_mov_reg_imm (code, AMD64_R11, (guint64)ss_trigger_page);
7148                 }
7149                 amd64_mov_membase_reg (code, ins->inst_basereg, ins->inst_offset, AMD64_R11, 8);
7150         }
7151
7152         cfg->code_len = code - cfg->native_code;
7153
7154         g_assert (cfg->code_len < cfg->code_size);
7155
7156         return code;
7157 }
7158
7159 void
7160 mono_arch_emit_epilog (MonoCompile *cfg)
7161 {
7162         MonoMethod *method = cfg->method;
7163         int quad, pos, i;
7164         guint8 *code;
7165         int max_epilog_size;
7166         CallInfo *cinfo;
7167         gint32 lmf_offset = cfg->arch.lmf_var ? ((MonoInst*)cfg->arch.lmf_var)->inst_offset : -1;
7168         
7169         max_epilog_size = get_max_epilog_size (cfg);
7170
7171         while (cfg->code_len + max_epilog_size > (cfg->code_size - 16)) {
7172                 cfg->code_size *= 2;
7173                 cfg->native_code = mono_realloc_native_code (cfg);
7174                 cfg->stat_code_reallocs++;
7175         }
7176
7177         code = cfg->native_code + cfg->code_len;
7178
7179         if (mono_jit_trace_calls != NULL && mono_trace_eval (method))
7180                 code = mono_arch_instrument_epilog (cfg, mono_trace_leave_method, code, TRUE);
7181
7182         /* the code restoring the registers must be kept in sync with OP_JMP */
7183         pos = 0;
7184         
7185         if (method->save_lmf) {
7186                 /* check if we need to restore protection of the stack after a stack overflow */
7187                 if (mono_get_jit_tls_offset () != -1) {
7188                         guint8 *patch;
7189                         code = mono_amd64_emit_tls_get (code, AMD64_RCX, mono_get_jit_tls_offset ());
7190                         /* we load the value in a separate instruction: this mechanism may be
7191                          * used later as a safer way to do thread interruption
7192                          */
7193                         amd64_mov_reg_membase (code, AMD64_RCX, AMD64_RCX, G_STRUCT_OFFSET (MonoJitTlsData, restore_stack_prot), 8);
7194                         x86_alu_reg_imm (code, X86_CMP, X86_ECX, 0);
7195                         patch = code;
7196                         x86_branch8 (code, X86_CC_Z, 0, FALSE);
7197                         /* note that the call trampoline will preserve eax/edx */
7198                         x86_call_reg (code, X86_ECX);
7199                         x86_patch (patch, code);
7200                 } else {
7201                         /* FIXME: maybe save the jit tls in the prolog */
7202                 }
7203
7204                 code = emit_restore_lmf (cfg, code, lmf_offset);
7205
7206                 /* Restore caller saved regs */
7207                 if (cfg->used_int_regs & (1 << AMD64_RBP)) {
7208                         amd64_mov_reg_membase (code, AMD64_RBP, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbp), 8);
7209                 }
7210                 if (cfg->used_int_regs & (1 << AMD64_RBX)) {
7211                         amd64_mov_reg_membase (code, AMD64_RBX, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbx), 8);
7212                 }
7213                 if (cfg->used_int_regs & (1 << AMD64_R12)) {
7214                         amd64_mov_reg_membase (code, AMD64_R12, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r12), 8);
7215                 }
7216                 if (cfg->used_int_regs & (1 << AMD64_R13)) {
7217                         amd64_mov_reg_membase (code, AMD64_R13, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r13), 8);
7218                 }
7219                 if (cfg->used_int_regs & (1 << AMD64_R14)) {
7220                         amd64_mov_reg_membase (code, AMD64_R14, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r14), 8);
7221                 }
7222                 if (cfg->used_int_regs & (1 << AMD64_R15)) {
7223 #if defined(__default_codegen__)
7224                         amd64_mov_reg_membase (code, AMD64_R15, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r15), 8);
7225 #elif defined(__native_client_codegen__)
7226                         g_assert_not_reached();
7227 #endif
7228                 }
7229 #ifdef HOST_WIN32
7230                 if (cfg->used_int_regs & (1 << AMD64_RDI)) {
7231                         amd64_mov_reg_membase (code, AMD64_RDI, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rdi), 8);
7232                 }
7233                 if (cfg->used_int_regs & (1 << AMD64_RSI)) {
7234                         amd64_mov_reg_membase (code, AMD64_RSI, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rsi), 8);
7235                 }
7236 #endif
7237         } else {
7238
7239                 if (cfg->arch.omit_fp) {
7240                         gint32 save_area_offset = cfg->arch.reg_save_area_offset;
7241
7242                         for (i = 0; i < AMD64_NREG; ++i)
7243                                 if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
7244                                         amd64_mov_reg_membase (code, i, AMD64_RSP, save_area_offset, 8);
7245                                         save_area_offset += 8;
7246                                 }
7247                 }
7248                 else {
7249                         for (i = 0; i < AMD64_NREG; ++i)
7250                                 if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i)))
7251                                         pos -= sizeof(mgreg_t);
7252
7253                         if (pos) {
7254                                 if (pos == - sizeof(mgreg_t)) {
7255                                         /* Only one register, so avoid lea */
7256                                         for (i = AMD64_NREG - 1; i > 0; --i)
7257                                                 if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
7258                                                         amd64_mov_reg_membase (code, i, AMD64_RBP, pos, 8);
7259                                                 }
7260                                 }
7261                                 else {
7262                                         amd64_lea_membase (code, AMD64_RSP, AMD64_RBP, pos);
7263
7264                                         /* Pop registers in reverse order */
7265                                         for (i = AMD64_NREG - 1; i > 0; --i)
7266                                                 if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
7267                                                         amd64_pop_reg (code, i);
7268                                                 }
7269                                 }
7270                         }
7271                 }
7272         }
7273
7274         /* Load returned vtypes into registers if needed */
7275         cinfo = cfg->arch.cinfo;
7276         if (cinfo->ret.storage == ArgValuetypeInReg) {
7277                 ArgInfo *ainfo = &cinfo->ret;
7278                 MonoInst *inst = cfg->ret;
7279
7280                 for (quad = 0; quad < 2; quad ++) {
7281                         switch (ainfo->pair_storage [quad]) {
7282                         case ArgInIReg:
7283                                 amd64_mov_reg_membase (code, ainfo->pair_regs [quad], inst->inst_basereg, inst->inst_offset + (quad * sizeof(mgreg_t)), sizeof(mgreg_t));
7284                                 break;
7285                         case ArgInFloatSSEReg:
7286                                 amd64_movss_reg_membase (code, ainfo->pair_regs [quad], inst->inst_basereg, inst->inst_offset + (quad * sizeof(mgreg_t)));
7287                                 break;
7288                         case ArgInDoubleSSEReg:
7289                                 amd64_movsd_reg_membase (code, ainfo->pair_regs [quad], inst->inst_basereg, inst->inst_offset + (quad * sizeof(mgreg_t)));
7290                                 break;
7291                         case ArgNone:
7292                                 break;
7293                         default:
7294                                 g_assert_not_reached ();
7295                         }
7296                 }
7297         }
7298
7299         if (cfg->arch.omit_fp) {
7300                 if (cfg->arch.stack_alloc_size)
7301                         amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, cfg->arch.stack_alloc_size);
7302         } else {
7303                 amd64_leave (code);
7304         }
7305         async_exc_point (code);
7306         amd64_ret (code);
7307
7308         cfg->code_len = code - cfg->native_code;
7309
7310         g_assert (cfg->code_len < cfg->code_size);
7311 }
7312
7313 void
7314 mono_arch_emit_exceptions (MonoCompile *cfg)
7315 {
7316         MonoJumpInfo *patch_info;
7317         int nthrows, i;
7318         guint8 *code;
7319         MonoClass *exc_classes [16];
7320         guint8 *exc_throw_start [16], *exc_throw_end [16];
7321         guint32 code_size = 0;
7322
7323         /* Compute needed space */
7324         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7325                 if (patch_info->type == MONO_PATCH_INFO_EXC)
7326                         code_size += 40;
7327                 if (patch_info->type == MONO_PATCH_INFO_R8)
7328                         code_size += 8 + 15; /* sizeof (double) + alignment */
7329                 if (patch_info->type == MONO_PATCH_INFO_R4)
7330                         code_size += 4 + 15; /* sizeof (float) + alignment */
7331                 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR)
7332                         code_size += 8 + 7; /*sizeof (void*) + alignment */
7333         }
7334
7335 #ifdef __native_client_codegen__
7336         /* Give us extra room on Native Client.  This could be   */
7337         /* more carefully calculated, but bundle alignment makes */
7338         /* it much trickier, so *2 like other places is good.    */
7339         code_size *= 2;
7340 #endif
7341
7342         while (cfg->code_len + code_size > (cfg->code_size - 16)) {
7343                 cfg->code_size *= 2;
7344                 cfg->native_code = mono_realloc_native_code (cfg);
7345                 cfg->stat_code_reallocs++;
7346         }
7347
7348         code = cfg->native_code + cfg->code_len;
7349
7350         /* add code to raise exceptions */
7351         nthrows = 0;
7352         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7353                 switch (patch_info->type) {
7354                 case MONO_PATCH_INFO_EXC: {
7355                         MonoClass *exc_class;
7356                         guint8 *buf, *buf2;
7357                         guint32 throw_ip;
7358
7359                         amd64_patch (patch_info->ip.i + cfg->native_code, code);
7360
7361                         exc_class = mono_class_from_name (mono_defaults.corlib, "System", patch_info->data.name);
7362                         g_assert (exc_class);
7363                         throw_ip = patch_info->ip.i;
7364
7365                         //x86_breakpoint (code);
7366                         /* Find a throw sequence for the same exception class */
7367                         for (i = 0; i < nthrows; ++i)
7368                                 if (exc_classes [i] == exc_class)
7369                                         break;
7370                         if (i < nthrows) {
7371                                 amd64_mov_reg_imm (code, AMD64_ARG_REG2, (exc_throw_end [i] - cfg->native_code) - throw_ip);
7372                                 x86_jump_code (code, exc_throw_start [i]);
7373                                 patch_info->type = MONO_PATCH_INFO_NONE;
7374                         }
7375                         else {
7376                                 buf = code;
7377                                 amd64_mov_reg_imm_size (code, AMD64_ARG_REG2, 0xf0f0f0f0, 4);
7378                                 buf2 = code;
7379
7380                                 if (nthrows < 16) {
7381                                         exc_classes [nthrows] = exc_class;
7382                                         exc_throw_start [nthrows] = code;
7383                                 }
7384                                 amd64_mov_reg_imm (code, AMD64_ARG_REG1, exc_class->type_token - MONO_TOKEN_TYPE_DEF);
7385
7386                                 patch_info->type = MONO_PATCH_INFO_NONE;
7387
7388                                 code = emit_call_body (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD, "mono_arch_throw_corlib_exception");
7389
7390                                 amd64_mov_reg_imm (buf, AMD64_ARG_REG2, (code - cfg->native_code) - throw_ip);
7391                                 while (buf < buf2)
7392                                         x86_nop (buf);
7393
7394                                 if (nthrows < 16) {
7395                                         exc_throw_end [nthrows] = code;
7396                                         nthrows ++;
7397                                 }
7398                         }
7399                         break;
7400                 }
7401                 default:
7402                         /* do nothing */
7403                         break;
7404                 }
7405                 g_assert(code < cfg->native_code + cfg->code_size);
7406         }
7407
7408         /* Handle relocations with RIP relative addressing */
7409         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7410                 gboolean remove = FALSE;
7411                 guint8 *orig_code = code;
7412
7413                 switch (patch_info->type) {
7414                 case MONO_PATCH_INFO_R8:
7415                 case MONO_PATCH_INFO_R4: {
7416                         guint8 *pos, *patch_pos;
7417                         guint32 target_pos;
7418
7419                         /* The SSE opcodes require a 16 byte alignment */
7420 #if defined(__default_codegen__)
7421                         code = (guint8*)ALIGN_TO (code, 16);
7422 #elif defined(__native_client_codegen__)
7423                         {
7424                                 /* Pad this out with HLT instructions  */
7425                                 /* or we can get garbage bytes emitted */
7426                                 /* which will fail validation          */
7427                                 guint8 *aligned_code;
7428                                 /* extra align to make room for  */
7429                                 /* mov/push below                      */
7430                                 int extra_align = patch_info->type == MONO_PATCH_INFO_R8 ? 2 : 1;
7431                                 aligned_code = (guint8*)ALIGN_TO (code + extra_align, 16);
7432                                 /* The technique of hiding data in an  */
7433                                 /* instruction has a problem here: we  */
7434                                 /* need the data aligned to a 16-byte  */
7435                                 /* boundary but the instruction cannot */
7436                                 /* cross the bundle boundary. so only  */
7437                                 /* odd multiples of 16 can be used     */
7438                                 if ((intptr_t)aligned_code % kNaClAlignment == 0) {
7439                                         aligned_code += 16;
7440                                 }
7441                                 while (code < aligned_code) {
7442                                         *(code++) = 0xf4; /* hlt */
7443                                 }
7444                         }       
7445 #endif
7446
7447                         pos = cfg->native_code + patch_info->ip.i;
7448                         if (IS_REX (pos [1])) {
7449                                 patch_pos = pos + 5;
7450                                 target_pos = code - pos - 9;
7451                         }
7452                         else {
7453                                 patch_pos = pos + 4;
7454                                 target_pos = code - pos - 8;
7455                         }
7456
7457                         if (patch_info->type == MONO_PATCH_INFO_R8) {
7458 #ifdef __native_client_codegen__
7459                                 /* Hide 64-bit data in a         */
7460                                 /* "mov imm64, r11" instruction. */
7461                                 /* write it before the start of  */
7462                                 /* the data*/
7463                                 *(code-2) = 0x49; /* prefix      */
7464                                 *(code-1) = 0xbb; /* mov X, %r11 */
7465 #endif
7466                                 *(double*)code = *(double*)patch_info->data.target;
7467                                 code += sizeof (double);
7468                         } else {
7469 #ifdef __native_client_codegen__
7470                                 /* Hide 32-bit data in a        */
7471                                 /* "push imm32" instruction.    */
7472                                 *(code-1) = 0x68; /* push */
7473 #endif
7474                                 *(float*)code = *(float*)patch_info->data.target;
7475                                 code += sizeof (float);
7476                         }
7477
7478                         *(guint32*)(patch_pos) = target_pos;
7479
7480                         remove = TRUE;
7481                         break;
7482                 }
7483                 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR: {
7484                         guint8 *pos;
7485
7486                         if (cfg->compile_aot)
7487                                 continue;
7488
7489                         /*loading is faster against aligned addresses.*/
7490                         code = (guint8*)ALIGN_TO (code, 8);
7491                         memset (orig_code, 0, code - orig_code);
7492
7493                         pos = cfg->native_code + patch_info->ip.i;
7494
7495                         /*alu_op [rex] modr/m imm32 - 7 or 8 bytes */
7496                         if (IS_REX (pos [1]))
7497                                 *(guint32*)(pos + 4) = (guint8*)code - pos - 8;
7498                         else
7499                                 *(guint32*)(pos + 3) = (guint8*)code - pos - 7;
7500
7501                         *(gpointer*)code = (gpointer)patch_info->data.target;
7502                         code += sizeof (gpointer);
7503
7504                         remove = TRUE;
7505                         break;
7506                 }
7507                 default:
7508                         break;
7509                 }
7510
7511                 if (remove) {
7512                         if (patch_info == cfg->patch_info)
7513                                 cfg->patch_info = patch_info->next;
7514                         else {
7515                                 MonoJumpInfo *tmp;
7516
7517                                 for (tmp = cfg->patch_info; tmp->next != patch_info; tmp = tmp->next)
7518                                         ;
7519                                 tmp->next = patch_info->next;
7520                         }
7521                 }
7522                 g_assert (code < cfg->native_code + cfg->code_size);
7523         }
7524
7525         cfg->code_len = code - cfg->native_code;
7526
7527         g_assert (cfg->code_len < cfg->code_size);
7528
7529 }
7530
7531 #endif /* DISABLE_JIT */
7532
7533 void*
7534 mono_arch_instrument_prolog (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments)
7535 {
7536         guchar *code = p;
7537         CallInfo *cinfo = NULL;
7538         MonoMethodSignature *sig;
7539         MonoInst *inst;
7540         int i, n, stack_area = 0;
7541
7542         /* Keep this in sync with mono_arch_get_argument_info */
7543
7544         if (enable_arguments) {
7545                 /* Allocate a new area on the stack and save arguments there */
7546                 sig = mono_method_signature (cfg->method);
7547
7548                 cinfo = get_call_info (cfg->generic_sharing_context, cfg->mempool, sig);
7549
7550                 n = sig->param_count + sig->hasthis;
7551
7552                 stack_area = ALIGN_TO (n * 8, 16);
7553
7554                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, stack_area);
7555
7556                 for (i = 0; i < n; ++i) {
7557                         inst = cfg->args [i];
7558
7559                         if (inst->opcode == OP_REGVAR)
7560                                 amd64_mov_membase_reg (code, AMD64_RSP, (i * 8), inst->dreg, 8);
7561                         else {
7562                                 amd64_mov_reg_membase (code, AMD64_R11, inst->inst_basereg, inst->inst_offset, 8);
7563                                 amd64_mov_membase_reg (code, AMD64_RSP, (i * 8), AMD64_R11, 8);
7564                         }
7565                 }
7566         }
7567
7568         mono_add_patch_info (cfg, code-cfg->native_code, MONO_PATCH_INFO_METHODCONST, cfg->method);
7569         amd64_set_reg_template (code, AMD64_ARG_REG1);
7570         amd64_mov_reg_reg (code, AMD64_ARG_REG2, AMD64_RSP, 8);
7571         code = emit_call (cfg, code, MONO_PATCH_INFO_ABS, (gpointer)func, TRUE);
7572
7573         if (enable_arguments)
7574                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, stack_area);
7575
7576         return code;
7577 }
7578
7579 enum {
7580         SAVE_NONE,
7581         SAVE_STRUCT,
7582         SAVE_EAX,
7583         SAVE_EAX_EDX,
7584         SAVE_XMM
7585 };
7586
7587 void*
7588 mono_arch_instrument_epilog_full (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments, gboolean preserve_argument_registers)
7589 {
7590         guchar *code = p;
7591         int save_mode = SAVE_NONE;
7592         MonoMethod *method = cfg->method;
7593         MonoType *ret_type = mini_type_get_underlying_type (NULL, mono_method_signature (method)->ret);
7594         int i;
7595         
7596         switch (ret_type->type) {
7597         case MONO_TYPE_VOID:
7598                 /* special case string .ctor icall */
7599                 if (strcmp (".ctor", method->name) && method->klass == mono_defaults.string_class)
7600                         save_mode = SAVE_EAX;
7601                 else
7602                         save_mode = SAVE_NONE;
7603                 break;
7604         case MONO_TYPE_I8:
7605         case MONO_TYPE_U8:
7606                 save_mode = SAVE_EAX;
7607                 break;
7608         case MONO_TYPE_R4:
7609         case MONO_TYPE_R8:
7610                 save_mode = SAVE_XMM;
7611                 break;
7612         case MONO_TYPE_GENERICINST:
7613                 if (!mono_type_generic_inst_is_valuetype (ret_type)) {
7614                         save_mode = SAVE_EAX;
7615                         break;
7616                 }
7617                 /* Fall through */
7618         case MONO_TYPE_VALUETYPE:
7619                 save_mode = SAVE_STRUCT;
7620                 break;
7621         default:
7622                 save_mode = SAVE_EAX;
7623                 break;
7624         }
7625
7626         /* Save the result and copy it into the proper argument register */
7627         switch (save_mode) {
7628         case SAVE_EAX:
7629                 amd64_push_reg (code, AMD64_RAX);
7630                 /* Align stack */
7631                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
7632                 if (enable_arguments)
7633                         amd64_mov_reg_reg (code, AMD64_ARG_REG2, AMD64_RAX, 8);
7634                 break;
7635         case SAVE_STRUCT:
7636                 /* FIXME: */
7637                 if (enable_arguments)
7638                         amd64_mov_reg_imm (code, AMD64_ARG_REG2, 0);
7639                 break;
7640         case SAVE_XMM:
7641                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
7642                 amd64_movsd_membase_reg (code, AMD64_RSP, 0, AMD64_XMM0);
7643                 /* Align stack */
7644                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
7645                 /* 
7646                  * The result is already in the proper argument register so no copying
7647                  * needed.
7648                  */
7649                 break;
7650         case SAVE_NONE:
7651                 break;
7652         default:
7653                 g_assert_not_reached ();
7654         }
7655
7656         /* Set %al since this is a varargs call */
7657         if (save_mode == SAVE_XMM)
7658                 amd64_mov_reg_imm (code, AMD64_RAX, 1);
7659         else
7660                 amd64_mov_reg_imm (code, AMD64_RAX, 0);
7661
7662         if (preserve_argument_registers) {
7663                 for (i = 0; i < PARAM_REGS; ++i)
7664                         amd64_push_reg (code, param_regs [i]);
7665         }
7666
7667         mono_add_patch_info (cfg, code-cfg->native_code, MONO_PATCH_INFO_METHODCONST, method);
7668         amd64_set_reg_template (code, AMD64_ARG_REG1);
7669         code = emit_call (cfg, code, MONO_PATCH_INFO_ABS, (gpointer)func, TRUE);
7670
7671         if (preserve_argument_registers) {
7672                 for (i = PARAM_REGS - 1; i >= 0; --i)
7673                         amd64_pop_reg (code, param_regs [i]);
7674         }
7675
7676         /* Restore result */
7677         switch (save_mode) {
7678         case SAVE_EAX:
7679                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
7680                 amd64_pop_reg (code, AMD64_RAX);
7681                 break;
7682         case SAVE_STRUCT:
7683                 /* FIXME: */
7684                 break;
7685         case SAVE_XMM:
7686                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
7687                 amd64_movsd_reg_membase (code, AMD64_XMM0, AMD64_RSP, 0);
7688                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
7689                 break;
7690         case SAVE_NONE:
7691                 break;
7692         default:
7693                 g_assert_not_reached ();
7694         }
7695
7696         return code;
7697 }
7698
7699 void
7700 mono_arch_flush_icache (guint8 *code, gint size)
7701 {
7702         /* Not needed */
7703 }
7704
7705 void
7706 mono_arch_flush_register_windows (void)
7707 {
7708 }
7709
7710 gboolean 
7711 mono_arch_is_inst_imm (gint64 imm)
7712 {
7713         return amd64_is_imm32 (imm);
7714 }
7715
7716 /*
7717  * Determine whenever the trap whose info is in SIGINFO is caused by
7718  * integer overflow.
7719  */
7720 gboolean
7721 mono_arch_is_int_overflow (void *sigctx, void *info)
7722 {
7723         MonoContext ctx;
7724         guint8* rip;
7725         int reg;
7726         gint64 value;
7727
7728         mono_arch_sigctx_to_monoctx (sigctx, &ctx);
7729
7730         rip = (guint8*)ctx.rip;
7731
7732         if (IS_REX (rip [0])) {
7733                 reg = amd64_rex_b (rip [0]);
7734                 rip ++;
7735         }
7736         else
7737                 reg = 0;
7738
7739         if ((rip [0] == 0xf7) && (x86_modrm_mod (rip [1]) == 0x3) && (x86_modrm_reg (rip [1]) == 0x7)) {
7740                 /* idiv REG */
7741                 reg += x86_modrm_rm (rip [1]);
7742
7743                 switch (reg) {
7744                 case AMD64_RAX:
7745                         value = ctx.rax;
7746                         break;
7747                 case AMD64_RBX:
7748                         value = ctx.rbx;
7749                         break;
7750                 case AMD64_RCX:
7751                         value = ctx.rcx;
7752                         break;
7753                 case AMD64_RDX:
7754                         value = ctx.rdx;
7755                         break;
7756                 case AMD64_RBP:
7757                         value = ctx.rbp;
7758                         break;
7759                 case AMD64_RSP:
7760                         value = ctx.rsp;
7761                         break;
7762                 case AMD64_RSI:
7763                         value = ctx.rsi;
7764                         break;
7765                 case AMD64_RDI:
7766                         value = ctx.rdi;
7767                         break;
7768                 case AMD64_R12:
7769                         value = ctx.r12;
7770                         break;
7771                 case AMD64_R13:
7772                         value = ctx.r13;
7773                         break;
7774                 case AMD64_R14:
7775                         value = ctx.r14;
7776                         break;
7777                 case AMD64_R15:
7778                         value = ctx.r15;
7779                         break;
7780                 default:
7781                         g_assert_not_reached ();
7782                         reg = -1;
7783                 }                       
7784
7785                 if (value == -1)
7786                         return TRUE;
7787         }
7788
7789         return FALSE;
7790 }
7791
7792 guint32
7793 mono_arch_get_patch_offset (guint8 *code)
7794 {
7795         return 3;
7796 }
7797
7798 /**
7799  * mono_breakpoint_clean_code:
7800  *
7801  * Copy @size bytes from @code - @offset to the buffer @buf. If the debugger inserted software
7802  * breakpoints in the original code, they are removed in the copy.
7803  *
7804  * Returns TRUE if no sw breakpoint was present.
7805  */
7806 gboolean
7807 mono_breakpoint_clean_code (guint8 *method_start, guint8 *code, int offset, guint8 *buf, int size)
7808 {
7809         int i;
7810         gboolean can_write = TRUE;
7811         /*
7812          * If method_start is non-NULL we need to perform bound checks, since we access memory
7813          * at code - offset we could go before the start of the method and end up in a different
7814          * page of memory that is not mapped or read incorrect data anyway. We zero-fill the bytes
7815          * instead.
7816          */
7817         if (!method_start || code - offset >= method_start) {
7818                 memcpy (buf, code - offset, size);
7819         } else {
7820                 int diff = code - method_start;
7821                 memset (buf, 0, size);
7822                 memcpy (buf + offset - diff, method_start, diff + size - offset);
7823         }
7824         code -= offset;
7825         for (i = 0; i < MONO_BREAKPOINT_ARRAY_SIZE; ++i) {
7826                 int idx = mono_breakpoint_info_index [i];
7827                 guint8 *ptr;
7828                 if (idx < 1)
7829                         continue;
7830                 ptr = mono_breakpoint_info [idx].address;
7831                 if (ptr >= code && ptr < code + size) {
7832                         guint8 saved_byte = mono_breakpoint_info [idx].saved_byte;
7833                         can_write = FALSE;
7834                         /*g_print ("patching %p with 0x%02x (was: 0x%02x)\n", ptr, saved_byte, buf [ptr - code]);*/
7835                         buf [ptr - code] = saved_byte;
7836                 }
7837         }
7838         return can_write;
7839 }
7840
7841 #if defined(__native_client_codegen__)
7842 /* For membase calls, we want the base register. for Native Client,  */
7843 /* all indirect calls have the following sequence with the given sizes: */
7844 /* mov %eXX,%eXX                                [2-3]   */
7845 /* mov disp(%r15,%rXX,scale),%r11d              [4-8]   */
7846 /* and $0xffffffffffffffe0,%r11d                [4]     */
7847 /* add %r15,%r11                                [3]     */
7848 /* callq *%r11                                  [3]     */
7849
7850
7851 /* Determine if code points to a NaCl call-through-register sequence, */
7852 /* (i.e., the last 3 instructions listed above) */
7853 int
7854 is_nacl_call_reg_sequence(guint8* code)
7855 {
7856         const char *sequence = "\x41\x83\xe3\xe0" /* and */
7857                                "\x4d\x03\xdf"     /* add */
7858                                "\x41\xff\xd3";   /* call */
7859         return memcmp(code, sequence, 10) == 0;
7860 }
7861
7862 /* Determine if code points to the first opcode of the mov membase component */
7863 /* of an indirect call sequence (i.e. the first 2 instructions listed above) */
7864 /* (there could be a REX prefix before the opcode but it is ignored) */
7865 static int
7866 is_nacl_indirect_call_membase_sequence(guint8* code)
7867 {
7868                /* Check for mov opcode, reg-reg addressing mode (mod = 3), */
7869         return code[0] == 0x8b && amd64_modrm_mod(code[1]) == 3 &&
7870                /* and that src reg = dest reg */
7871                amd64_modrm_reg(code[1]) == amd64_modrm_rm(code[1]) &&
7872                /* Check that next inst is mov, uses SIB byte (rm = 4), */
7873                IS_REX(code[2]) &&
7874                code[3] == 0x8b && amd64_modrm_rm(code[4]) == 4 &&
7875                /* and has dst of r11 and base of r15 */
7876                (amd64_modrm_reg(code[4]) + amd64_rex_r(code[2])) == AMD64_R11 &&
7877                (amd64_sib_base(code[5]) + amd64_rex_b(code[2])) == AMD64_R15;
7878 }
7879 #endif /* __native_client_codegen__ */
7880
7881 int
7882 mono_arch_get_this_arg_reg (guint8 *code)
7883 {
7884         return AMD64_ARG_REG1;
7885 }
7886
7887 gpointer
7888 mono_arch_get_this_arg_from_call (mgreg_t *regs, guint8 *code)
7889 {
7890         return (gpointer)regs [mono_arch_get_this_arg_reg (code)];
7891 }
7892
7893 #define MAX_ARCH_DELEGATE_PARAMS 10
7894
7895 static gpointer
7896 get_delegate_invoke_impl (gboolean has_target, guint32 param_count, guint32 *code_len)
7897 {
7898         guint8 *code, *start;
7899         int i;
7900
7901         if (has_target) {
7902                 start = code = mono_global_codeman_reserve (64);
7903
7904                 /* Replace the this argument with the target */
7905                 amd64_mov_reg_reg (code, AMD64_RAX, AMD64_ARG_REG1, 8);
7906                 amd64_mov_reg_membase (code, AMD64_ARG_REG1, AMD64_RAX, G_STRUCT_OFFSET (MonoDelegate, target), 8);
7907                 amd64_jump_membase (code, AMD64_RAX, G_STRUCT_OFFSET (MonoDelegate, method_ptr));
7908
7909                 g_assert ((code - start) < 64);
7910         } else {
7911                 start = code = mono_global_codeman_reserve (64);
7912
7913                 if (param_count == 0) {
7914                         amd64_jump_membase (code, AMD64_ARG_REG1, G_STRUCT_OFFSET (MonoDelegate, method_ptr));
7915                 } else {
7916                         /* We have to shift the arguments left */
7917                         amd64_mov_reg_reg (code, AMD64_RAX, AMD64_ARG_REG1, 8);
7918                         for (i = 0; i < param_count; ++i) {
7919 #ifdef HOST_WIN32
7920                                 if (i < 3)
7921                                         amd64_mov_reg_reg (code, param_regs [i], param_regs [i + 1], 8);
7922                                 else
7923                                         amd64_mov_reg_membase (code, param_regs [i], AMD64_RSP, 0x28, 8);
7924 #else
7925                                 amd64_mov_reg_reg (code, param_regs [i], param_regs [i + 1], 8);
7926 #endif
7927                         }
7928
7929                         amd64_jump_membase (code, AMD64_RAX, G_STRUCT_OFFSET (MonoDelegate, method_ptr));
7930                 }
7931                 g_assert ((code - start) < 64);
7932         }
7933
7934         nacl_global_codeman_validate(&start, 64, &code);
7935
7936         mono_debug_add_delegate_trampoline (start, code - start);
7937
7938         if (code_len)
7939                 *code_len = code - start;
7940
7941
7942         if (mono_jit_map_is_enabled ()) {
7943                 char *buff;
7944                 if (has_target)
7945                         buff = (char*)"delegate_invoke_has_target";
7946                 else
7947                         buff = g_strdup_printf ("delegate_invoke_no_target_%d", param_count);
7948                 mono_emit_jit_tramp (start, code - start, buff);
7949                 if (!has_target)
7950                         g_free (buff);
7951         }
7952
7953         return start;
7954 }
7955
7956 /*
7957  * mono_arch_get_delegate_invoke_impls:
7958  *
7959  *   Return a list of MonoTrampInfo structures for the delegate invoke impl
7960  * trampolines.
7961  */
7962 GSList*
7963 mono_arch_get_delegate_invoke_impls (void)
7964 {
7965         GSList *res = NULL;
7966         guint8 *code;
7967         guint32 code_len;
7968         int i;
7969
7970         code = get_delegate_invoke_impl (TRUE, 0, &code_len);
7971         res = g_slist_prepend (res, mono_tramp_info_create (g_strdup ("delegate_invoke_impl_has_target"), code, code_len, NULL, NULL));
7972
7973         for (i = 0; i < MAX_ARCH_DELEGATE_PARAMS; ++i) {
7974                 code = get_delegate_invoke_impl (FALSE, i, &code_len);
7975                 res = g_slist_prepend (res, mono_tramp_info_create (g_strdup_printf ("delegate_invoke_impl_target_%d", i), code, code_len, NULL, NULL));
7976         }
7977
7978         return res;
7979 }
7980
7981 gpointer
7982 mono_arch_get_delegate_invoke_impl (MonoMethodSignature *sig, gboolean has_target)
7983 {
7984         guint8 *code, *start;
7985         int i;
7986
7987         if (sig->param_count > MAX_ARCH_DELEGATE_PARAMS)
7988                 return NULL;
7989
7990         /* FIXME: Support more cases */
7991         if (MONO_TYPE_ISSTRUCT (sig->ret))
7992                 return NULL;
7993
7994         if (has_target) {
7995                 static guint8* cached = NULL;
7996
7997                 if (cached)
7998                         return cached;
7999
8000                 if (mono_aot_only)
8001                         start = mono_aot_get_trampoline ("delegate_invoke_impl_has_target");
8002                 else
8003                         start = get_delegate_invoke_impl (TRUE, 0, NULL);
8004
8005                 mono_memory_barrier ();
8006
8007                 cached = start;
8008         } else {
8009                 static guint8* cache [MAX_ARCH_DELEGATE_PARAMS + 1] = {NULL};
8010                 for (i = 0; i < sig->param_count; ++i)
8011                         if (!mono_is_regsize_var (sig->params [i]))
8012                                 return NULL;
8013                 if (sig->param_count > 4)
8014                         return NULL;
8015
8016                 code = cache [sig->param_count];
8017                 if (code)
8018                         return code;
8019
8020                 if (mono_aot_only) {
8021                         char *name = g_strdup_printf ("delegate_invoke_impl_target_%d", sig->param_count);
8022                         start = mono_aot_get_trampoline (name);
8023                         g_free (name);
8024                 } else {
8025                         start = get_delegate_invoke_impl (FALSE, sig->param_count, NULL);
8026                 }
8027
8028                 mono_memory_barrier ();
8029
8030                 cache [sig->param_count] = start;
8031         }
8032
8033         return start;
8034 }
8035
8036 /*
8037  * Support for fast access to the thread-local lmf structure using the GS
8038  * segment register on NPTL + kernel 2.6.x.
8039  */
8040
8041 static gboolean tls_offset_inited = FALSE;
8042
8043 void
8044 mono_arch_setup_jit_tls_data (MonoJitTlsData *tls)
8045 {
8046         if (!tls_offset_inited) {
8047 #ifdef HOST_WIN32
8048                 /* 
8049                  * We need to init this multiple times, since when we are first called, the key might not
8050                  * be initialized yet.
8051                  */
8052                 appdomain_tls_offset = mono_domain_get_tls_key ();
8053                 lmf_tls_offset = mono_get_jit_tls_key ();
8054                 lmf_addr_tls_offset = mono_get_jit_tls_key ();
8055
8056                 /* Only 64 tls entries can be accessed using inline code */
8057                 if (appdomain_tls_offset >= 64)
8058                         appdomain_tls_offset = -1;
8059                 if (lmf_tls_offset >= 64)
8060                         lmf_tls_offset = -1;
8061 #else
8062                 tls_offset_inited = TRUE;
8063 #ifdef MONO_XEN_OPT
8064                 optimize_for_xen = access ("/proc/xen", F_OK) == 0;
8065 #endif
8066                 appdomain_tls_offset = mono_domain_get_tls_offset ();
8067                 lmf_tls_offset = mono_get_lmf_tls_offset ();
8068                 lmf_addr_tls_offset = mono_get_lmf_addr_tls_offset ();
8069 #endif
8070         }               
8071 }
8072
8073 void
8074 mono_arch_free_jit_tls_data (MonoJitTlsData *tls)
8075 {
8076 }
8077
8078 #ifdef MONO_ARCH_HAVE_IMT
8079
8080 #if defined(__default_codegen__)
8081 #define CMP_SIZE (6 + 1)
8082 #define CMP_REG_REG_SIZE (4 + 1)
8083 #define BR_SMALL_SIZE 2
8084 #define BR_LARGE_SIZE 6
8085 #define MOV_REG_IMM_SIZE 10
8086 #define MOV_REG_IMM_32BIT_SIZE 6
8087 #define JUMP_REG_SIZE (2 + 1)
8088 #elif defined(__native_client_codegen__)
8089 /* NaCl N-byte instructions can be padded up to N-1 bytes */
8090 #define CMP_SIZE ((6 + 1) * 2 - 1)
8091 #define CMP_REG_REG_SIZE ((4 + 1) * 2 - 1)
8092 #define BR_SMALL_SIZE (2 * 2 - 1)
8093 #define BR_LARGE_SIZE (6 * 2 - 1)
8094 #define MOV_REG_IMM_SIZE (10 * 2 - 1)
8095 #define MOV_REG_IMM_32BIT_SIZE (6 * 2 - 1)
8096 /* Jump reg for NaCl adds a mask (+4) and add (+3) */
8097 #define JUMP_REG_SIZE ((2 + 1 + 4 + 3) * 2 - 1)
8098 /* Jump membase's size is large and unpredictable    */
8099 /* in native client, just pad it out a whole bundle. */
8100 #define JUMP_MEMBASE_SIZE (kNaClAlignment)
8101 #endif
8102
8103 static int
8104 imt_branch_distance (MonoIMTCheckItem **imt_entries, int start, int target)
8105 {
8106         int i, distance = 0;
8107         for (i = start; i < target; ++i)
8108                 distance += imt_entries [i]->chunk_size;
8109         return distance;
8110 }
8111
8112 /*
8113  * LOCKING: called with the domain lock held
8114  */
8115 gpointer
8116 mono_arch_build_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count,
8117         gpointer fail_tramp)
8118 {
8119         int i;
8120         int size = 0;
8121         guint8 *code, *start;
8122         gboolean vtable_is_32bit = ((gsize)(vtable) == (gsize)(int)(gsize)(vtable));
8123
8124         for (i = 0; i < count; ++i) {
8125                 MonoIMTCheckItem *item = imt_entries [i];
8126                 if (item->is_equals) {
8127                         if (item->check_target_idx) {
8128                                 if (!item->compare_done) {
8129                                         if (amd64_is_imm32 (item->key))
8130                                                 item->chunk_size += CMP_SIZE;
8131                                         else
8132                                                 item->chunk_size += MOV_REG_IMM_SIZE + CMP_REG_REG_SIZE;
8133                                 }
8134                                 if (item->has_target_code) {
8135                                         item->chunk_size += MOV_REG_IMM_SIZE;
8136                                 } else {
8137                                         if (vtable_is_32bit)
8138                                                 item->chunk_size += MOV_REG_IMM_32BIT_SIZE;
8139                                         else
8140                                                 item->chunk_size += MOV_REG_IMM_SIZE;
8141 #ifdef __native_client_codegen__
8142                                         item->chunk_size += JUMP_MEMBASE_SIZE;
8143 #endif
8144                                 }
8145                                 item->chunk_size += BR_SMALL_SIZE + JUMP_REG_SIZE;
8146                         } else {
8147                                 if (fail_tramp) {
8148                                         item->chunk_size += MOV_REG_IMM_SIZE * 3 + CMP_REG_REG_SIZE +
8149                                                 BR_SMALL_SIZE + JUMP_REG_SIZE * 2;
8150                                 } else {
8151                                         if (vtable_is_32bit)
8152                                                 item->chunk_size += MOV_REG_IMM_32BIT_SIZE;
8153                                         else
8154                                                 item->chunk_size += MOV_REG_IMM_SIZE;
8155                                         item->chunk_size += JUMP_REG_SIZE;
8156                                         /* with assert below:
8157                                          * item->chunk_size += CMP_SIZE + BR_SMALL_SIZE + 1;
8158                                          */
8159 #ifdef __native_client_codegen__
8160                                         item->chunk_size += JUMP_MEMBASE_SIZE;
8161 #endif
8162                                 }
8163                         }
8164                 } else {
8165                         if (amd64_is_imm32 (item->key))
8166                                 item->chunk_size += CMP_SIZE;
8167                         else
8168                                 item->chunk_size += MOV_REG_IMM_SIZE + CMP_REG_REG_SIZE;
8169                         item->chunk_size += BR_LARGE_SIZE;
8170                         imt_entries [item->check_target_idx]->compare_done = TRUE;
8171                 }
8172                 size += item->chunk_size;
8173         }
8174 #if defined(__native_client__) && defined(__native_client_codegen__)
8175         /* In Native Client, we don't re-use thunks, allocate from the */
8176         /* normal code manager paths. */
8177         code = mono_domain_code_reserve (domain, size);
8178 #else
8179         if (fail_tramp)
8180                 code = mono_method_alloc_generic_virtual_thunk (domain, size);
8181         else
8182                 code = mono_domain_code_reserve (domain, size);
8183 #endif
8184         start = code;
8185         for (i = 0; i < count; ++i) {
8186                 MonoIMTCheckItem *item = imt_entries [i];
8187                 item->code_target = code;
8188                 if (item->is_equals) {
8189                         gboolean fail_case = !item->check_target_idx && fail_tramp;
8190
8191                         if (item->check_target_idx || fail_case) {
8192                                 if (!item->compare_done || fail_case) {
8193                                         if (amd64_is_imm32 (item->key))
8194                                                 amd64_alu_reg_imm (code, X86_CMP, MONO_ARCH_IMT_REG, (guint32)(gssize)item->key);
8195                                         else {
8196                                                 amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, item->key);
8197                                                 amd64_alu_reg_reg (code, X86_CMP, MONO_ARCH_IMT_REG, MONO_ARCH_IMT_SCRATCH_REG);
8198                                         }
8199                                 }
8200                                 item->jmp_code = code;
8201                                 amd64_branch8 (code, X86_CC_NE, 0, FALSE);
8202                                 if (item->has_target_code) {
8203                                         amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, item->value.target_code);
8204                                         amd64_jump_reg (code, MONO_ARCH_IMT_SCRATCH_REG);
8205                                 } else {
8206                                         amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, & (vtable->vtable [item->value.vtable_slot]));
8207                                         amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
8208                                 }
8209
8210                                 if (fail_case) {
8211                                         amd64_patch (item->jmp_code, code);
8212                                         amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, fail_tramp);
8213                                         amd64_jump_reg (code, MONO_ARCH_IMT_SCRATCH_REG);
8214                                         item->jmp_code = NULL;
8215                                 }
8216                         } else {
8217                                 /* enable the commented code to assert on wrong method */
8218 #if 0
8219                                 if (amd64_is_imm32 (item->key))
8220                                         amd64_alu_reg_imm (code, X86_CMP, MONO_ARCH_IMT_REG, (guint32)(gssize)item->key);
8221                                 else {
8222                                         amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, item->key);
8223                                         amd64_alu_reg_reg (code, X86_CMP, MONO_ARCH_IMT_REG, MONO_ARCH_IMT_SCRATCH_REG);
8224                                 }
8225                                 item->jmp_code = code;
8226                                 amd64_branch8 (code, X86_CC_NE, 0, FALSE);
8227                                 /* See the comment below about R10 */
8228                                 amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, & (vtable->vtable [item->value.vtable_slot]));
8229                                 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
8230                                 amd64_patch (item->jmp_code, code);
8231                                 amd64_breakpoint (code);
8232                                 item->jmp_code = NULL;
8233 #else
8234                                 /* We're using R10 (MONO_ARCH_IMT_SCRATCH_REG) here because R11 (MONO_ARCH_IMT_REG)
8235                                    needs to be preserved.  R10 needs
8236                                    to be preserved for calls which
8237                                    require a runtime generic context,
8238                                    but interface calls don't. */
8239                                 amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, & (vtable->vtable [item->value.vtable_slot]));
8240                                 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
8241 #endif
8242                         }
8243                 } else {
8244                         if (amd64_is_imm32 (item->key))
8245                                 amd64_alu_reg_imm (code, X86_CMP, MONO_ARCH_IMT_REG, (guint32)(gssize)item->key);
8246                         else {
8247                                 amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, item->key);
8248                                 amd64_alu_reg_reg (code, X86_CMP, MONO_ARCH_IMT_REG, MONO_ARCH_IMT_SCRATCH_REG);
8249                         }
8250                         item->jmp_code = code;
8251                         if (x86_is_imm8 (imt_branch_distance (imt_entries, i, item->check_target_idx)))
8252                                 x86_branch8 (code, X86_CC_GE, 0, FALSE);
8253                         else
8254                                 x86_branch32 (code, X86_CC_GE, 0, FALSE);
8255                 }
8256                 g_assert (code - item->code_target <= item->chunk_size);
8257         }
8258         /* patch the branches to get to the target items */
8259         for (i = 0; i < count; ++i) {
8260                 MonoIMTCheckItem *item = imt_entries [i];
8261                 if (item->jmp_code) {
8262                         if (item->check_target_idx) {
8263                                 amd64_patch (item->jmp_code, imt_entries [item->check_target_idx]->code_target);
8264                         }
8265                 }
8266         }
8267
8268         if (!fail_tramp)
8269                 mono_stats.imt_thunks_size += code - start;
8270         g_assert (code - start <= size);
8271
8272         nacl_domain_code_validate(domain, &start, size, &code);
8273
8274         return start;
8275 }
8276
8277 MonoMethod*
8278 mono_arch_find_imt_method (mgreg_t *regs, guint8 *code)
8279 {
8280         return (MonoMethod*)regs [MONO_ARCH_IMT_REG];
8281 }
8282 #endif
8283
8284 MonoVTable*
8285 mono_arch_find_static_call_vtable (mgreg_t *regs, guint8 *code)
8286 {
8287         return (MonoVTable*) regs [MONO_ARCH_RGCTX_REG];
8288 }
8289
8290 GSList*
8291 mono_arch_get_cie_program (void)
8292 {
8293         GSList *l = NULL;
8294
8295         mono_add_unwind_op_def_cfa (l, (guint8*)NULL, (guint8*)NULL, AMD64_RSP, 8);
8296         mono_add_unwind_op_offset (l, (guint8*)NULL, (guint8*)NULL, AMD64_RIP, -8);
8297
8298         return l;
8299 }
8300
8301 MonoInst*
8302 mono_arch_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
8303 {
8304         MonoInst *ins = NULL;
8305         int opcode = 0;
8306
8307         if (cmethod->klass == mono_defaults.math_class) {
8308                 if (strcmp (cmethod->name, "Sin") == 0) {
8309                         opcode = OP_SIN;
8310                 } else if (strcmp (cmethod->name, "Cos") == 0) {
8311                         opcode = OP_COS;
8312                 } else if (strcmp (cmethod->name, "Sqrt") == 0) {
8313                         opcode = OP_SQRT;
8314                 } else if (strcmp (cmethod->name, "Abs") == 0 && fsig->params [0]->type == MONO_TYPE_R8) {
8315                         opcode = OP_ABS;
8316                 }
8317                 
8318                 if (opcode) {
8319                         MONO_INST_NEW (cfg, ins, opcode);
8320                         ins->type = STACK_R8;
8321                         ins->dreg = mono_alloc_freg (cfg);
8322                         ins->sreg1 = args [0]->dreg;
8323                         MONO_ADD_INS (cfg->cbb, ins);
8324                 }
8325
8326                 opcode = 0;
8327                 if (cfg->opt & MONO_OPT_CMOV) {
8328                         if (strcmp (cmethod->name, "Min") == 0) {
8329                                 if (fsig->params [0]->type == MONO_TYPE_I4)
8330                                         opcode = OP_IMIN;
8331                                 if (fsig->params [0]->type == MONO_TYPE_U4)
8332                                         opcode = OP_IMIN_UN;
8333                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
8334                                         opcode = OP_LMIN;
8335                                 else if (fsig->params [0]->type == MONO_TYPE_U8)
8336                                         opcode = OP_LMIN_UN;
8337                         } else if (strcmp (cmethod->name, "Max") == 0) {
8338                                 if (fsig->params [0]->type == MONO_TYPE_I4)
8339                                         opcode = OP_IMAX;
8340                                 if (fsig->params [0]->type == MONO_TYPE_U4)
8341                                         opcode = OP_IMAX_UN;
8342                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
8343                                         opcode = OP_LMAX;
8344                                 else if (fsig->params [0]->type == MONO_TYPE_U8)
8345                                         opcode = OP_LMAX_UN;
8346                         }
8347                 }
8348                 
8349                 if (opcode) {
8350                         MONO_INST_NEW (cfg, ins, opcode);
8351                         ins->type = fsig->params [0]->type == MONO_TYPE_I4 ? STACK_I4 : STACK_I8;
8352                         ins->dreg = mono_alloc_ireg (cfg);
8353                         ins->sreg1 = args [0]->dreg;
8354                         ins->sreg2 = args [1]->dreg;
8355                         MONO_ADD_INS (cfg->cbb, ins);
8356                 }
8357
8358 #if 0
8359                 /* OP_FREM is not IEEE compatible */
8360                 else if (strcmp (cmethod->name, "IEEERemainder") == 0) {
8361                         MONO_INST_NEW (cfg, ins, OP_FREM);
8362                         ins->inst_i0 = args [0];
8363                         ins->inst_i1 = args [1];
8364                 }
8365 #endif
8366         }
8367
8368         /* 
8369          * Can't implement CompareExchange methods this way since they have
8370          * three arguments.
8371          */
8372
8373         return ins;
8374 }
8375
8376 gboolean
8377 mono_arch_print_tree (MonoInst *tree, int arity)
8378 {
8379         return 0;
8380 }
8381
8382 MonoInst* mono_arch_get_domain_intrinsic (MonoCompile* cfg)
8383 {
8384         MonoInst* ins;
8385         
8386         if (appdomain_tls_offset == -1)
8387                 return NULL;
8388         
8389         MONO_INST_NEW (cfg, ins, OP_TLS_GET);
8390         ins->inst_offset = appdomain_tls_offset;
8391         return ins;
8392 }
8393
8394 #define _CTX_REG(ctx,fld,i) ((&ctx->fld)[i])
8395
8396 mgreg_t
8397 mono_arch_context_get_int_reg (MonoContext *ctx, int reg)
8398 {
8399         switch (reg) {
8400         case AMD64_RCX: return ctx->rcx;
8401         case AMD64_RDX: return ctx->rdx;
8402         case AMD64_RBX: return ctx->rbx;
8403         case AMD64_RBP: return ctx->rbp;
8404         case AMD64_RSP: return ctx->rsp;
8405         default:
8406                 if (reg < 8)
8407                         return _CTX_REG (ctx, rax, reg);
8408                 else if (reg >= 12)
8409                         return _CTX_REG (ctx, r12, reg - 12);
8410                 else
8411                         g_assert_not_reached ();
8412         }
8413 }
8414
8415 void
8416 mono_arch_context_set_int_reg (MonoContext *ctx, int reg, mgreg_t val)
8417 {
8418         switch (reg) {
8419         case AMD64_RCX:
8420                 ctx->rcx = val;
8421                 break;
8422         case AMD64_RDX: 
8423                 ctx->rdx = val;
8424                 break;
8425         case AMD64_RBX:
8426                 ctx->rbx = val;
8427                 break;
8428         case AMD64_RBP:
8429                 ctx->rbp = val;
8430                 break;
8431         case AMD64_RSP:
8432                 ctx->rsp = val;
8433                 break;
8434         default:
8435                 if (reg < 8)
8436                         _CTX_REG (ctx, rax, reg) = val;
8437                 else if (reg >= 12)
8438                         _CTX_REG (ctx, r12, reg - 12) = val;
8439                 else
8440                         g_assert_not_reached ();
8441         }
8442 }
8443
8444 /*MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD*/
8445 gpointer
8446 mono_arch_install_handler_block_guard (MonoJitInfo *ji, MonoJitExceptionInfo *clause, MonoContext *ctx, gpointer new_value)
8447 {
8448         int offset;
8449         gpointer *sp, old_value;
8450         char *bp;
8451         const unsigned char *handler;
8452
8453         /*Decode the first instruction to figure out where did we store the spvar*/
8454         /*Our jit MUST generate the following:
8455          mov    %rsp, ?(%rbp)
8456
8457          Which is encoded as: REX.W 0x89 mod_rm
8458          mod_rm (rsp, rbp, imm) which can be: (imm will never be zero)
8459                 mod (reg + imm8):  01 reg(rsp): 100 rm(rbp): 101 -> 01100101 (0x65)
8460                 mod (reg + imm32): 10 reg(rsp): 100 rm(rbp): 101 -> 10100101 (0xA5)
8461
8462         FIXME can we generate frameless methods on this case?
8463
8464         */
8465         handler = clause->handler_start;
8466
8467         /*REX.W*/
8468         if (*handler != 0x48)
8469                 return NULL;
8470         ++handler;
8471
8472         /*mov r, r/m */
8473         if (*handler != 0x89)
8474                 return NULL;
8475         ++handler;
8476
8477         if (*handler == 0x65)
8478                 offset = *(signed char*)(handler + 1);
8479         else if (*handler == 0xA5)
8480                 offset = *(int*)(handler + 1);
8481         else
8482                 return NULL;
8483
8484         /*Load the spvar*/
8485         bp = MONO_CONTEXT_GET_BP (ctx);
8486         sp = *(gpointer*)(bp + offset);
8487
8488         old_value = *sp;
8489         if (old_value < ji->code_start || (char*)old_value > ((char*)ji->code_start + ji->code_size))
8490                 return old_value;
8491
8492         *sp = new_value;
8493
8494         return old_value;
8495 }
8496
8497 /*
8498  * mono_arch_emit_load_aotconst:
8499  *
8500  *   Emit code to load the contents of the GOT slot identified by TRAMP_TYPE and
8501  * TARGET from the mscorlib GOT in full-aot code.
8502  * On AMD64, the result is placed into R11.
8503  */
8504 guint8*
8505 mono_arch_emit_load_aotconst (guint8 *start, guint8 *code, MonoJumpInfo **ji, int tramp_type, gconstpointer target)
8506 {
8507         *ji = mono_patch_info_list_prepend (*ji, code - start, tramp_type, target);
8508         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, 8);
8509
8510         return code;
8511 }
8512
8513 /*
8514  * mono_arch_get_trampolines:
8515  *
8516  *   Return a list of MonoTrampInfo structures describing arch specific trampolines
8517  * for AOT.
8518  */
8519 GSList *
8520 mono_arch_get_trampolines (gboolean aot)
8521 {
8522         return mono_amd64_get_exception_trampolines (aot);
8523 }
8524
8525 /* Soft Debug support */
8526 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
8527
8528 /*
8529  * mono_arch_set_breakpoint:
8530  *
8531  *   Set a breakpoint at the native code corresponding to JI at NATIVE_OFFSET.
8532  * The location should contain code emitted by OP_SEQ_POINT.
8533  */
8534 void
8535 mono_arch_set_breakpoint (MonoJitInfo *ji, guint8 *ip)
8536 {
8537         guint8 *code = ip;
8538         guint8 *orig_code = code;
8539
8540         if (ji->from_aot) {
8541                 guint32 native_offset = ip - (guint8*)ji->code_start;
8542                 SeqPointInfo *info = mono_arch_get_seq_point_info (mono_domain_get (), ji->code_start);
8543
8544                 g_assert (info->bp_addrs [native_offset] == 0);
8545                 info->bp_addrs [native_offset] = bp_trigger_page;
8546         } else {
8547                 /* 
8548                  * In production, we will use int3 (has to fix the size in the md 
8549                  * file). But that could confuse gdb, so during development, we emit a SIGSEGV
8550                  * instead.
8551                  */
8552                 g_assert (code [0] == 0x90);
8553                 if (breakpoint_size == 8) {
8554                         amd64_mov_reg_mem (code, AMD64_R11, (guint64)bp_trigger_page, 4);
8555                 } else {
8556                         amd64_mov_reg_imm_size (code, AMD64_R11, (guint64)bp_trigger_page, 8);
8557                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 0, 4);
8558                 }
8559
8560                 g_assert (code - orig_code == breakpoint_size);
8561         }
8562 }
8563
8564 /*
8565  * mono_arch_clear_breakpoint:
8566  *
8567  *   Clear the breakpoint at IP.
8568  */
8569 void
8570 mono_arch_clear_breakpoint (MonoJitInfo *ji, guint8 *ip)
8571 {
8572         guint8 *code = ip;
8573         int i;
8574
8575         if (ji->from_aot) {
8576                 guint32 native_offset = ip - (guint8*)ji->code_start;
8577                 SeqPointInfo *info = mono_arch_get_seq_point_info (mono_domain_get (), ji->code_start);
8578
8579                 g_assert (info->bp_addrs [native_offset] == 0);
8580                 info->bp_addrs [native_offset] = info;
8581         } else {
8582                 for (i = 0; i < breakpoint_size; ++i)
8583                         x86_nop (code);
8584         }
8585 }
8586
8587 gboolean
8588 mono_arch_is_breakpoint_event (void *info, void *sigctx)
8589 {
8590 #ifdef HOST_WIN32
8591         EXCEPTION_RECORD* einfo = (EXCEPTION_RECORD*)info;
8592         return FALSE;
8593 #else
8594         siginfo_t* sinfo = (siginfo_t*) info;
8595         /* Sometimes the address is off by 4 */
8596         if (sinfo->si_addr >= bp_trigger_page && (guint8*)sinfo->si_addr <= (guint8*)bp_trigger_page + 128)
8597                 return TRUE;
8598         else
8599                 return FALSE;
8600 #endif
8601 }
8602
8603 /*
8604  * mono_arch_skip_breakpoint:
8605  *
8606  *   Modify CTX so the ip is placed after the breakpoint instruction, so when
8607  * we resume, the instruction is not executed again.
8608  */
8609 void
8610 mono_arch_skip_breakpoint (MonoContext *ctx, MonoJitInfo *ji)
8611 {
8612         if (ji->from_aot) {
8613                 /* amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 0, 8) */
8614                 MONO_CONTEXT_SET_IP (ctx, (guint8*)MONO_CONTEXT_GET_IP (ctx) + 3);
8615         } else {
8616                 MONO_CONTEXT_SET_IP (ctx, (guint8*)MONO_CONTEXT_GET_IP (ctx) + breakpoint_fault_size);
8617         }
8618 }
8619         
8620 /*
8621  * mono_arch_start_single_stepping:
8622  *
8623  *   Start single stepping.
8624  */
8625 void
8626 mono_arch_start_single_stepping (void)
8627 {
8628         mono_mprotect (ss_trigger_page, mono_pagesize (), 0);
8629 }
8630         
8631 /*
8632  * mono_arch_stop_single_stepping:
8633  *
8634  *   Stop single stepping.
8635  */
8636 void
8637 mono_arch_stop_single_stepping (void)
8638 {
8639         mono_mprotect (ss_trigger_page, mono_pagesize (), MONO_MMAP_READ);
8640 }
8641
8642 /*
8643  * mono_arch_is_single_step_event:
8644  *
8645  *   Return whenever the machine state in SIGCTX corresponds to a single
8646  * step event.
8647  */
8648 gboolean
8649 mono_arch_is_single_step_event (void *info, void *sigctx)
8650 {
8651 #ifdef HOST_WIN32
8652         EXCEPTION_RECORD* einfo = (EXCEPTION_RECORD*)info;
8653         return FALSE;
8654 #else
8655         siginfo_t* sinfo = (siginfo_t*) info;
8656         /* Sometimes the address is off by 4 */
8657         if (sinfo->si_addr >= ss_trigger_page && (guint8*)sinfo->si_addr <= (guint8*)ss_trigger_page + 128)
8658                 return TRUE;
8659         else
8660                 return FALSE;
8661 #endif
8662 }
8663
8664 /*
8665  * mono_arch_skip_single_step:
8666  *
8667  *   Modify CTX so the ip is placed after the single step trigger instruction,
8668  * we resume, the instruction is not executed again.
8669  */
8670 void
8671 mono_arch_skip_single_step (MonoContext *ctx)
8672 {
8673         MONO_CONTEXT_SET_IP (ctx, (guint8*)MONO_CONTEXT_GET_IP (ctx) + single_step_fault_size);
8674 }
8675
8676 /*
8677  * mono_arch_create_seq_point_info:
8678  *
8679  *   Return a pointer to a data structure which is used by the sequence
8680  * point implementation in AOTed code.
8681  */
8682 gpointer
8683 mono_arch_get_seq_point_info (MonoDomain *domain, guint8 *code)
8684 {
8685         SeqPointInfo *info;
8686         MonoJitInfo *ji;
8687         int i;
8688
8689         // FIXME: Add a free function
8690
8691         mono_domain_lock (domain);
8692         info = g_hash_table_lookup (domain_jit_info (domain)->arch_seq_points,
8693                                                                 code);
8694         mono_domain_unlock (domain);
8695
8696         if (!info) {
8697                 ji = mono_jit_info_table_find (domain, (char*)code);
8698                 g_assert (ji);
8699
8700                 // FIXME: Optimize the size
8701                 info = g_malloc0 (sizeof (SeqPointInfo) + (ji->code_size * sizeof (gpointer)));
8702
8703                 info->ss_trigger_page = ss_trigger_page;
8704                 info->bp_trigger_page = bp_trigger_page;
8705                 /* Initialize to a valid address */
8706                 for (i = 0; i < ji->code_size; ++i)
8707                         info->bp_addrs [i] = info;
8708
8709                 mono_domain_lock (domain);
8710                 g_hash_table_insert (domain_jit_info (domain)->arch_seq_points,
8711                                                          code, info);
8712                 mono_domain_unlock (domain);
8713         }
8714
8715         return info;
8716 }
8717
8718 #endif