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