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