Merge pull request #754 from blackfusion/master
[mono.git] / mono / mini / mini-amd64.c
1 /*
2  * mini-amd64.c: AMD64 backend for the Mono code generator
3  *
4  * Based on mini-x86.c.
5  *
6  * Authors:
7  *   Paolo Molaro (lupus@ximian.com)
8  *   Dietmar Maurer (dietmar@ximian.com)
9  *   Patrik Torstensson
10  *   Zoltan Varga (vargaz@gmail.com)
11  *
12  * (C) 2003 Ximian, Inc.
13  * Copyright 2003-2011 Novell, Inc (http://www.novell.com)
14  * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
15  */
16 #include "mini.h"
17 #include <string.h>
18 #include <math.h>
19 #ifdef HAVE_UNISTD_H
20 #include <unistd.h>
21 #endif
22
23 #include <mono/metadata/appdomain.h>
24 #include <mono/metadata/debug-helpers.h>
25 #include <mono/metadata/threads.h>
26 #include <mono/metadata/profiler-private.h>
27 #include <mono/metadata/mono-debug.h>
28 #include <mono/metadata/gc-internal.h>
29 #include <mono/utils/mono-math.h>
30 #include <mono/utils/mono-mmap.h>
31 #include <mono/utils/mono-memory-model.h>
32 #include <mono/utils/mono-tls.h>
33 #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                 load->inst_p0 = vtaddr;
2498                 vtaddr->flags |= MONO_INST_INDIRECT;
2499                 load->type = STACK_MP;
2500                 load->klass = vtaddr->klass;
2501                 load->dreg = mono_alloc_ireg (cfg);
2502                 MONO_ADD_INS (cfg->cbb, load);
2503                 mini_emit_memcpy (cfg, load->dreg, 0, src->dreg, 0, size, 4);
2504
2505                 if (ainfo->pair_storage [0] == ArgInIReg) {
2506                         MONO_INST_NEW (cfg, arg, OP_X86_LEA_MEMBASE);
2507                         arg->dreg = mono_alloc_ireg (cfg);
2508                         arg->sreg1 = load->dreg;
2509                         arg->inst_imm = 0;
2510                         MONO_ADD_INS (cfg->cbb, arg);
2511                         mono_call_inst_add_outarg_reg (cfg, call, arg->dreg, ainfo->pair_regs [0], FALSE);
2512                 } else {
2513                         MONO_INST_NEW (cfg, arg, OP_X86_PUSH);
2514                         arg->sreg1 = load->dreg;
2515                         MONO_ADD_INS (cfg->cbb, arg);
2516                 }
2517         } else {
2518                 if (size == 8) {
2519                         if (cfg->arch.no_pushes) {
2520                                 int dreg = mono_alloc_ireg (cfg);
2521
2522                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, src->dreg, 0);
2523                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, AMD64_RSP, ainfo->offset, dreg);
2524                         } else {
2525                                 /* Can't use this for < 8 since it does an 8 byte memory load */
2526                                 MONO_INST_NEW (cfg, arg, OP_X86_PUSH_MEMBASE);
2527                                 arg->inst_basereg = src->dreg;
2528                                 arg->inst_offset = 0;
2529                                 MONO_ADD_INS (cfg->cbb, arg);
2530                         }
2531                 } else if (size <= 40) {
2532                         if (cfg->arch.no_pushes) {
2533                                 mini_emit_memcpy (cfg, AMD64_RSP, ainfo->offset, src->dreg, 0, size, 4);
2534                         } else {
2535                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SUB_IMM, X86_ESP, X86_ESP, ALIGN_TO (size, 8));
2536                                 mini_emit_memcpy (cfg, X86_ESP, 0, src->dreg, 0, size, 4);
2537                         }
2538                 } else {
2539                         if (cfg->arch.no_pushes) {
2540                                 // FIXME: Code growth
2541                                 mini_emit_memcpy (cfg, AMD64_RSP, ainfo->offset, src->dreg, 0, size, 4);
2542                         } else {
2543                                 MONO_INST_NEW (cfg, arg, OP_X86_PUSH_OBJ);
2544                                 arg->inst_basereg = src->dreg;
2545                                 arg->inst_offset = 0;
2546                                 arg->inst_imm = size;
2547                                 MONO_ADD_INS (cfg->cbb, arg);
2548                         }
2549                 }
2550
2551                 if (cfg->compute_gc_maps) {
2552                         MonoInst *def;
2553                         EMIT_NEW_GC_PARAM_SLOT_LIVENESS_DEF (cfg, def, ainfo->offset, &ins->klass->byval_arg);
2554                 }
2555         }
2556 }
2557
2558 void
2559 mono_arch_emit_setret (MonoCompile *cfg, MonoMethod *method, MonoInst *val)
2560 {
2561         MonoType *ret = mini_type_get_underlying_type (NULL, mono_method_signature (method)->ret);
2562
2563         if (ret->type == MONO_TYPE_R4) {
2564                 if (COMPILE_LLVM (cfg))
2565                         MONO_EMIT_NEW_UNALU (cfg, OP_FMOVE, cfg->ret->dreg, val->dreg);
2566                 else
2567                         MONO_EMIT_NEW_UNALU (cfg, OP_AMD64_SET_XMMREG_R4, cfg->ret->dreg, val->dreg);
2568                 return;
2569         } else if (ret->type == MONO_TYPE_R8) {
2570                 MONO_EMIT_NEW_UNALU (cfg, OP_FMOVE, cfg->ret->dreg, val->dreg);
2571                 return;
2572         }
2573                         
2574         MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->ret->dreg, val->dreg);
2575 }
2576
2577 #endif /* DISABLE_JIT */
2578
2579 #define EMIT_COND_BRANCH(ins,cond,sign) \
2580         if (ins->inst_true_bb->native_offset) { \
2581                 x86_branch (code, cond, cfg->native_code + ins->inst_true_bb->native_offset, sign); \
2582         } else { \
2583                 mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_BB, ins->inst_true_bb); \
2584                 if ((cfg->opt & MONO_OPT_BRANCH) && \
2585             x86_is_imm8 (ins->inst_true_bb->max_offset - offset)) \
2586                         x86_branch8 (code, cond, 0, sign); \
2587                 else \
2588                         x86_branch32 (code, cond, 0, sign); \
2589 }
2590
2591 typedef struct {
2592         MonoMethodSignature *sig;
2593         CallInfo *cinfo;
2594 } ArchDynCallInfo;
2595
2596 typedef struct {
2597         mgreg_t regs [PARAM_REGS];
2598         mgreg_t res;
2599         guint8 *ret;
2600 } DynCallArgs;
2601
2602 static gboolean
2603 dyn_call_supported (MonoMethodSignature *sig, CallInfo *cinfo)
2604 {
2605         int i;
2606
2607 #ifdef HOST_WIN32
2608         return FALSE;
2609 #endif
2610
2611         switch (cinfo->ret.storage) {
2612         case ArgNone:
2613         case ArgInIReg:
2614                 break;
2615         case ArgValuetypeInReg: {
2616                 ArgInfo *ainfo = &cinfo->ret;
2617
2618                 if (ainfo->pair_storage [0] != ArgNone && ainfo->pair_storage [0] != ArgInIReg)
2619                         return FALSE;
2620                 if (ainfo->pair_storage [1] != ArgNone && ainfo->pair_storage [1] != ArgInIReg)
2621                         return FALSE;
2622                 break;
2623         }
2624         default:
2625                 return FALSE;
2626         }
2627
2628         for (i = 0; i < cinfo->nargs; ++i) {
2629                 ArgInfo *ainfo = &cinfo->args [i];
2630                 switch (ainfo->storage) {
2631                 case ArgInIReg:
2632                         break;
2633                 case ArgValuetypeInReg:
2634                         if (ainfo->pair_storage [0] != ArgNone && ainfo->pair_storage [0] != ArgInIReg)
2635                                 return FALSE;
2636                         if (ainfo->pair_storage [1] != ArgNone && ainfo->pair_storage [1] != ArgInIReg)
2637                                 return FALSE;
2638                         break;
2639                 default:
2640                         return FALSE;
2641                 }
2642         }
2643
2644         return TRUE;
2645 }
2646
2647 /*
2648  * mono_arch_dyn_call_prepare:
2649  *
2650  *   Return a pointer to an arch-specific structure which contains information 
2651  * needed by mono_arch_get_dyn_call_args (). Return NULL if OP_DYN_CALL is not
2652  * supported for SIG.
2653  * This function is equivalent to ffi_prep_cif in libffi.
2654  */
2655 MonoDynCallInfo*
2656 mono_arch_dyn_call_prepare (MonoMethodSignature *sig)
2657 {
2658         ArchDynCallInfo *info;
2659         CallInfo *cinfo;
2660
2661         cinfo = get_call_info (NULL, NULL, sig);
2662
2663         if (!dyn_call_supported (sig, cinfo)) {
2664                 g_free (cinfo);
2665                 return NULL;
2666         }
2667
2668         info = g_new0 (ArchDynCallInfo, 1);
2669         // FIXME: Preprocess the info to speed up get_dyn_call_args ().
2670         info->sig = sig;
2671         info->cinfo = cinfo;
2672         
2673         return (MonoDynCallInfo*)info;
2674 }
2675
2676 /*
2677  * mono_arch_dyn_call_free:
2678  *
2679  *   Free a MonoDynCallInfo structure.
2680  */
2681 void
2682 mono_arch_dyn_call_free (MonoDynCallInfo *info)
2683 {
2684         ArchDynCallInfo *ainfo = (ArchDynCallInfo*)info;
2685
2686         g_free (ainfo->cinfo);
2687         g_free (ainfo);
2688 }
2689
2690 #if !defined(__native_client__)
2691 #define PTR_TO_GREG(ptr) (mgreg_t)(ptr)
2692 #define GREG_TO_PTR(greg) (gpointer)(greg)
2693 #else
2694 /* Correctly handle casts to/from 32-bit pointers without compiler warnings */
2695 #define PTR_TO_GREG(ptr) (mgreg_t)(uintptr_t)(ptr)
2696 #define GREG_TO_PTR(greg) (gpointer)(guint32)(greg)
2697 #endif
2698
2699 /*
2700  * mono_arch_get_start_dyn_call:
2701  *
2702  *   Convert the arguments ARGS to a format which can be passed to OP_DYN_CALL, and
2703  * store the result into BUF.
2704  * ARGS should be an array of pointers pointing to the arguments.
2705  * RET should point to a memory buffer large enought to hold the result of the
2706  * call.
2707  * This function should be as fast as possible, any work which does not depend
2708  * on the actual values of the arguments should be done in 
2709  * mono_arch_dyn_call_prepare ().
2710  * start_dyn_call + OP_DYN_CALL + finish_dyn_call is equivalent to ffi_call in
2711  * libffi.
2712  */
2713 void
2714 mono_arch_start_dyn_call (MonoDynCallInfo *info, gpointer **args, guint8 *ret, guint8 *buf, int buf_len)
2715 {
2716         ArchDynCallInfo *dinfo = (ArchDynCallInfo*)info;
2717         DynCallArgs *p = (DynCallArgs*)buf;
2718         int arg_index, greg, i, pindex;
2719         MonoMethodSignature *sig = dinfo->sig;
2720
2721         g_assert (buf_len >= sizeof (DynCallArgs));
2722
2723         p->res = 0;
2724         p->ret = ret;
2725
2726         arg_index = 0;
2727         greg = 0;
2728         pindex = 0;
2729
2730         if (sig->hasthis || dinfo->cinfo->vret_arg_index == 1) {
2731                 p->regs [greg ++] = PTR_TO_GREG(*(args [arg_index ++]));
2732                 if (!sig->hasthis)
2733                         pindex = 1;
2734         }
2735
2736         if (dinfo->cinfo->vtype_retaddr)
2737                 p->regs [greg ++] = PTR_TO_GREG(ret);
2738
2739         for (i = pindex; i < sig->param_count; i++) {
2740                 MonoType *t = mono_type_get_underlying_type (sig->params [i]);
2741                 gpointer *arg = args [arg_index ++];
2742
2743                 if (t->byref) {
2744                         p->regs [greg ++] = PTR_TO_GREG(*(arg));
2745                         continue;
2746                 }
2747
2748                 switch (t->type) {
2749                 case MONO_TYPE_STRING:
2750                 case MONO_TYPE_CLASS:  
2751                 case MONO_TYPE_ARRAY:
2752                 case MONO_TYPE_SZARRAY:
2753                 case MONO_TYPE_OBJECT:
2754                 case MONO_TYPE_PTR:
2755                 case MONO_TYPE_I:
2756                 case MONO_TYPE_U:
2757 #if !defined(__mono_ilp32__)
2758                 case MONO_TYPE_I8:
2759                 case MONO_TYPE_U8:
2760 #endif
2761                         g_assert (dinfo->cinfo->args [i + sig->hasthis].reg == param_regs [greg]);
2762                         p->regs [greg ++] = PTR_TO_GREG(*(arg));
2763                         break;
2764 #if defined(__mono_ilp32__)
2765                 case MONO_TYPE_I8:
2766                 case MONO_TYPE_U8:
2767                         g_assert (dinfo->cinfo->args [i + sig->hasthis].reg == param_regs [greg]);
2768                         p->regs [greg ++] = *(guint64*)(arg);
2769                         break;
2770 #endif
2771                 case MONO_TYPE_BOOLEAN:
2772                 case MONO_TYPE_U1:
2773                         p->regs [greg ++] = *(guint8*)(arg);
2774                         break;
2775                 case MONO_TYPE_I1:
2776                         p->regs [greg ++] = *(gint8*)(arg);
2777                         break;
2778                 case MONO_TYPE_I2:
2779                         p->regs [greg ++] = *(gint16*)(arg);
2780                         break;
2781                 case MONO_TYPE_U2:
2782                 case MONO_TYPE_CHAR:
2783                         p->regs [greg ++] = *(guint16*)(arg);
2784                         break;
2785                 case MONO_TYPE_I4:
2786                         p->regs [greg ++] = *(gint32*)(arg);
2787                         break;
2788                 case MONO_TYPE_U4:
2789                         p->regs [greg ++] = *(guint32*)(arg);
2790                         break;
2791                 case MONO_TYPE_GENERICINST:
2792                     if (MONO_TYPE_IS_REFERENCE (t)) {
2793                                 p->regs [greg ++] = PTR_TO_GREG(*(arg));
2794                                 break;
2795                         } else {
2796                                 /* Fall through */
2797                         }
2798                 case MONO_TYPE_VALUETYPE: {
2799                         ArgInfo *ainfo = &dinfo->cinfo->args [i + sig->hasthis];
2800
2801                         g_assert (ainfo->storage == ArgValuetypeInReg);
2802                         if (ainfo->pair_storage [0] != ArgNone) {
2803                                 g_assert (ainfo->pair_storage [0] == ArgInIReg);
2804                                 p->regs [greg ++] = ((mgreg_t*)(arg))[0];
2805                         }
2806                         if (ainfo->pair_storage [1] != ArgNone) {
2807                                 g_assert (ainfo->pair_storage [1] == ArgInIReg);
2808                                 p->regs [greg ++] = ((mgreg_t*)(arg))[1];
2809                         }
2810                         break;
2811                 }
2812                 default:
2813                         g_assert_not_reached ();
2814                 }
2815         }
2816
2817         g_assert (greg <= PARAM_REGS);
2818 }
2819
2820 /*
2821  * mono_arch_finish_dyn_call:
2822  *
2823  *   Store the result of a dyn call into the return value buffer passed to
2824  * start_dyn_call ().
2825  * This function should be as fast as possible, any work which does not depend
2826  * on the actual values of the arguments should be done in 
2827  * mono_arch_dyn_call_prepare ().
2828  */
2829 void
2830 mono_arch_finish_dyn_call (MonoDynCallInfo *info, guint8 *buf)
2831 {
2832         ArchDynCallInfo *dinfo = (ArchDynCallInfo*)info;
2833         MonoMethodSignature *sig = dinfo->sig;
2834         guint8 *ret = ((DynCallArgs*)buf)->ret;
2835         mgreg_t res = ((DynCallArgs*)buf)->res;
2836
2837         switch (mono_type_get_underlying_type (sig->ret)->type) {
2838         case MONO_TYPE_VOID:
2839                 *(gpointer*)ret = NULL;
2840                 break;
2841         case MONO_TYPE_STRING:
2842         case MONO_TYPE_CLASS:  
2843         case MONO_TYPE_ARRAY:
2844         case MONO_TYPE_SZARRAY:
2845         case MONO_TYPE_OBJECT:
2846         case MONO_TYPE_I:
2847         case MONO_TYPE_U:
2848         case MONO_TYPE_PTR:
2849                 *(gpointer*)ret = GREG_TO_PTR(res);
2850                 break;
2851         case MONO_TYPE_I1:
2852                 *(gint8*)ret = res;
2853                 break;
2854         case MONO_TYPE_U1:
2855         case MONO_TYPE_BOOLEAN:
2856                 *(guint8*)ret = res;
2857                 break;
2858         case MONO_TYPE_I2:
2859                 *(gint16*)ret = res;
2860                 break;
2861         case MONO_TYPE_U2:
2862         case MONO_TYPE_CHAR:
2863                 *(guint16*)ret = res;
2864                 break;
2865         case MONO_TYPE_I4:
2866                 *(gint32*)ret = res;
2867                 break;
2868         case MONO_TYPE_U4:
2869                 *(guint32*)ret = res;
2870                 break;
2871         case MONO_TYPE_I8:
2872                 *(gint64*)ret = res;
2873                 break;
2874         case MONO_TYPE_U8:
2875                 *(guint64*)ret = res;
2876                 break;
2877         case MONO_TYPE_GENERICINST:
2878                 if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
2879                         *(gpointer*)ret = GREG_TO_PTR(res);
2880                         break;
2881                 } else {
2882                         /* Fall through */
2883                 }
2884         case MONO_TYPE_VALUETYPE:
2885                 if (dinfo->cinfo->vtype_retaddr) {
2886                         /* Nothing to do */
2887                 } else {
2888                         ArgInfo *ainfo = &dinfo->cinfo->ret;
2889
2890                         g_assert (ainfo->storage == ArgValuetypeInReg);
2891
2892                         if (ainfo->pair_storage [0] != ArgNone) {
2893                                 g_assert (ainfo->pair_storage [0] == ArgInIReg);
2894                                 ((mgreg_t*)ret)[0] = res;
2895                         }
2896
2897                         g_assert (ainfo->pair_storage [1] == ArgNone);
2898                 }
2899                 break;
2900         default:
2901                 g_assert_not_reached ();
2902         }
2903 }
2904
2905 /* emit an exception if condition is fail */
2906 #define EMIT_COND_SYSTEM_EXCEPTION(cond,signed,exc_name)            \
2907         do {                                                        \
2908                 MonoInst *tins = mono_branch_optimize_exception_target (cfg, bb, exc_name); \
2909                 if (tins == NULL) {                                                                             \
2910                         mono_add_patch_info (cfg, code - cfg->native_code,   \
2911                                         MONO_PATCH_INFO_EXC, exc_name);  \
2912                         x86_branch32 (code, cond, 0, signed);               \
2913                 } else {        \
2914                         EMIT_COND_BRANCH (tins, cond, signed);  \
2915                 }                       \
2916         } while (0); 
2917
2918 #define EMIT_FPCOMPARE(code) do { \
2919         amd64_fcompp (code); \
2920         amd64_fnstsw (code); \
2921 } while (0); 
2922
2923 #define EMIT_SSE2_FPFUNC(code, op, dreg, sreg1) do { \
2924     amd64_movsd_membase_reg (code, AMD64_RSP, -8, (sreg1)); \
2925         amd64_fld_membase (code, AMD64_RSP, -8, TRUE); \
2926         amd64_ ##op (code); \
2927         amd64_fst_membase (code, AMD64_RSP, -8, TRUE, TRUE); \
2928         amd64_movsd_reg_membase (code, (dreg), AMD64_RSP, -8); \
2929 } while (0);
2930
2931 static guint8*
2932 emit_call_body (MonoCompile *cfg, guint8 *code, guint32 patch_type, gconstpointer data)
2933 {
2934         gboolean no_patch = FALSE;
2935
2936         /* 
2937          * FIXME: Add support for thunks
2938          */
2939         {
2940                 gboolean near_call = FALSE;
2941
2942                 /*
2943                  * Indirect calls are expensive so try to make a near call if possible.
2944                  * The caller memory is allocated by the code manager so it is 
2945                  * guaranteed to be at a 32 bit offset.
2946                  */
2947
2948                 if (patch_type != MONO_PATCH_INFO_ABS) {
2949                         /* The target is in memory allocated using the code manager */
2950                         near_call = TRUE;
2951
2952                         if ((patch_type == MONO_PATCH_INFO_METHOD) || (patch_type == MONO_PATCH_INFO_METHOD_JUMP)) {
2953                                 if (((MonoMethod*)data)->klass->image->aot_module)
2954                                         /* The callee might be an AOT method */
2955                                         near_call = FALSE;
2956                                 if (((MonoMethod*)data)->dynamic)
2957                                         /* The target is in malloc-ed memory */
2958                                         near_call = FALSE;
2959                         }
2960
2961                         if (patch_type == MONO_PATCH_INFO_INTERNAL_METHOD) {
2962                                 /* 
2963                                  * The call might go directly to a native function without
2964                                  * the wrapper.
2965                                  */
2966                                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (data);
2967                                 if (mi) {
2968                                         gconstpointer target = mono_icall_get_wrapper (mi);
2969                                         if ((((guint64)target) >> 32) != 0)
2970                                                 near_call = FALSE;
2971                                 }
2972                         }
2973                 }
2974                 else {
2975                         MonoJumpInfo *jinfo = NULL;
2976
2977                         if (cfg->abs_patches)
2978                                 jinfo = g_hash_table_lookup (cfg->abs_patches, data);
2979                         if (jinfo) {
2980                                 if (jinfo->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
2981                                         MonoJitICallInfo *mi = mono_find_jit_icall_by_name (jinfo->data.name);
2982                                         if (mi && (((guint64)mi->func) >> 32) == 0)
2983                                                 near_call = TRUE;
2984                                         no_patch = TRUE;
2985                                 } else {
2986                                         /* 
2987                                          * This is not really an optimization, but required because the
2988                                          * generic class init trampolines use R11 to pass the vtable.
2989                                          */
2990                                         near_call = TRUE;
2991                                 }
2992                         } else {
2993                                 MonoJitICallInfo *info = mono_find_jit_icall_by_addr (data);
2994                                 if (info) {
2995                                         if (info->func == info->wrapper) {
2996                                                 /* No wrapper */
2997                                                 if ((((guint64)info->func) >> 32) == 0)
2998                                                         near_call = TRUE;
2999                                         }
3000                                         else {
3001                                                 /* See the comment in mono_codegen () */
3002                                                 if ((info->name [0] != 'v') || (strstr (info->name, "ves_array_new_va_") == NULL && strstr (info->name, "ves_array_element_address_") == NULL))
3003                                                         near_call = TRUE;
3004                                         }
3005                                 }
3006                                 else if ((((guint64)data) >> 32) == 0) {
3007                                         near_call = TRUE;
3008                                         no_patch = TRUE;
3009                                 }
3010                         }
3011                 }
3012
3013                 if (cfg->method->dynamic)
3014                         /* These methods are allocated using malloc */
3015                         near_call = FALSE;
3016
3017 #ifdef MONO_ARCH_NOMAP32BIT
3018                 near_call = FALSE;
3019 #endif
3020 #if defined(__native_client__)
3021                 /* Always use near_call == TRUE for Native Client */
3022                 near_call = TRUE;
3023 #endif
3024                 /* The 64bit XEN kernel does not honour the MAP_32BIT flag. (#522894) */
3025                 if (optimize_for_xen)
3026                         near_call = FALSE;
3027
3028                 if (cfg->compile_aot) {
3029                         near_call = TRUE;
3030                         no_patch = TRUE;
3031                 }
3032
3033                 if (near_call) {
3034                         /* 
3035                          * Align the call displacement to an address divisible by 4 so it does
3036                          * not span cache lines. This is required for code patching to work on SMP
3037                          * systems.
3038                          */
3039                         if (!no_patch && ((guint32)(code + 1 - cfg->native_code) % 4) != 0) {
3040                                 guint32 pad_size = 4 - ((guint32)(code + 1 - cfg->native_code) % 4);
3041                                 amd64_padding (code, pad_size);
3042                         }
3043                         mono_add_patch_info (cfg, code - cfg->native_code, patch_type, data);
3044                         amd64_call_code (code, 0);
3045                 }
3046                 else {
3047                         mono_add_patch_info (cfg, code - cfg->native_code, patch_type, data);
3048                         amd64_set_reg_template (code, GP_SCRATCH_REG);
3049                         amd64_call_reg (code, GP_SCRATCH_REG);
3050                 }
3051         }
3052
3053         return code;
3054 }
3055
3056 static inline guint8*
3057 emit_call (MonoCompile *cfg, guint8 *code, guint32 patch_type, gconstpointer data, gboolean win64_adjust_stack)
3058 {
3059 #ifdef HOST_WIN32
3060         if (win64_adjust_stack)
3061                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 32);
3062 #endif
3063         code = emit_call_body (cfg, code, patch_type, data);
3064 #ifdef HOST_WIN32
3065         if (win64_adjust_stack)
3066                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 32);
3067 #endif  
3068         
3069         return code;
3070 }
3071
3072 static inline int
3073 store_membase_imm_to_store_membase_reg (int opcode)
3074 {
3075         switch (opcode) {
3076         case OP_STORE_MEMBASE_IMM:
3077                 return OP_STORE_MEMBASE_REG;
3078         case OP_STOREI4_MEMBASE_IMM:
3079                 return OP_STOREI4_MEMBASE_REG;
3080         case OP_STOREI8_MEMBASE_IMM:
3081                 return OP_STOREI8_MEMBASE_REG;
3082         }
3083
3084         return -1;
3085 }
3086
3087 #ifndef DISABLE_JIT
3088
3089 #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)))
3090
3091 /*
3092  * mono_arch_peephole_pass_1:
3093  *
3094  *   Perform peephole opts which should/can be performed before local regalloc
3095  */
3096 void
3097 mono_arch_peephole_pass_1 (MonoCompile *cfg, MonoBasicBlock *bb)
3098 {
3099         MonoInst *ins, *n;
3100
3101         MONO_BB_FOR_EACH_INS_SAFE (bb, n, ins) {
3102                 MonoInst *last_ins = ins->prev;
3103
3104                 switch (ins->opcode) {
3105                 case OP_ADD_IMM:
3106                 case OP_IADD_IMM:
3107                 case OP_LADD_IMM:
3108                         if ((ins->sreg1 < MONO_MAX_IREGS) && (ins->dreg >= MONO_MAX_IREGS) && (ins->inst_imm > 0)) {
3109                                 /* 
3110                                  * X86_LEA is like ADD, but doesn't have the
3111                                  * sreg1==dreg restriction. inst_imm > 0 is needed since LEA sign-extends 
3112                                  * its operand to 64 bit.
3113                                  */
3114                                 ins->opcode = OP_X86_LEA_MEMBASE;
3115                                 ins->inst_basereg = ins->sreg1;
3116                         }
3117                         break;
3118                 case OP_LXOR:
3119                 case OP_IXOR:
3120                         if ((ins->sreg1 == ins->sreg2) && (ins->sreg1 == ins->dreg)) {
3121                                 MonoInst *ins2;
3122
3123                                 /* 
3124                                  * Replace STORE_MEMBASE_IMM 0 with STORE_MEMBASE_REG since 
3125                                  * the latter has length 2-3 instead of 6 (reverse constant
3126                                  * propagation). These instruction sequences are very common
3127                                  * in the initlocals bblock.
3128                                  */
3129                                 for (ins2 = ins->next; ins2; ins2 = ins2->next) {
3130                                         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)) {
3131                                                 ins2->opcode = store_membase_imm_to_store_membase_reg (ins2->opcode);
3132                                                 ins2->sreg1 = ins->dreg;
3133                                         } 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)) {
3134                                                 /* Continue */
3135                                         } else if (((ins2->opcode == OP_ICONST) || (ins2->opcode == OP_I8CONST)) && (ins2->dreg == ins->dreg) && (ins2->inst_c0 == 0)) {
3136                                                 NULLIFY_INS (ins2);
3137                                                 /* Continue */
3138                                         } else {
3139                                                 break;
3140                                         }
3141                                 }
3142                         }
3143                         break;
3144                 case OP_COMPARE_IMM:
3145                 case OP_LCOMPARE_IMM:
3146                         /* OP_COMPARE_IMM (reg, 0) 
3147                          * --> 
3148                          * OP_AMD64_TEST_NULL (reg) 
3149                          */
3150                         if (!ins->inst_imm)
3151                                 ins->opcode = OP_AMD64_TEST_NULL;
3152                         break;
3153                 case OP_ICOMPARE_IMM:
3154                         if (!ins->inst_imm)
3155                                 ins->opcode = OP_X86_TEST_NULL;
3156                         break;
3157                 case OP_AMD64_ICOMPARE_MEMBASE_IMM:
3158                         /* 
3159                          * OP_STORE_MEMBASE_REG reg, offset(basereg)
3160                          * OP_X86_COMPARE_MEMBASE_IMM offset(basereg), imm
3161                          * -->
3162                          * OP_STORE_MEMBASE_REG reg, offset(basereg)
3163                          * OP_COMPARE_IMM reg, imm
3164                          *
3165                          * Note: if imm = 0 then OP_COMPARE_IMM replaced with OP_X86_TEST_NULL
3166                          */
3167                         if (last_ins && (last_ins->opcode == OP_STOREI4_MEMBASE_REG) &&
3168                             ins->inst_basereg == last_ins->inst_destbasereg &&
3169                             ins->inst_offset == last_ins->inst_offset) {
3170                                         ins->opcode = OP_ICOMPARE_IMM;
3171                                         ins->sreg1 = last_ins->sreg1;
3172
3173                                         /* check if we can remove cmp reg,0 with test null */
3174                                         if (!ins->inst_imm)
3175                                                 ins->opcode = OP_X86_TEST_NULL;
3176                                 }
3177
3178                         break;
3179                 }
3180
3181                 mono_peephole_ins (bb, ins);
3182         }
3183 }
3184
3185 void
3186 mono_arch_peephole_pass_2 (MonoCompile *cfg, MonoBasicBlock *bb)
3187 {
3188         MonoInst *ins, *n;
3189
3190         MONO_BB_FOR_EACH_INS_SAFE (bb, n, ins) {
3191                 switch (ins->opcode) {
3192                 case OP_ICONST:
3193                 case OP_I8CONST: {
3194                         /* reg = 0 -> XOR (reg, reg) */
3195                         /* XOR sets cflags on x86, so we cant do it always */
3196                         if (ins->inst_c0 == 0 && (!ins->next || (ins->next && INST_IGNORES_CFLAGS (ins->next->opcode)))) {
3197                                 ins->opcode = OP_LXOR;
3198                                 ins->sreg1 = ins->dreg;
3199                                 ins->sreg2 = ins->dreg;
3200                                 /* Fall through */
3201                         } else {
3202                                 break;
3203                         }
3204                 }
3205                 case OP_LXOR:
3206                         /*
3207                          * Use IXOR to avoid a rex prefix if possible. The cpu will sign extend the 
3208                          * 0 result into 64 bits.
3209                          */
3210                         if ((ins->sreg1 == ins->sreg2) && (ins->sreg1 == ins->dreg)) {
3211                                 ins->opcode = OP_IXOR;
3212                         }
3213                         /* Fall through */
3214                 case OP_IXOR:
3215                         if ((ins->sreg1 == ins->sreg2) && (ins->sreg1 == ins->dreg)) {
3216                                 MonoInst *ins2;
3217
3218                                 /* 
3219                                  * Replace STORE_MEMBASE_IMM 0 with STORE_MEMBASE_REG since 
3220                                  * the latter has length 2-3 instead of 6 (reverse constant
3221                                  * propagation). These instruction sequences are very common
3222                                  * in the initlocals bblock.
3223                                  */
3224                                 for (ins2 = ins->next; ins2; ins2 = ins2->next) {
3225                                         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)) {
3226                                                 ins2->opcode = store_membase_imm_to_store_membase_reg (ins2->opcode);
3227                                                 ins2->sreg1 = ins->dreg;
3228                                         } 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)) {
3229                                                 /* Continue */
3230                                         } else if (((ins2->opcode == OP_ICONST) || (ins2->opcode == OP_I8CONST)) && (ins2->dreg == ins->dreg) && (ins2->inst_c0 == 0)) {
3231                                                 NULLIFY_INS (ins2);
3232                                                 /* Continue */
3233                                         } else {
3234                                                 break;
3235                                         }
3236                                 }
3237                         }
3238                         break;
3239                 case OP_IADD_IMM:
3240                         if ((ins->inst_imm == 1) && (ins->dreg == ins->sreg1))
3241                                 ins->opcode = OP_X86_INC_REG;
3242                         break;
3243                 case OP_ISUB_IMM:
3244                         if ((ins->inst_imm == 1) && (ins->dreg == ins->sreg1))
3245                                 ins->opcode = OP_X86_DEC_REG;
3246                         break;
3247                 }
3248
3249                 mono_peephole_ins (bb, ins);
3250         }
3251 }
3252
3253 #define NEW_INS(cfg,ins,dest,op) do {   \
3254                 MONO_INST_NEW ((cfg), (dest), (op)); \
3255         (dest)->cil_code = (ins)->cil_code; \
3256         mono_bblock_insert_before_ins (bb, ins, (dest)); \
3257         } while (0)
3258
3259 /*
3260  * mono_arch_lowering_pass:
3261  *
3262  *  Converts complex opcodes into simpler ones so that each IR instruction
3263  * corresponds to one machine instruction.
3264  */
3265 void
3266 mono_arch_lowering_pass (MonoCompile *cfg, MonoBasicBlock *bb)
3267 {
3268         MonoInst *ins, *n, *temp;
3269
3270         /*
3271          * FIXME: Need to add more instructions, but the current machine 
3272          * description can't model some parts of the composite instructions like
3273          * cdq.
3274          */
3275         MONO_BB_FOR_EACH_INS_SAFE (bb, n, ins) {
3276                 switch (ins->opcode) {
3277                 case OP_DIV_IMM:
3278                 case OP_REM_IMM:
3279                 case OP_IDIV_IMM:
3280                 case OP_IDIV_UN_IMM:
3281                 case OP_IREM_UN_IMM:
3282                         mono_decompose_op_imm (cfg, bb, ins);
3283                         break;
3284                 case OP_IREM_IMM:
3285                         /* Keep the opcode if we can implement it efficiently */
3286                         if (!((ins->inst_imm > 0) && (mono_is_power_of_two (ins->inst_imm) != -1)))
3287                                 mono_decompose_op_imm (cfg, bb, ins);
3288                         break;
3289                 case OP_COMPARE_IMM:
3290                 case OP_LCOMPARE_IMM:
3291                         if (!amd64_is_imm32 (ins->inst_imm)) {
3292                                 NEW_INS (cfg, ins, temp, OP_I8CONST);
3293                                 temp->inst_c0 = ins->inst_imm;
3294                                 temp->dreg = mono_alloc_ireg (cfg);
3295                                 ins->opcode = OP_COMPARE;
3296                                 ins->sreg2 = temp->dreg;
3297                         }
3298                         break;
3299 #ifndef __mono_ilp32__
3300                 case OP_LOAD_MEMBASE:
3301 #endif
3302                 case OP_LOADI8_MEMBASE:
3303 #ifndef __native_client_codegen__
3304                 /*  Don't generate memindex opcodes (to simplify */
3305                 /*  read sandboxing) */
3306                         if (!amd64_is_imm32 (ins->inst_offset)) {
3307                                 NEW_INS (cfg, ins, temp, OP_I8CONST);
3308                                 temp->inst_c0 = ins->inst_offset;
3309                                 temp->dreg = mono_alloc_ireg (cfg);
3310                                 ins->opcode = OP_AMD64_LOADI8_MEMINDEX;
3311                                 ins->inst_indexreg = temp->dreg;
3312                         }
3313 #endif
3314                         break;
3315 #ifndef __mono_ilp32__
3316                 case OP_STORE_MEMBASE_IMM:
3317 #endif
3318                 case OP_STOREI8_MEMBASE_IMM:
3319                         if (!amd64_is_imm32 (ins->inst_imm)) {
3320                                 NEW_INS (cfg, ins, temp, OP_I8CONST);
3321                                 temp->inst_c0 = ins->inst_imm;
3322                                 temp->dreg = mono_alloc_ireg (cfg);
3323                                 ins->opcode = OP_STOREI8_MEMBASE_REG;
3324                                 ins->sreg1 = temp->dreg;
3325                         }
3326                         break;
3327 #ifdef MONO_ARCH_SIMD_INTRINSICS
3328                 case OP_EXPAND_I1: {
3329                                 int temp_reg1 = mono_alloc_ireg (cfg);
3330                                 int temp_reg2 = mono_alloc_ireg (cfg);
3331                                 int original_reg = ins->sreg1;
3332
3333                                 NEW_INS (cfg, ins, temp, OP_ICONV_TO_U1);
3334                                 temp->sreg1 = original_reg;
3335                                 temp->dreg = temp_reg1;
3336
3337                                 NEW_INS (cfg, ins, temp, OP_SHL_IMM);
3338                                 temp->sreg1 = temp_reg1;
3339                                 temp->dreg = temp_reg2;
3340                                 temp->inst_imm = 8;
3341
3342                                 NEW_INS (cfg, ins, temp, OP_LOR);
3343                                 temp->sreg1 = temp->dreg = temp_reg2;
3344                                 temp->sreg2 = temp_reg1;
3345
3346                                 ins->opcode = OP_EXPAND_I2;
3347                                 ins->sreg1 = temp_reg2;
3348                         }
3349                         break;
3350 #endif
3351                 default:
3352                         break;
3353                 }
3354         }
3355
3356         bb->max_vreg = cfg->next_vreg;
3357 }
3358
3359 static const int 
3360 branch_cc_table [] = {
3361         X86_CC_EQ, X86_CC_GE, X86_CC_GT, X86_CC_LE, X86_CC_LT,
3362         X86_CC_NE, X86_CC_GE, X86_CC_GT, X86_CC_LE, X86_CC_LT,
3363         X86_CC_O, X86_CC_NO, X86_CC_C, X86_CC_NC
3364 };
3365
3366 /* Maps CMP_... constants to X86_CC_... constants */
3367 static const int
3368 cc_table [] = {
3369         X86_CC_EQ, X86_CC_NE, X86_CC_LE, X86_CC_GE, X86_CC_LT, X86_CC_GT,
3370         X86_CC_LE, X86_CC_GE, X86_CC_LT, X86_CC_GT
3371 };
3372
3373 static const int
3374 cc_signed_table [] = {
3375         TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
3376         FALSE, FALSE, FALSE, FALSE
3377 };
3378
3379 /*#include "cprop.c"*/
3380
3381 static unsigned char*
3382 emit_float_to_int (MonoCompile *cfg, guchar *code, int dreg, int sreg, int size, gboolean is_signed)
3383 {
3384         amd64_sse_cvttsd2si_reg_reg (code, dreg, sreg);
3385
3386         if (size == 1)
3387                 amd64_widen_reg (code, dreg, dreg, is_signed, FALSE);
3388         else if (size == 2)
3389                 amd64_widen_reg (code, dreg, dreg, is_signed, TRUE);
3390         return code;
3391 }
3392
3393 static unsigned char*
3394 mono_emit_stack_alloc (MonoCompile *cfg, guchar *code, MonoInst* tree)
3395 {
3396         int sreg = tree->sreg1;
3397         int need_touch = FALSE;
3398
3399 #if defined(HOST_WIN32) || defined(MONO_ARCH_SIGSEGV_ON_ALTSTACK)
3400         if (!tree->flags & MONO_INST_INIT)
3401                 need_touch = TRUE;
3402 #endif
3403
3404         if (need_touch) {
3405                 guint8* br[5];
3406
3407                 /*
3408                  * Under Windows:
3409                  * If requested stack size is larger than one page,
3410                  * perform stack-touch operation
3411                  */
3412                 /*
3413                  * Generate stack probe code.
3414                  * Under Windows, it is necessary to allocate one page at a time,
3415                  * "touching" stack after each successful sub-allocation. This is
3416                  * because of the way stack growth is implemented - there is a
3417                  * guard page before the lowest stack page that is currently commited.
3418                  * Stack normally grows sequentially so OS traps access to the
3419                  * guard page and commits more pages when needed.
3420                  */
3421                 amd64_test_reg_imm (code, sreg, ~0xFFF);
3422                 br[0] = code; x86_branch8 (code, X86_CC_Z, 0, FALSE);
3423
3424                 br[2] = code; /* loop */
3425                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 0x1000);
3426                 amd64_test_membase_reg (code, AMD64_RSP, 0, AMD64_RSP);
3427                 amd64_alu_reg_imm (code, X86_SUB, sreg, 0x1000);
3428                 amd64_alu_reg_imm (code, X86_CMP, sreg, 0x1000);
3429                 br[3] = code; x86_branch8 (code, X86_CC_AE, 0, FALSE);
3430                 amd64_patch (br[3], br[2]);
3431                 amd64_test_reg_reg (code, sreg, sreg);
3432                 br[4] = code; x86_branch8 (code, X86_CC_Z, 0, FALSE);
3433                 amd64_alu_reg_reg (code, X86_SUB, AMD64_RSP, sreg);
3434
3435                 br[1] = code; x86_jump8 (code, 0);
3436
3437                 amd64_patch (br[0], code);
3438                 amd64_alu_reg_reg (code, X86_SUB, AMD64_RSP, sreg);
3439                 amd64_patch (br[1], code);
3440                 amd64_patch (br[4], code);
3441         }
3442         else
3443                 amd64_alu_reg_reg (code, X86_SUB, AMD64_RSP, tree->sreg1);
3444
3445         if (tree->flags & MONO_INST_INIT) {
3446                 int offset = 0;
3447                 if (tree->dreg != AMD64_RAX && sreg != AMD64_RAX) {
3448                         amd64_push_reg (code, AMD64_RAX);
3449                         offset += 8;
3450                 }
3451                 if (tree->dreg != AMD64_RCX && sreg != AMD64_RCX) {
3452                         amd64_push_reg (code, AMD64_RCX);
3453                         offset += 8;
3454                 }
3455                 if (tree->dreg != AMD64_RDI && sreg != AMD64_RDI) {
3456                         amd64_push_reg (code, AMD64_RDI);
3457                         offset += 8;
3458                 }
3459                 
3460                 amd64_shift_reg_imm (code, X86_SHR, sreg, 3);
3461                 if (sreg != AMD64_RCX)
3462                         amd64_mov_reg_reg (code, AMD64_RCX, sreg, 8);
3463                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
3464                                 
3465                 amd64_lea_membase (code, AMD64_RDI, AMD64_RSP, offset);
3466                 if (cfg->param_area && cfg->arch.no_pushes)
3467                         amd64_alu_reg_imm (code, X86_ADD, AMD64_RDI, cfg->param_area);
3468                 amd64_cld (code);
3469 #if defined(__default_codegen__)
3470                 amd64_prefix (code, X86_REP_PREFIX);
3471                 amd64_stosl (code);
3472 #elif defined(__native_client_codegen__)
3473                 /* NaCl stos pseudo-instruction */
3474                 amd64_codegen_pre(code);
3475                 /* First, clear the upper 32 bits of RDI (mov %edi, %edi)  */
3476                 amd64_mov_reg_reg (code, AMD64_RDI, AMD64_RDI, 4);
3477                 /* Add %r15 to %rdi using lea, condition flags unaffected. */
3478                 amd64_lea_memindex_size (code, AMD64_RDI, AMD64_R15, 0, AMD64_RDI, 0, 8);
3479                 amd64_prefix (code, X86_REP_PREFIX);
3480                 amd64_stosl (code);
3481                 amd64_codegen_post(code);
3482 #endif /* __native_client_codegen__ */
3483                 
3484                 if (tree->dreg != AMD64_RDI && sreg != AMD64_RDI)
3485                         amd64_pop_reg (code, AMD64_RDI);
3486                 if (tree->dreg != AMD64_RCX && sreg != AMD64_RCX)
3487                         amd64_pop_reg (code, AMD64_RCX);
3488                 if (tree->dreg != AMD64_RAX && sreg != AMD64_RAX)
3489                         amd64_pop_reg (code, AMD64_RAX);
3490         }
3491         return code;
3492 }
3493
3494 static guint8*
3495 emit_move_return_value (MonoCompile *cfg, MonoInst *ins, guint8 *code)
3496 {
3497         CallInfo *cinfo;
3498         guint32 quad;
3499
3500         /* Move return value to the target register */
3501         /* FIXME: do this in the local reg allocator */
3502         switch (ins->opcode) {
3503         case OP_CALL:
3504         case OP_CALL_REG:
3505         case OP_CALL_MEMBASE:
3506         case OP_LCALL:
3507         case OP_LCALL_REG:
3508         case OP_LCALL_MEMBASE:
3509                 g_assert (ins->dreg == AMD64_RAX);
3510                 break;
3511         case OP_FCALL:
3512         case OP_FCALL_REG:
3513         case OP_FCALL_MEMBASE:
3514                 if (((MonoCallInst*)ins)->signature->ret->type == MONO_TYPE_R4) {
3515                         amd64_sse_cvtss2sd_reg_reg (code, ins->dreg, AMD64_XMM0);
3516                 }
3517                 else {
3518                         if (ins->dreg != AMD64_XMM0)
3519                                 amd64_sse_movsd_reg_reg (code, ins->dreg, AMD64_XMM0);
3520                 }
3521                 break;
3522         case OP_VCALL:
3523         case OP_VCALL_REG:
3524         case OP_VCALL_MEMBASE:
3525         case OP_VCALL2:
3526         case OP_VCALL2_REG:
3527         case OP_VCALL2_MEMBASE:
3528                 cinfo = get_call_info (cfg->generic_sharing_context, cfg->mempool, ((MonoCallInst*)ins)->signature);
3529                 if (cinfo->ret.storage == ArgValuetypeInReg) {
3530                         MonoInst *loc = cfg->arch.vret_addr_loc;
3531
3532                         /* Load the destination address */
3533                         g_assert (loc->opcode == OP_REGOFFSET);
3534                         amd64_mov_reg_membase (code, AMD64_RCX, loc->inst_basereg, loc->inst_offset, sizeof(gpointer));
3535
3536                         for (quad = 0; quad < 2; quad ++) {
3537                                 switch (cinfo->ret.pair_storage [quad]) {
3538                                 case ArgInIReg:
3539                                         amd64_mov_membase_reg (code, AMD64_RCX, (quad * sizeof(mgreg_t)), cinfo->ret.pair_regs [quad], sizeof(mgreg_t));
3540                                         break;
3541                                 case ArgInFloatSSEReg:
3542                                         amd64_movss_membase_reg (code, AMD64_RCX, (quad * 8), cinfo->ret.pair_regs [quad]);
3543                                         break;
3544                                 case ArgInDoubleSSEReg:
3545                                         amd64_movsd_membase_reg (code, AMD64_RCX, (quad * 8), cinfo->ret.pair_regs [quad]);
3546                                         break;
3547                                 case ArgNone:
3548                                         break;
3549                                 default:
3550                                         NOT_IMPLEMENTED;
3551                                 }
3552                         }
3553                 }
3554                 break;
3555         }
3556
3557         return code;
3558 }
3559
3560 #endif /* DISABLE_JIT */
3561
3562 #ifdef __APPLE__
3563 static int tls_gs_offset;
3564 #endif
3565
3566 gboolean
3567 mono_amd64_have_tls_get (void)
3568 {
3569 #ifdef __APPLE__
3570         static gboolean have_tls_get = FALSE;
3571         static gboolean inited = FALSE;
3572         guint8 *ins;
3573
3574         if (inited)
3575                 return have_tls_get;
3576
3577         ins = (guint8*)pthread_getspecific;
3578
3579         /*
3580          * We're looking for these two instructions:
3581          *
3582          * mov    %gs:[offset](,%rdi,8),%rax
3583          * retq
3584          */
3585         have_tls_get = ins [0] == 0x65 &&
3586                        ins [1] == 0x48 &&
3587                        ins [2] == 0x8b &&
3588                        ins [3] == 0x04 &&
3589                        ins [4] == 0xfd &&
3590                        ins [6] == 0x00 &&
3591                        ins [7] == 0x00 &&
3592                        ins [8] == 0x00 &&
3593                        ins [9] == 0xc3;
3594
3595         inited = TRUE;
3596
3597         tls_gs_offset = ins[5];
3598
3599         return have_tls_get;
3600 #else
3601         return TRUE;
3602 #endif
3603 }
3604
3605 /*
3606  * mono_amd64_emit_tls_get:
3607  * @code: buffer to store code to
3608  * @dreg: hard register where to place the result
3609  * @tls_offset: offset info
3610  *
3611  * mono_amd64_emit_tls_get emits in @code the native code that puts in
3612  * the dreg register the item in the thread local storage identified
3613  * by tls_offset.
3614  *
3615  * Returns: a pointer to the end of the stored code
3616  */
3617 guint8*
3618 mono_amd64_emit_tls_get (guint8* code, int dreg, int tls_offset)
3619 {
3620 #ifdef HOST_WIN32
3621         g_assert (tls_offset < 64);
3622         x86_prefix (code, X86_GS_PREFIX);
3623         amd64_mov_reg_mem (code, dreg, (tls_offset * 8) + 0x1480, 8);
3624 #elif defined(__APPLE__)
3625         x86_prefix (code, X86_GS_PREFIX);
3626         amd64_mov_reg_mem (code, dreg, tls_gs_offset + (tls_offset * 8), 8);
3627 #else
3628         if (optimize_for_xen) {
3629                 x86_prefix (code, X86_FS_PREFIX);
3630                 amd64_mov_reg_mem (code, dreg, 0, 8);
3631                 amd64_mov_reg_membase (code, dreg, dreg, tls_offset, 8);
3632         } else {
3633                 x86_prefix (code, X86_FS_PREFIX);
3634                 amd64_mov_reg_mem (code, dreg, tls_offset, 8);
3635         }
3636 #endif
3637         return code;
3638 }
3639
3640 /*
3641  * emit_setup_lmf:
3642  *
3643  *   Emit code to initialize an LMF structure at LMF_OFFSET.
3644  */
3645 static guint8*
3646 emit_setup_lmf (MonoCompile *cfg, guint8 *code, gint32 lmf_offset, int cfa_offset)
3647 {
3648         int i;
3649
3650         /* 
3651          * The ip field is not set, the exception handling code will obtain it from the stack location pointed to by the sp field.
3652          */
3653         /* 
3654          * sp is saved right before calls but we need to save it here too so
3655          * async stack walks would work.
3656          */
3657         amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rsp), AMD64_RSP, 8);
3658         /* Skip method (only needed for trampoline LMF frames) */
3659         /* Save callee saved regs */
3660         for (i = 0; i < MONO_MAX_IREGS; ++i) {
3661                 int offset;
3662
3663                 switch (i) {
3664                 case AMD64_RBX: offset = G_STRUCT_OFFSET (MonoLMF, rbx); break;
3665                 case AMD64_RBP: offset = G_STRUCT_OFFSET (MonoLMF, rbp); break;
3666                 case AMD64_R12: offset = G_STRUCT_OFFSET (MonoLMF, r12); break;
3667                 case AMD64_R13: offset = G_STRUCT_OFFSET (MonoLMF, r13); break;
3668                 case AMD64_R14: offset = G_STRUCT_OFFSET (MonoLMF, r14); break;
3669 #ifndef __native_client_codegen__
3670                 case AMD64_R15: offset = G_STRUCT_OFFSET (MonoLMF, r15); break;
3671 #endif
3672 #ifdef HOST_WIN32
3673                 case AMD64_RDI: offset = G_STRUCT_OFFSET (MonoLMF, rdi); break;
3674                 case AMD64_RSI: offset = G_STRUCT_OFFSET (MonoLMF, rsi); break;
3675 #endif
3676                 default:
3677                         offset = -1;
3678                         break;
3679                 }
3680
3681                 if (offset != -1) {
3682                         amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + offset, i, 8);
3683                         if ((cfg->arch.omit_fp || (i != AMD64_RBP)) && cfa_offset != -1)
3684                                 mono_emit_unwind_op_offset (cfg, code, i, - (cfa_offset - (lmf_offset + offset)));
3685                 }
3686         }
3687
3688         /* These can't contain refs */
3689         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), SLOT_NOREF);
3690         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, lmf_addr), SLOT_NOREF);
3691         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, method), SLOT_NOREF);
3692         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rip), SLOT_NOREF);
3693         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rsp), SLOT_NOREF);
3694
3695         /* These are handled automatically by the stack marking code */
3696         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbx), SLOT_NOREF);
3697         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbp), SLOT_NOREF);
3698         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r12), SLOT_NOREF);
3699         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r13), SLOT_NOREF);
3700         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r14), SLOT_NOREF);
3701         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r15), SLOT_NOREF);
3702 #ifdef HOST_WIN32
3703         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rdi), SLOT_NOREF);
3704         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rsi), SLOT_NOREF);
3705 #endif
3706
3707         return code;
3708 }
3709
3710 /*
3711  * emit_save_lmf:
3712  *
3713  *   Emit code to push an LMF structure on the LMF stack.
3714  */
3715 static guint8*
3716 emit_save_lmf (MonoCompile *cfg, guint8 *code, gint32 lmf_offset, gboolean *args_clobbered)
3717 {
3718         if ((lmf_tls_offset != -1) && !optimize_for_xen) {
3719                 /*
3720                  * Optimized version which uses the mono_lmf TLS variable instead of 
3721                  * indirection through the mono_lmf_addr TLS variable.
3722                  */
3723                 /* %rax = previous_lmf */
3724                 x86_prefix (code, X86_FS_PREFIX);
3725                 amd64_mov_reg_mem (code, AMD64_RAX, lmf_tls_offset, 8);
3726
3727                 /* Save previous_lmf */
3728                 amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), AMD64_RAX, 8);
3729                 /* Set new lmf */
3730                 if (lmf_offset == 0) {
3731                         x86_prefix (code, X86_FS_PREFIX);
3732                         amd64_mov_mem_reg (code, lmf_tls_offset, cfg->frame_reg, 8);
3733                 } else {
3734                         amd64_lea_membase (code, AMD64_R11, cfg->frame_reg, lmf_offset);
3735                         x86_prefix (code, X86_FS_PREFIX);
3736                         amd64_mov_mem_reg (code, lmf_tls_offset, AMD64_R11, 8);
3737                 }
3738         } else {
3739                 if (lmf_addr_tls_offset != -1) {
3740                         /* Load lmf quicky using the FS register */
3741                         code = mono_amd64_emit_tls_get (code, AMD64_RAX, lmf_addr_tls_offset);
3742 #ifdef HOST_WIN32
3743                         /* The TLS key actually contains a pointer to the MonoJitTlsData structure */
3744                         /* FIXME: Add a separate key for LMF to avoid this */
3745                         amd64_alu_reg_imm (code, X86_ADD, AMD64_RAX, G_STRUCT_OFFSET (MonoJitTlsData, lmf));
3746 #endif
3747                 }
3748                 else {
3749                         /* 
3750                          * The call might clobber argument registers, but they are already
3751                          * saved to the stack/global regs.
3752                          */
3753                         if (args_clobbered)
3754                                 *args_clobbered = TRUE;
3755                         code = emit_call (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD, 
3756                                                           (gpointer)"mono_get_lmf_addr", TRUE);         
3757                 }
3758
3759                 /* Save lmf_addr */
3760                 amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, lmf_addr), AMD64_RAX, sizeof(gpointer));
3761                 /* Save previous_lmf */
3762                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RAX, 0, sizeof(gpointer));
3763                 amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), AMD64_R11, sizeof(gpointer));
3764                 /* Set new lmf */
3765                 amd64_lea_membase (code, AMD64_R11, cfg->frame_reg, lmf_offset);
3766                 amd64_mov_membase_reg (code, AMD64_RAX, 0, AMD64_R11, sizeof(gpointer));
3767         }
3768
3769         return code;
3770 }
3771
3772 /*
3773  * emit_save_lmf:
3774  *
3775  *   Emit code to pop an LMF structure from the LMF stack.
3776  */
3777 static guint8*
3778 emit_restore_lmf (MonoCompile *cfg, guint8 *code, gint32 lmf_offset)
3779 {
3780         if ((lmf_tls_offset != -1) && !optimize_for_xen) {
3781                 /*
3782                  * Optimized version which uses the mono_lmf TLS variable instead of indirection
3783                  * through the mono_lmf_addr TLS variable.
3784                  */
3785                 /* reg = previous_lmf */
3786                 amd64_mov_reg_membase (code, AMD64_R11, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), sizeof(gpointer));
3787                 x86_prefix (code, X86_FS_PREFIX);
3788                 amd64_mov_mem_reg (code, lmf_tls_offset, AMD64_R11, 8);
3789         } else {
3790                 /* Restore previous lmf */
3791                 amd64_mov_reg_membase (code, AMD64_RCX, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), sizeof(gpointer));
3792                 amd64_mov_reg_membase (code, AMD64_R11, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, lmf_addr), sizeof(gpointer));
3793                 amd64_mov_membase_reg (code, AMD64_R11, 0, AMD64_RCX, sizeof(gpointer));
3794         }
3795
3796         return code;
3797 }
3798
3799 #define REAL_PRINT_REG(text,reg) \
3800 mono_assert (reg >= 0); \
3801 amd64_push_reg (code, AMD64_RAX); \
3802 amd64_push_reg (code, AMD64_RDX); \
3803 amd64_push_reg (code, AMD64_RCX); \
3804 amd64_push_reg (code, reg); \
3805 amd64_push_imm (code, reg); \
3806 amd64_push_imm (code, text " %d %p\n"); \
3807 amd64_mov_reg_imm (code, AMD64_RAX, printf); \
3808 amd64_call_reg (code, AMD64_RAX); \
3809 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 3*4); \
3810 amd64_pop_reg (code, AMD64_RCX); \
3811 amd64_pop_reg (code, AMD64_RDX); \
3812 amd64_pop_reg (code, AMD64_RAX);
3813
3814 /* benchmark and set based on cpu */
3815 #define LOOP_ALIGNMENT 8
3816 #define bb_is_loop_start(bb) ((bb)->loop_body_start && (bb)->nesting)
3817
3818 #ifndef DISABLE_JIT
3819 void
3820 mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb)
3821 {
3822         MonoInst *ins;
3823         MonoCallInst *call;
3824         guint offset;
3825         guint8 *code = cfg->native_code + cfg->code_len;
3826         MonoInst *last_ins = NULL;
3827         guint last_offset = 0;
3828         int max_len;
3829
3830         /* Fix max_offset estimate for each successor bb */
3831         if (cfg->opt & MONO_OPT_BRANCH) {
3832                 int current_offset = cfg->code_len;
3833                 MonoBasicBlock *current_bb;
3834                 for (current_bb = bb; current_bb != NULL; current_bb = current_bb->next_bb) {
3835                         current_bb->max_offset = current_offset;
3836                         current_offset += current_bb->max_length;
3837                 }
3838         }
3839
3840         if (cfg->opt & MONO_OPT_LOOP) {
3841                 int pad, align = LOOP_ALIGNMENT;
3842                 /* set alignment depending on cpu */
3843                 if (bb_is_loop_start (bb) && (pad = (cfg->code_len & (align - 1)))) {
3844                         pad = align - pad;
3845                         /*g_print ("adding %d pad at %x to loop in %s\n", pad, cfg->code_len, cfg->method->name);*/
3846                         amd64_padding (code, pad);
3847                         cfg->code_len += pad;
3848                         bb->native_offset = cfg->code_len;
3849                 }
3850         }
3851
3852 #if defined(__native_client_codegen__)
3853         /* For Native Client, all indirect call/jump targets must be */
3854         /* 32-byte aligned.  Exception handler blocks are jumped to  */
3855         /* indirectly as well.                                       */
3856         gboolean bb_needs_alignment = (bb->flags & BB_INDIRECT_JUMP_TARGET) ||
3857                                       (bb->flags & BB_EXCEPTION_HANDLER);
3858
3859         if ( bb_needs_alignment && ((cfg->code_len & kNaClAlignmentMask) != 0)) {
3860                 int pad = kNaClAlignment - (cfg->code_len & kNaClAlignmentMask);
3861                 if (pad != kNaClAlignment) code = mono_arch_nacl_pad(code, pad);
3862                 cfg->code_len += pad;
3863                 bb->native_offset = cfg->code_len;
3864         }
3865 #endif  /*__native_client_codegen__*/
3866
3867         if (cfg->verbose_level > 2)
3868                 g_print ("Basic block %d starting at offset 0x%x\n", bb->block_num, bb->native_offset);
3869
3870         if (cfg->prof_options & MONO_PROFILE_COVERAGE) {
3871                 MonoProfileCoverageInfo *cov = cfg->coverage_info;
3872                 g_assert (!cfg->compile_aot);
3873
3874                 cov->data [bb->dfn].cil_code = bb->cil_code;
3875                 amd64_mov_reg_imm (code, AMD64_R11, (guint64)&cov->data [bb->dfn].count);
3876                 /* this is not thread save, but good enough */
3877                 amd64_inc_membase (code, AMD64_R11, 0);
3878         }
3879
3880         offset = code - cfg->native_code;
3881
3882         mono_debug_open_block (cfg, bb, offset);
3883
3884     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)
3885                 x86_breakpoint (code);
3886
3887         MONO_BB_FOR_EACH_INS (bb, ins) {
3888                 offset = code - cfg->native_code;
3889
3890                 max_len = ((guint8 *)ins_get_spec (ins->opcode))[MONO_INST_LEN];
3891
3892 #define EXTRA_CODE_SPACE (NACL_SIZE (16, 16 + kNaClAlignment))
3893
3894                 if (G_UNLIKELY (offset > (cfg->code_size - max_len - EXTRA_CODE_SPACE))) {
3895                         cfg->code_size *= 2;
3896                         cfg->native_code = mono_realloc_native_code(cfg);
3897                         code = cfg->native_code + offset;
3898                         cfg->stat_code_reallocs++;
3899                 }
3900
3901                 if (cfg->debug_info)
3902                         mono_debug_record_line_number (cfg, ins, offset);
3903
3904                 switch (ins->opcode) {
3905                 case OP_BIGMUL:
3906                         amd64_mul_reg (code, ins->sreg2, TRUE);
3907                         break;
3908                 case OP_BIGMUL_UN:
3909                         amd64_mul_reg (code, ins->sreg2, FALSE);
3910                         break;
3911                 case OP_X86_SETEQ_MEMBASE:
3912                         amd64_set_membase (code, X86_CC_EQ, ins->inst_basereg, ins->inst_offset, TRUE);
3913                         break;
3914                 case OP_STOREI1_MEMBASE_IMM:
3915                         amd64_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 1);
3916                         break;
3917                 case OP_STOREI2_MEMBASE_IMM:
3918                         amd64_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 2);
3919                         break;
3920                 case OP_STOREI4_MEMBASE_IMM:
3921                         amd64_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 4);
3922                         break;
3923                 case OP_STOREI1_MEMBASE_REG:
3924                         amd64_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 1);
3925                         break;
3926                 case OP_STOREI2_MEMBASE_REG:
3927                         amd64_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 2);
3928                         break;
3929                 /* In AMD64 NaCl, pointers are 4 bytes, */
3930                 /*  so STORE_* != STOREI8_*. Likewise below. */
3931                 case OP_STORE_MEMBASE_REG:
3932                         amd64_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, sizeof(gpointer));
3933                         break;
3934                 case OP_STOREI8_MEMBASE_REG:
3935                         amd64_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 8);
3936                         break;
3937                 case OP_STOREI4_MEMBASE_REG:
3938                         amd64_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 4);
3939                         break;
3940                 case OP_STORE_MEMBASE_IMM:
3941 #ifndef __native_client_codegen__
3942                         /* In NaCl, this could be a PCONST type, which could */
3943                         /* mean a pointer type was copied directly into the  */
3944                         /* lower 32-bits of inst_imm, so for InvalidPtr==-1  */
3945                         /* the value would be 0x00000000FFFFFFFF which is    */
3946                         /* not proper for an imm32 unless you cast it.       */
3947                         g_assert (amd64_is_imm32 (ins->inst_imm));
3948 #endif
3949                         amd64_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, (gint32)ins->inst_imm, sizeof(gpointer));
3950                         break;
3951                 case OP_STOREI8_MEMBASE_IMM:
3952                         g_assert (amd64_is_imm32 (ins->inst_imm));
3953                         amd64_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 8);
3954                         break;
3955                 case OP_LOAD_MEM:
3956 #ifdef __mono_ilp32__
3957                         /* In ILP32, pointers are 4 bytes, so separate these */
3958                         /* cases, use literal 8 below where we really want 8 */
3959                         amd64_mov_reg_imm (code, ins->dreg, ins->inst_imm);
3960                         amd64_mov_reg_membase (code, ins->dreg, ins->dreg, 0, sizeof(gpointer));
3961                         break;
3962 #endif
3963                 case OP_LOADI8_MEM:
3964                         // FIXME: Decompose this earlier
3965                         if (amd64_is_imm32 (ins->inst_imm))
3966                                 amd64_mov_reg_mem (code, ins->dreg, ins->inst_imm, 8);
3967                         else {
3968                                 amd64_mov_reg_imm (code, ins->dreg, ins->inst_imm);
3969                                 amd64_mov_reg_membase (code, ins->dreg, ins->dreg, 0, 8);
3970                         }
3971                         break;
3972                 case OP_LOADI4_MEM:
3973                         amd64_mov_reg_imm (code, ins->dreg, ins->inst_imm);
3974                         amd64_movsxd_reg_membase (code, ins->dreg, ins->dreg, 0);
3975                         break;
3976                 case OP_LOADU4_MEM:
3977                         // FIXME: Decompose this earlier
3978                         if (amd64_is_imm32 (ins->inst_imm))
3979                                 amd64_mov_reg_mem (code, ins->dreg, ins->inst_imm, 4);
3980                         else {
3981                                 amd64_mov_reg_imm (code, ins->dreg, ins->inst_imm);
3982                                 amd64_mov_reg_membase (code, ins->dreg, ins->dreg, 0, 4);
3983                         }
3984                         break;
3985                 case OP_LOADU1_MEM:
3986                         amd64_mov_reg_imm (code, ins->dreg, ins->inst_imm);
3987                         amd64_widen_membase (code, ins->dreg, ins->dreg, 0, FALSE, FALSE);
3988                         break;
3989                 case OP_LOADU2_MEM:
3990                         /* For NaCl, pointers are 4 bytes, so separate these */
3991                         /* cases, use literal 8 below where we really want 8 */
3992                         amd64_mov_reg_imm (code, ins->dreg, ins->inst_imm);
3993                         amd64_widen_membase (code, ins->dreg, ins->dreg, 0, FALSE, TRUE);
3994                         break;
3995                 case OP_LOAD_MEMBASE:
3996                         g_assert (amd64_is_imm32 (ins->inst_offset));
3997                         amd64_mov_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, sizeof(gpointer));
3998                         break;
3999                 case OP_LOADI8_MEMBASE:
4000                         /* Use literal 8 instead of sizeof pointer or */
4001                         /* register, we really want 8 for this opcode */
4002                         g_assert (amd64_is_imm32 (ins->inst_offset));
4003                         amd64_mov_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, 8);
4004                         break;
4005                 case OP_LOADI4_MEMBASE:
4006                         amd64_movsxd_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset);
4007                         break;
4008                 case OP_LOADU4_MEMBASE:
4009                         amd64_mov_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, 4);
4010                         break;
4011                 case OP_LOADU1_MEMBASE:
4012                         /* The cpu zero extends the result into 64 bits */
4013                         amd64_widen_membase_size (code, ins->dreg, ins->inst_basereg, ins->inst_offset, FALSE, FALSE, 4);
4014                         break;
4015                 case OP_LOADI1_MEMBASE:
4016                         amd64_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, TRUE, FALSE);
4017                         break;
4018                 case OP_LOADU2_MEMBASE:
4019                         /* The cpu zero extends the result into 64 bits */
4020                         amd64_widen_membase_size (code, ins->dreg, ins->inst_basereg, ins->inst_offset, FALSE, TRUE, 4);
4021                         break;
4022                 case OP_LOADI2_MEMBASE:
4023                         amd64_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, TRUE, TRUE);
4024                         break;
4025                 case OP_AMD64_LOADI8_MEMINDEX:
4026                         amd64_mov_reg_memindex_size (code, ins->dreg, ins->inst_basereg, 0, ins->inst_indexreg, 0, 8);
4027                         break;
4028                 case OP_LCONV_TO_I1:
4029                 case OP_ICONV_TO_I1:
4030                 case OP_SEXT_I1:
4031                         amd64_widen_reg (code, ins->dreg, ins->sreg1, TRUE, FALSE);
4032                         break;
4033                 case OP_LCONV_TO_I2:
4034                 case OP_ICONV_TO_I2:
4035                 case OP_SEXT_I2:
4036                         amd64_widen_reg (code, ins->dreg, ins->sreg1, TRUE, TRUE);
4037                         break;
4038                 case OP_LCONV_TO_U1:
4039                 case OP_ICONV_TO_U1:
4040                         amd64_widen_reg (code, ins->dreg, ins->sreg1, FALSE, FALSE);
4041                         break;
4042                 case OP_LCONV_TO_U2:
4043                 case OP_ICONV_TO_U2:
4044                         amd64_widen_reg (code, ins->dreg, ins->sreg1, FALSE, TRUE);
4045                         break;
4046                 case OP_ZEXT_I4:
4047                         /* Clean out the upper word */
4048                         amd64_mov_reg_reg_size (code, ins->dreg, ins->sreg1, 4);
4049                         break;
4050                 case OP_SEXT_I4:
4051                         amd64_movsxd_reg_reg (code, ins->dreg, ins->sreg1);
4052                         break;
4053                 case OP_COMPARE:
4054                 case OP_LCOMPARE:
4055                         amd64_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2);
4056                         break;
4057                 case OP_COMPARE_IMM:
4058 #if defined(__mono_ilp32__)
4059                         /* Comparison of pointer immediates should be 4 bytes to avoid sign-extend problems */
4060                         g_assert (amd64_is_imm32 (ins->inst_imm));
4061                         amd64_alu_reg_imm_size (code, X86_CMP, ins->sreg1, ins->inst_imm, 4);
4062                         break;
4063 #endif
4064                 case OP_LCOMPARE_IMM:
4065                         g_assert (amd64_is_imm32 (ins->inst_imm));
4066                         amd64_alu_reg_imm (code, X86_CMP, ins->sreg1, ins->inst_imm);
4067                         break;
4068                 case OP_X86_COMPARE_REG_MEMBASE:
4069                         amd64_alu_reg_membase (code, X86_CMP, ins->sreg1, ins->sreg2, ins->inst_offset);
4070                         break;
4071                 case OP_X86_TEST_NULL:
4072                         amd64_test_reg_reg_size (code, ins->sreg1, ins->sreg1, 4);
4073                         break;
4074                 case OP_AMD64_TEST_NULL:
4075                         amd64_test_reg_reg (code, ins->sreg1, ins->sreg1);
4076                         break;
4077
4078                 case OP_X86_ADD_REG_MEMBASE:
4079                         amd64_alu_reg_membase_size (code, X86_ADD, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
4080                         break;
4081                 case OP_X86_SUB_REG_MEMBASE:
4082                         amd64_alu_reg_membase_size (code, X86_SUB, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
4083                         break;
4084                 case OP_X86_AND_REG_MEMBASE:
4085                         amd64_alu_reg_membase_size (code, X86_AND, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
4086                         break;
4087                 case OP_X86_OR_REG_MEMBASE:
4088                         amd64_alu_reg_membase_size (code, X86_OR, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
4089                         break;
4090                 case OP_X86_XOR_REG_MEMBASE:
4091                         amd64_alu_reg_membase_size (code, X86_XOR, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
4092                         break;
4093
4094                 case OP_X86_ADD_MEMBASE_IMM:
4095                         /* FIXME: Make a 64 version too */
4096                         amd64_alu_membase_imm_size (code, X86_ADD, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
4097                         break;
4098                 case OP_X86_SUB_MEMBASE_IMM:
4099                         g_assert (amd64_is_imm32 (ins->inst_imm));
4100                         amd64_alu_membase_imm_size (code, X86_SUB, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
4101                         break;
4102                 case OP_X86_AND_MEMBASE_IMM:
4103                         g_assert (amd64_is_imm32 (ins->inst_imm));
4104                         amd64_alu_membase_imm_size (code, X86_AND, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
4105                         break;
4106                 case OP_X86_OR_MEMBASE_IMM:
4107                         g_assert (amd64_is_imm32 (ins->inst_imm));
4108                         amd64_alu_membase_imm_size (code, X86_OR, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
4109                         break;
4110                 case OP_X86_XOR_MEMBASE_IMM:
4111                         g_assert (amd64_is_imm32 (ins->inst_imm));
4112                         amd64_alu_membase_imm_size (code, X86_XOR, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
4113                         break;
4114                 case OP_X86_ADD_MEMBASE_REG:
4115                         amd64_alu_membase_reg_size (code, X86_ADD, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
4116                         break;
4117                 case OP_X86_SUB_MEMBASE_REG:
4118                         amd64_alu_membase_reg_size (code, X86_SUB, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
4119                         break;
4120                 case OP_X86_AND_MEMBASE_REG:
4121                         amd64_alu_membase_reg_size (code, X86_AND, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
4122                         break;
4123                 case OP_X86_OR_MEMBASE_REG:
4124                         amd64_alu_membase_reg_size (code, X86_OR, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
4125                         break;
4126                 case OP_X86_XOR_MEMBASE_REG:
4127                         amd64_alu_membase_reg_size (code, X86_XOR, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
4128                         break;
4129                 case OP_X86_INC_MEMBASE:
4130                         amd64_inc_membase_size (code, ins->inst_basereg, ins->inst_offset, 4);
4131                         break;
4132                 case OP_X86_INC_REG:
4133                         amd64_inc_reg_size (code, ins->dreg, 4);
4134                         break;
4135                 case OP_X86_DEC_MEMBASE:
4136                         amd64_dec_membase_size (code, ins->inst_basereg, ins->inst_offset, 4);
4137                         break;
4138                 case OP_X86_DEC_REG:
4139                         amd64_dec_reg_size (code, ins->dreg, 4);
4140                         break;
4141                 case OP_X86_MUL_REG_MEMBASE:
4142                 case OP_X86_MUL_MEMBASE_REG:
4143                         amd64_imul_reg_membase_size (code, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
4144                         break;
4145                 case OP_AMD64_ICOMPARE_MEMBASE_REG:
4146                         amd64_alu_membase_reg_size (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
4147                         break;
4148                 case OP_AMD64_ICOMPARE_MEMBASE_IMM:
4149                         amd64_alu_membase_imm_size (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
4150                         break;
4151                 case OP_AMD64_COMPARE_MEMBASE_REG:
4152                         amd64_alu_membase_reg_size (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
4153                         break;
4154                 case OP_AMD64_COMPARE_MEMBASE_IMM:
4155                         g_assert (amd64_is_imm32 (ins->inst_imm));
4156                         amd64_alu_membase_imm_size (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
4157                         break;
4158                 case OP_X86_COMPARE_MEMBASE8_IMM:
4159                         amd64_alu_membase8_imm_size (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
4160                         break;
4161                 case OP_AMD64_ICOMPARE_REG_MEMBASE:
4162                         amd64_alu_reg_membase_size (code, X86_CMP, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
4163                         break;
4164                 case OP_AMD64_COMPARE_REG_MEMBASE:
4165                         amd64_alu_reg_membase_size (code, X86_CMP, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
4166                         break;
4167
4168                 case OP_AMD64_ADD_REG_MEMBASE:
4169                         amd64_alu_reg_membase_size (code, X86_ADD, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
4170                         break;
4171                 case OP_AMD64_SUB_REG_MEMBASE:
4172                         amd64_alu_reg_membase_size (code, X86_SUB, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
4173                         break;
4174                 case OP_AMD64_AND_REG_MEMBASE:
4175                         amd64_alu_reg_membase_size (code, X86_AND, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
4176                         break;
4177                 case OP_AMD64_OR_REG_MEMBASE:
4178                         amd64_alu_reg_membase_size (code, X86_OR, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
4179                         break;
4180                 case OP_AMD64_XOR_REG_MEMBASE:
4181                         amd64_alu_reg_membase_size (code, X86_XOR, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
4182                         break;
4183
4184                 case OP_AMD64_ADD_MEMBASE_REG:
4185                         amd64_alu_membase_reg_size (code, X86_ADD, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
4186                         break;
4187                 case OP_AMD64_SUB_MEMBASE_REG:
4188                         amd64_alu_membase_reg_size (code, X86_SUB, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
4189                         break;
4190                 case OP_AMD64_AND_MEMBASE_REG:
4191                         amd64_alu_membase_reg_size (code, X86_AND, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
4192                         break;
4193                 case OP_AMD64_OR_MEMBASE_REG:
4194                         amd64_alu_membase_reg_size (code, X86_OR, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
4195                         break;
4196                 case OP_AMD64_XOR_MEMBASE_REG:
4197                         amd64_alu_membase_reg_size (code, X86_XOR, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
4198                         break;
4199
4200                 case OP_AMD64_ADD_MEMBASE_IMM:
4201                         g_assert (amd64_is_imm32 (ins->inst_imm));
4202                         amd64_alu_membase_imm_size (code, X86_ADD, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
4203                         break;
4204                 case OP_AMD64_SUB_MEMBASE_IMM:
4205                         g_assert (amd64_is_imm32 (ins->inst_imm));
4206                         amd64_alu_membase_imm_size (code, X86_SUB, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
4207                         break;
4208                 case OP_AMD64_AND_MEMBASE_IMM:
4209                         g_assert (amd64_is_imm32 (ins->inst_imm));
4210                         amd64_alu_membase_imm_size (code, X86_AND, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
4211                         break;
4212                 case OP_AMD64_OR_MEMBASE_IMM:
4213                         g_assert (amd64_is_imm32 (ins->inst_imm));
4214                         amd64_alu_membase_imm_size (code, X86_OR, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
4215                         break;
4216                 case OP_AMD64_XOR_MEMBASE_IMM:
4217                         g_assert (amd64_is_imm32 (ins->inst_imm));
4218                         amd64_alu_membase_imm_size (code, X86_XOR, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
4219                         break;
4220
4221                 case OP_BREAK:
4222                         amd64_breakpoint (code);
4223                         break;
4224                 case OP_RELAXED_NOP:
4225                         x86_prefix (code, X86_REP_PREFIX);
4226                         x86_nop (code);
4227                         break;
4228                 case OP_HARD_NOP:
4229                         x86_nop (code);
4230                         break;
4231                 case OP_NOP:
4232                 case OP_DUMMY_USE:
4233                 case OP_DUMMY_STORE:
4234                 case OP_NOT_REACHED:
4235                 case OP_NOT_NULL:
4236                         break;
4237                 case OP_SEQ_POINT: {
4238                         int i;
4239
4240                         /* 
4241                          * Read from the single stepping trigger page. This will cause a
4242                          * SIGSEGV when single stepping is enabled.
4243                          * We do this _before_ the breakpoint, so single stepping after
4244                          * a breakpoint is hit will step to the next IL offset.
4245                          */
4246                         if (ins->flags & MONO_INST_SINGLE_STEP_LOC) {
4247                                 MonoInst *var = cfg->arch.ss_trigger_page_var;
4248
4249                                 amd64_mov_reg_membase (code, AMD64_R11, var->inst_basereg, var->inst_offset, 8);
4250                                 amd64_alu_membase_imm_size (code, X86_CMP, AMD64_R11, 0, 0, 4);
4251                         }
4252
4253                         /* 
4254                          * This is the address which is saved in seq points, 
4255                          */
4256                         mono_add_seq_point (cfg, bb, ins, code - cfg->native_code);
4257
4258                         if (cfg->compile_aot) {
4259                                 guint32 offset = code - cfg->native_code;
4260                                 guint32 val;
4261                                 MonoInst *info_var = cfg->arch.seq_point_info_var;
4262
4263                                 /* Load info var */
4264                                 amd64_mov_reg_membase (code, AMD64_R11, info_var->inst_basereg, info_var->inst_offset, 8);
4265                                 val = ((offset) * sizeof (guint8*)) + G_STRUCT_OFFSET (SeqPointInfo, bp_addrs);
4266                                 /* Load the info->bp_addrs [offset], which is either a valid address or the address of a trigger page */
4267                                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, val, 8);
4268                                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 0, 8);
4269                         } else {
4270                                 /* 
4271                                  * A placeholder for a possible breakpoint inserted by
4272                                  * mono_arch_set_breakpoint ().
4273                                  */
4274                                 for (i = 0; i < breakpoint_size; ++i)
4275                                         x86_nop (code);
4276                         }
4277                         /*
4278                          * Add an additional nop so skipping the bp doesn't cause the ip to point
4279                          * to another IL offset.
4280                          */
4281                         x86_nop (code);
4282                         break;
4283                 }
4284                 case OP_ADDCC:
4285                 case OP_LADDCC:
4286                 case OP_LADD:
4287                         amd64_alu_reg_reg (code, X86_ADD, ins->sreg1, ins->sreg2);
4288                         break;
4289                 case OP_ADC:
4290                         amd64_alu_reg_reg (code, X86_ADC, ins->sreg1, ins->sreg2);
4291                         break;
4292                 case OP_ADD_IMM:
4293                 case OP_LADD_IMM:
4294                         g_assert (amd64_is_imm32 (ins->inst_imm));
4295                         amd64_alu_reg_imm (code, X86_ADD, ins->dreg, ins->inst_imm);
4296                         break;
4297                 case OP_ADC_IMM:
4298                         g_assert (amd64_is_imm32 (ins->inst_imm));
4299                         amd64_alu_reg_imm (code, X86_ADC, ins->dreg, ins->inst_imm);
4300                         break;
4301                 case OP_SUBCC:
4302                 case OP_LSUBCC:
4303                 case OP_LSUB:
4304                         amd64_alu_reg_reg (code, X86_SUB, ins->sreg1, ins->sreg2);
4305                         break;
4306                 case OP_SBB:
4307                         amd64_alu_reg_reg (code, X86_SBB, ins->sreg1, ins->sreg2);
4308                         break;
4309                 case OP_SUB_IMM:
4310                 case OP_LSUB_IMM:
4311                         g_assert (amd64_is_imm32 (ins->inst_imm));
4312                         amd64_alu_reg_imm (code, X86_SUB, ins->dreg, ins->inst_imm);
4313                         break;
4314                 case OP_SBB_IMM:
4315                         g_assert (amd64_is_imm32 (ins->inst_imm));
4316                         amd64_alu_reg_imm (code, X86_SBB, ins->dreg, ins->inst_imm);
4317                         break;
4318                 case OP_LAND:
4319                         amd64_alu_reg_reg (code, X86_AND, ins->sreg1, ins->sreg2);
4320                         break;
4321                 case OP_AND_IMM:
4322                 case OP_LAND_IMM:
4323                         g_assert (amd64_is_imm32 (ins->inst_imm));
4324                         amd64_alu_reg_imm (code, X86_AND, ins->sreg1, ins->inst_imm);
4325                         break;
4326                 case OP_LMUL:
4327                         amd64_imul_reg_reg (code, ins->sreg1, ins->sreg2);
4328                         break;
4329                 case OP_MUL_IMM:
4330                 case OP_LMUL_IMM:
4331                 case OP_IMUL_IMM: {
4332                         guint32 size = (ins->opcode == OP_IMUL_IMM) ? 4 : 8;
4333                         
4334                         switch (ins->inst_imm) {
4335                         case 2:
4336                                 /* MOV r1, r2 */
4337                                 /* ADD r1, r1 */
4338                                 if (ins->dreg != ins->sreg1)
4339                                         amd64_mov_reg_reg (code, ins->dreg, ins->sreg1, size);
4340                                 amd64_alu_reg_reg (code, X86_ADD, ins->dreg, ins->dreg);
4341                                 break;
4342                         case 3:
4343                                 /* LEA r1, [r2 + r2*2] */
4344                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 1);
4345                                 break;
4346                         case 5:
4347                                 /* LEA r1, [r2 + r2*4] */
4348                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 2);
4349                                 break;
4350                         case 6:
4351                                 /* LEA r1, [r2 + r2*2] */
4352                                 /* ADD r1, r1          */
4353                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 1);
4354                                 amd64_alu_reg_reg (code, X86_ADD, ins->dreg, ins->dreg);
4355                                 break;
4356                         case 9:
4357                                 /* LEA r1, [r2 + r2*8] */
4358                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 3);
4359                                 break;
4360                         case 10:
4361                                 /* LEA r1, [r2 + r2*4] */
4362                                 /* ADD r1, r1          */
4363                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 2);
4364                                 amd64_alu_reg_reg (code, X86_ADD, ins->dreg, ins->dreg);
4365                                 break;
4366                         case 12:
4367                                 /* LEA r1, [r2 + r2*2] */
4368                                 /* SHL r1, 2           */
4369                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 1);
4370                                 amd64_shift_reg_imm (code, X86_SHL, ins->dreg, 2);
4371                                 break;
4372                         case 25:
4373                                 /* LEA r1, [r2 + r2*4] */
4374                                 /* LEA r1, [r1 + r1*4] */
4375                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 2);
4376                                 amd64_lea_memindex (code, ins->dreg, ins->dreg, 0, ins->dreg, 2);
4377                                 break;
4378                         case 100:
4379                                 /* LEA r1, [r2 + r2*4] */
4380                                 /* SHL r1, 2           */
4381                                 /* LEA r1, [r1 + r1*4] */
4382                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 2);
4383                                 amd64_shift_reg_imm (code, X86_SHL, ins->dreg, 2);
4384                                 amd64_lea_memindex (code, ins->dreg, ins->dreg, 0, ins->dreg, 2);
4385                                 break;
4386                         default:
4387                                 amd64_imul_reg_reg_imm_size (code, ins->dreg, ins->sreg1, ins->inst_imm, size);
4388                                 break;
4389                         }
4390                         break;
4391                 }
4392                 case OP_LDIV:
4393                 case OP_LREM:
4394 #if defined( __native_client_codegen__ )
4395                         amd64_alu_reg_imm (code, X86_CMP, ins->sreg2, 0);
4396                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_EQ, TRUE, "DivideByZeroException");
4397 #endif
4398                         /* Regalloc magic makes the div/rem cases the same */
4399                         if (ins->sreg2 == AMD64_RDX) {
4400                                 amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RDX, 8);
4401                                 amd64_cdq (code);
4402                                 amd64_div_membase (code, AMD64_RSP, -8, TRUE);
4403                         } else {
4404                                 amd64_cdq (code);
4405                                 amd64_div_reg (code, ins->sreg2, TRUE);
4406                         }
4407                         break;
4408                 case OP_LDIV_UN:
4409                 case OP_LREM_UN:
4410 #if defined( __native_client_codegen__ )
4411                         amd64_alu_reg_imm (code, X86_CMP, ins->sreg2, 0);
4412                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_EQ, TRUE, "DivideByZeroException");
4413 #endif
4414                         if (ins->sreg2 == AMD64_RDX) {
4415                                 amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RDX, 8);
4416                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RDX, AMD64_RDX);
4417                                 amd64_div_membase (code, AMD64_RSP, -8, FALSE);
4418                         } else {
4419                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RDX, AMD64_RDX);
4420                                 amd64_div_reg (code, ins->sreg2, FALSE);
4421                         }
4422                         break;
4423                 case OP_IDIV:
4424                 case OP_IREM:
4425 #if defined( __native_client_codegen__ )
4426                         amd64_alu_reg_imm (code, X86_CMP, ins->sreg2, 0);
4427                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_EQ, TRUE, "DivideByZeroException");
4428 #endif
4429                         if (ins->sreg2 == AMD64_RDX) {
4430                                 amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RDX, 8);
4431                                 amd64_cdq_size (code, 4);
4432                                 amd64_div_membase_size (code, AMD64_RSP, -8, TRUE, 4);
4433                         } else {
4434                                 amd64_cdq_size (code, 4);
4435                                 amd64_div_reg_size (code, ins->sreg2, TRUE, 4);
4436                         }
4437                         break;
4438                 case OP_IDIV_UN:
4439                 case OP_IREM_UN:
4440 #if defined( __native_client_codegen__ )
4441                         amd64_alu_reg_imm_size (code, X86_CMP, ins->sreg2, 0, 4);
4442                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_EQ, TRUE, "DivideByZeroException");
4443 #endif
4444                         if (ins->sreg2 == AMD64_RDX) {
4445                                 amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RDX, 8);
4446                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RDX, AMD64_RDX);
4447                                 amd64_div_membase_size (code, AMD64_RSP, -8, FALSE, 4);
4448                         } else {
4449                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RDX, AMD64_RDX);
4450                                 amd64_div_reg_size (code, ins->sreg2, FALSE, 4);
4451                         }
4452                         break;
4453                 case OP_IREM_IMM: {
4454                         int power = mono_is_power_of_two (ins->inst_imm);
4455
4456                         g_assert (ins->sreg1 == X86_EAX);
4457                         g_assert (ins->dreg == X86_EAX);
4458                         g_assert (power >= 0);
4459
4460                         if (power == 0) {
4461                                 amd64_mov_reg_imm (code, ins->dreg, 0);
4462                                 break;
4463                         }
4464
4465                         /* Based on gcc code */
4466
4467                         /* Add compensation for negative dividents */
4468                         amd64_mov_reg_reg_size (code, AMD64_RDX, AMD64_RAX, 4);
4469                         if (power > 1)
4470                                 amd64_shift_reg_imm_size (code, X86_SAR, AMD64_RDX, 31, 4);
4471                         amd64_shift_reg_imm_size (code, X86_SHR, AMD64_RDX, 32 - power, 4);
4472                         amd64_alu_reg_reg_size (code, X86_ADD, AMD64_RAX, AMD64_RDX, 4);
4473                         /* Compute remainder */
4474                         amd64_alu_reg_imm_size (code, X86_AND, AMD64_RAX, (1 << power) - 1, 4);
4475                         /* Remove compensation */
4476                         amd64_alu_reg_reg_size (code, X86_SUB, AMD64_RAX, AMD64_RDX, 4);
4477                         break;
4478                 }
4479                 case OP_LMUL_OVF:
4480                         amd64_imul_reg_reg (code, ins->sreg1, ins->sreg2);
4481                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_O, FALSE, "OverflowException");
4482                         break;
4483                 case OP_LOR:
4484                         amd64_alu_reg_reg (code, X86_OR, ins->sreg1, ins->sreg2);
4485                         break;
4486                 case OP_OR_IMM:
4487                 case OP_LOR_IMM:
4488                         g_assert (amd64_is_imm32 (ins->inst_imm));
4489                         amd64_alu_reg_imm (code, X86_OR, ins->sreg1, ins->inst_imm);
4490                         break;
4491                 case OP_LXOR:
4492                         amd64_alu_reg_reg (code, X86_XOR, ins->sreg1, ins->sreg2);
4493                         break;
4494                 case OP_XOR_IMM:
4495                 case OP_LXOR_IMM:
4496                         g_assert (amd64_is_imm32 (ins->inst_imm));
4497                         amd64_alu_reg_imm (code, X86_XOR, ins->sreg1, ins->inst_imm);
4498                         break;
4499                 case OP_LSHL:
4500                         g_assert (ins->sreg2 == AMD64_RCX);
4501                         amd64_shift_reg (code, X86_SHL, ins->dreg);
4502                         break;
4503                 case OP_LSHR:
4504                         g_assert (ins->sreg2 == AMD64_RCX);
4505                         amd64_shift_reg (code, X86_SAR, ins->dreg);
4506                         break;
4507                 case OP_SHR_IMM:
4508                         g_assert (amd64_is_imm32 (ins->inst_imm));
4509                         amd64_shift_reg_imm_size (code, X86_SAR, ins->dreg, ins->inst_imm, 4);
4510                         break;
4511                 case OP_LSHR_IMM:
4512                         g_assert (amd64_is_imm32 (ins->inst_imm));
4513                         amd64_shift_reg_imm (code, X86_SAR, ins->dreg, ins->inst_imm);
4514                         break;
4515                 case OP_SHR_UN_IMM:
4516                         g_assert (amd64_is_imm32 (ins->inst_imm));
4517                         amd64_shift_reg_imm_size (code, X86_SHR, ins->dreg, ins->inst_imm, 4);
4518                         break;
4519                 case OP_LSHR_UN_IMM:
4520                         g_assert (amd64_is_imm32 (ins->inst_imm));
4521                         amd64_shift_reg_imm (code, X86_SHR, ins->dreg, ins->inst_imm);
4522                         break;
4523                 case OP_LSHR_UN:
4524                         g_assert (ins->sreg2 == AMD64_RCX);
4525                         amd64_shift_reg (code, X86_SHR, ins->dreg);
4526                         break;
4527                 case OP_SHL_IMM:
4528                         g_assert (amd64_is_imm32 (ins->inst_imm));
4529                         amd64_shift_reg_imm_size (code, X86_SHL, ins->dreg, ins->inst_imm, 4);
4530                         break;
4531                 case OP_LSHL_IMM:
4532                         g_assert (amd64_is_imm32 (ins->inst_imm));
4533                         amd64_shift_reg_imm (code, X86_SHL, ins->dreg, ins->inst_imm);
4534                         break;
4535
4536                 case OP_IADDCC:
4537                 case OP_IADD:
4538                         amd64_alu_reg_reg_size (code, X86_ADD, ins->sreg1, ins->sreg2, 4);
4539                         break;
4540                 case OP_IADC:
4541                         amd64_alu_reg_reg_size (code, X86_ADC, ins->sreg1, ins->sreg2, 4);
4542                         break;
4543                 case OP_IADD_IMM:
4544                         amd64_alu_reg_imm_size (code, X86_ADD, ins->dreg, ins->inst_imm, 4);
4545                         break;
4546                 case OP_IADC_IMM:
4547                         amd64_alu_reg_imm_size (code, X86_ADC, ins->dreg, ins->inst_imm, 4);
4548                         break;
4549                 case OP_ISUBCC:
4550                 case OP_ISUB:
4551                         amd64_alu_reg_reg_size (code, X86_SUB, ins->sreg1, ins->sreg2, 4);
4552                         break;
4553                 case OP_ISBB:
4554                         amd64_alu_reg_reg_size (code, X86_SBB, ins->sreg1, ins->sreg2, 4);
4555                         break;
4556                 case OP_ISUB_IMM:
4557                         amd64_alu_reg_imm_size (code, X86_SUB, ins->dreg, ins->inst_imm, 4);
4558                         break;
4559                 case OP_ISBB_IMM:
4560                         amd64_alu_reg_imm_size (code, X86_SBB, ins->dreg, ins->inst_imm, 4);
4561                         break;
4562                 case OP_IAND:
4563                         amd64_alu_reg_reg_size (code, X86_AND, ins->sreg1, ins->sreg2, 4);
4564                         break;
4565                 case OP_IAND_IMM:
4566                         amd64_alu_reg_imm_size (code, X86_AND, ins->sreg1, ins->inst_imm, 4);
4567                         break;
4568                 case OP_IOR:
4569                         amd64_alu_reg_reg_size (code, X86_OR, ins->sreg1, ins->sreg2, 4);
4570                         break;
4571                 case OP_IOR_IMM:
4572                         amd64_alu_reg_imm_size (code, X86_OR, ins->sreg1, ins->inst_imm, 4);
4573                         break;
4574                 case OP_IXOR:
4575                         amd64_alu_reg_reg_size (code, X86_XOR, ins->sreg1, ins->sreg2, 4);
4576                         break;
4577                 case OP_IXOR_IMM:
4578                         amd64_alu_reg_imm_size (code, X86_XOR, ins->sreg1, ins->inst_imm, 4);
4579                         break;
4580                 case OP_INEG:
4581                         amd64_neg_reg_size (code, ins->sreg1, 4);
4582                         break;
4583                 case OP_INOT:
4584                         amd64_not_reg_size (code, ins->sreg1, 4);
4585                         break;
4586                 case OP_ISHL:
4587                         g_assert (ins->sreg2 == AMD64_RCX);
4588                         amd64_shift_reg_size (code, X86_SHL, ins->dreg, 4);
4589                         break;
4590                 case OP_ISHR:
4591                         g_assert (ins->sreg2 == AMD64_RCX);
4592                         amd64_shift_reg_size (code, X86_SAR, ins->dreg, 4);
4593                         break;
4594                 case OP_ISHR_IMM:
4595                         amd64_shift_reg_imm_size (code, X86_SAR, ins->dreg, ins->inst_imm, 4);
4596                         break;
4597                 case OP_ISHR_UN_IMM:
4598                         amd64_shift_reg_imm_size (code, X86_SHR, ins->dreg, ins->inst_imm, 4);
4599                         break;
4600                 case OP_ISHR_UN:
4601                         g_assert (ins->sreg2 == AMD64_RCX);
4602                         amd64_shift_reg_size (code, X86_SHR, ins->dreg, 4);
4603                         break;
4604                 case OP_ISHL_IMM:
4605                         amd64_shift_reg_imm_size (code, X86_SHL, ins->dreg, ins->inst_imm, 4);
4606                         break;
4607                 case OP_IMUL:
4608                         amd64_imul_reg_reg_size (code, ins->sreg1, ins->sreg2, 4);
4609                         break;
4610                 case OP_IMUL_OVF:
4611                         amd64_imul_reg_reg_size (code, ins->sreg1, ins->sreg2, 4);
4612                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_O, FALSE, "OverflowException");
4613                         break;
4614                 case OP_IMUL_OVF_UN:
4615                 case OP_LMUL_OVF_UN: {
4616                         /* the mul operation and the exception check should most likely be split */
4617                         int non_eax_reg, saved_eax = FALSE, saved_edx = FALSE;
4618                         int size = (ins->opcode == OP_IMUL_OVF_UN) ? 4 : 8;
4619                         /*g_assert (ins->sreg2 == X86_EAX);
4620                         g_assert (ins->dreg == X86_EAX);*/
4621                         if (ins->sreg2 == X86_EAX) {
4622                                 non_eax_reg = ins->sreg1;
4623                         } else if (ins->sreg1 == X86_EAX) {
4624                                 non_eax_reg = ins->sreg2;
4625                         } else {
4626                                 /* no need to save since we're going to store to it anyway */
4627                                 if (ins->dreg != X86_EAX) {
4628                                         saved_eax = TRUE;
4629                                         amd64_push_reg (code, X86_EAX);
4630                                 }
4631                                 amd64_mov_reg_reg (code, X86_EAX, ins->sreg1, size);
4632                                 non_eax_reg = ins->sreg2;
4633                         }
4634                         if (ins->dreg == X86_EDX) {
4635                                 if (!saved_eax) {
4636                                         saved_eax = TRUE;
4637                                         amd64_push_reg (code, X86_EAX);
4638                                 }
4639                         } else {
4640                                 saved_edx = TRUE;
4641                                 amd64_push_reg (code, X86_EDX);
4642                         }
4643                         amd64_mul_reg_size (code, non_eax_reg, FALSE, size);
4644                         /* save before the check since pop and mov don't change the flags */
4645                         if (ins->dreg != X86_EAX)
4646                                 amd64_mov_reg_reg (code, ins->dreg, X86_EAX, size);
4647                         if (saved_edx)
4648                                 amd64_pop_reg (code, X86_EDX);
4649                         if (saved_eax)
4650                                 amd64_pop_reg (code, X86_EAX);
4651                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_O, FALSE, "OverflowException");
4652                         break;
4653                 }
4654                 case OP_ICOMPARE:
4655                         amd64_alu_reg_reg_size (code, X86_CMP, ins->sreg1, ins->sreg2, 4);
4656                         break;
4657                 case OP_ICOMPARE_IMM:
4658                         amd64_alu_reg_imm_size (code, X86_CMP, ins->sreg1, ins->inst_imm, 4);
4659                         break;
4660                 case OP_IBEQ:
4661                 case OP_IBLT:
4662                 case OP_IBGT:
4663                 case OP_IBGE:
4664                 case OP_IBLE:
4665                 case OP_LBEQ:
4666                 case OP_LBLT:
4667                 case OP_LBGT:
4668                 case OP_LBGE:
4669                 case OP_LBLE:
4670                 case OP_IBNE_UN:
4671                 case OP_IBLT_UN:
4672                 case OP_IBGT_UN:
4673                 case OP_IBGE_UN:
4674                 case OP_IBLE_UN:
4675                 case OP_LBNE_UN:
4676                 case OP_LBLT_UN:
4677                 case OP_LBGT_UN:
4678                 case OP_LBGE_UN:
4679                 case OP_LBLE_UN:
4680                         EMIT_COND_BRANCH (ins, cc_table [mono_opcode_to_cond (ins->opcode)], cc_signed_table [mono_opcode_to_cond (ins->opcode)]);
4681                         break;
4682
4683                 case OP_CMOV_IEQ:
4684                 case OP_CMOV_IGE:
4685                 case OP_CMOV_IGT:
4686                 case OP_CMOV_ILE:
4687                 case OP_CMOV_ILT:
4688                 case OP_CMOV_INE_UN:
4689                 case OP_CMOV_IGE_UN:
4690                 case OP_CMOV_IGT_UN:
4691                 case OP_CMOV_ILE_UN:
4692                 case OP_CMOV_ILT_UN:
4693                 case OP_CMOV_LEQ:
4694                 case OP_CMOV_LGE:
4695                 case OP_CMOV_LGT:
4696                 case OP_CMOV_LLE:
4697                 case OP_CMOV_LLT:
4698                 case OP_CMOV_LNE_UN:
4699                 case OP_CMOV_LGE_UN:
4700                 case OP_CMOV_LGT_UN:
4701                 case OP_CMOV_LLE_UN:
4702                 case OP_CMOV_LLT_UN:
4703                         g_assert (ins->dreg == ins->sreg1);
4704                         /* This needs to operate on 64 bit values */
4705                         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);
4706                         break;
4707
4708                 case OP_LNOT:
4709                         amd64_not_reg (code, ins->sreg1);
4710                         break;
4711                 case OP_LNEG:
4712                         amd64_neg_reg (code, ins->sreg1);
4713                         break;
4714
4715                 case OP_ICONST:
4716                 case OP_I8CONST:
4717                         if ((((guint64)ins->inst_c0) >> 32) == 0)
4718                                 amd64_mov_reg_imm_size (code, ins->dreg, ins->inst_c0, 4);
4719                         else
4720                                 amd64_mov_reg_imm_size (code, ins->dreg, ins->inst_c0, 8);
4721                         break;
4722                 case OP_AOTCONST:
4723                         mono_add_patch_info (cfg, offset, (MonoJumpInfoType)ins->inst_i1, ins->inst_p0);
4724                         amd64_mov_reg_membase (code, ins->dreg, AMD64_RIP, 0, sizeof(gpointer));
4725                         break;
4726                 case OP_JUMP_TABLE:
4727                         mono_add_patch_info (cfg, offset, (MonoJumpInfoType)ins->inst_i1, ins->inst_p0);
4728                         amd64_mov_reg_imm_size (code, ins->dreg, 0, 8);
4729                         break;
4730                 case OP_MOVE:
4731                         amd64_mov_reg_reg (code, ins->dreg, ins->sreg1, sizeof(mgreg_t));
4732                         break;
4733                 case OP_AMD64_SET_XMMREG_R4: {
4734                         amd64_sse_cvtsd2ss_reg_reg (code, ins->dreg, ins->sreg1);
4735                         break;
4736                 }
4737                 case OP_AMD64_SET_XMMREG_R8: {
4738                         if (ins->dreg != ins->sreg1)
4739                                 amd64_sse_movsd_reg_reg (code, ins->dreg, ins->sreg1);
4740                         break;
4741                 }
4742                 case OP_TAILCALL: {
4743                         MonoCallInst *call = (MonoCallInst*)ins;
4744                         int pos = 0, i;
4745
4746                         /* FIXME: no tracing support... */
4747                         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
4748                                 code = mono_arch_instrument_epilog_full (cfg, mono_profiler_method_leave, code, FALSE, TRUE);
4749
4750                         g_assert (!cfg->method->save_lmf);
4751
4752                         if (cfg->arch.omit_fp) {
4753                                 guint32 save_offset = 0;
4754                                 /* Pop callee-saved registers */
4755                                 for (i = 0; i < AMD64_NREG; ++i)
4756                                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
4757                                                 amd64_mov_reg_membase (code, i, AMD64_RSP, save_offset, 8);
4758                                                 save_offset += 8;
4759                                         }
4760                                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, cfg->arch.stack_alloc_size);
4761
4762                                 // FIXME:
4763                                 if (call->stack_usage)
4764                                         NOT_IMPLEMENTED;
4765                         }
4766                         else {
4767                                 for (i = 0; i < AMD64_NREG; ++i)
4768                                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i)))
4769                                                 pos -= sizeof(mgreg_t);
4770
4771                                 /* Restore callee-saved registers */
4772                                 for (i = AMD64_NREG - 1; i > 0; --i) {
4773                                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
4774                                                 amd64_mov_reg_membase (code, i, AMD64_RBP, pos, sizeof(mgreg_t));
4775                                                 pos += sizeof(mgreg_t);
4776                                         }
4777                                 }
4778
4779                                 /* Copy arguments on the stack to our argument area */
4780                                 for (i = 0; i < call->stack_usage; i += sizeof(mgreg_t)) {
4781                                         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RSP, i, sizeof(mgreg_t));
4782                                         amd64_mov_membase_reg (code, AMD64_RBP, 16 + i, AMD64_RAX, sizeof(mgreg_t));
4783                                 }
4784                         
4785                                 if (pos)
4786                                         amd64_lea_membase (code, AMD64_RSP, AMD64_RBP, pos);
4787
4788                                 amd64_leave (code);
4789                         }
4790
4791                         offset = code - cfg->native_code;
4792                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_METHOD_JUMP, call->method);
4793                         if (cfg->compile_aot)
4794                                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, 8);
4795                         else
4796                                 amd64_set_reg_template (code, AMD64_R11);
4797                         amd64_jump_reg (code, AMD64_R11);
4798                         ins->flags |= MONO_INST_GC_CALLSITE;
4799                         ins->backend.pc_offset = code - cfg->native_code;
4800                         break;
4801                 }
4802                 case OP_CHECK_THIS:
4803                         /* ensure ins->sreg1 is not NULL */
4804                         amd64_alu_membase_imm_size (code, X86_CMP, ins->sreg1, 0, 0, 4);
4805                         break;
4806                 case OP_ARGLIST: {
4807                         amd64_lea_membase (code, AMD64_R11, cfg->frame_reg, cfg->sig_cookie);
4808                         amd64_mov_membase_reg (code, ins->sreg1, 0, AMD64_R11, sizeof(gpointer));
4809                         break;
4810                 }
4811                 case OP_CALL:
4812                 case OP_FCALL:
4813                 case OP_LCALL:
4814                 case OP_VCALL:
4815                 case OP_VCALL2:
4816                 case OP_VOIDCALL:
4817                         call = (MonoCallInst*)ins;
4818                         /*
4819                          * The AMD64 ABI forces callers to know about varargs.
4820                          */
4821                         if ((call->signature->call_convention == MONO_CALL_VARARG) && (call->signature->pinvoke))
4822                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
4823                         else if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && (cfg->method->klass->image != mono_defaults.corlib)) {
4824                                 /* 
4825                                  * Since the unmanaged calling convention doesn't contain a 
4826                                  * 'vararg' entry, we have to treat every pinvoke call as a
4827                                  * potential vararg call.
4828                                  */
4829                                 guint32 nregs, i;
4830                                 nregs = 0;
4831                                 for (i = 0; i < AMD64_XMM_NREG; ++i)
4832                                         if (call->used_fregs & (1 << i))
4833                                                 nregs ++;
4834                                 if (!nregs)
4835                                         amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
4836                                 else
4837                                         amd64_mov_reg_imm (code, AMD64_RAX, nregs);
4838                         }
4839
4840                         if (ins->flags & MONO_INST_HAS_METHOD)
4841                                 code = emit_call (cfg, code, MONO_PATCH_INFO_METHOD, call->method, FALSE);
4842                         else
4843                                 code = emit_call (cfg, code, MONO_PATCH_INFO_ABS, call->fptr, FALSE);
4844                         ins->flags |= MONO_INST_GC_CALLSITE;
4845                         ins->backend.pc_offset = code - cfg->native_code;
4846                         if (call->stack_usage && !CALLCONV_IS_STDCALL (call->signature->call_convention) && !cfg->arch.no_pushes)
4847                                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, call->stack_usage);
4848                         code = emit_move_return_value (cfg, ins, code);
4849                         break;
4850                 case OP_FCALL_REG:
4851                 case OP_LCALL_REG:
4852                 case OP_VCALL_REG:
4853                 case OP_VCALL2_REG:
4854                 case OP_VOIDCALL_REG:
4855                 case OP_CALL_REG:
4856                         call = (MonoCallInst*)ins;
4857
4858                         if (AMD64_IS_ARGUMENT_REG (ins->sreg1)) {
4859                                 amd64_mov_reg_reg (code, AMD64_R11, ins->sreg1, 8);
4860                                 ins->sreg1 = AMD64_R11;
4861                         }
4862
4863                         /*
4864                          * The AMD64 ABI forces callers to know about varargs.
4865                          */
4866                         if ((call->signature->call_convention == MONO_CALL_VARARG) && (call->signature->pinvoke)) {
4867                                 if (ins->sreg1 == AMD64_RAX) {
4868                                         amd64_mov_reg_reg (code, AMD64_R11, AMD64_RAX, 8);
4869                                         ins->sreg1 = AMD64_R11;
4870                                 }
4871                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
4872                         } else if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && (cfg->method->klass->image != mono_defaults.corlib)) {
4873                                 /* 
4874                                  * Since the unmanaged calling convention doesn't contain a 
4875                                  * 'vararg' entry, we have to treat every pinvoke call as a
4876                                  * potential vararg call.
4877                                  */
4878                                 guint32 nregs, i;
4879                                 nregs = 0;
4880                                 for (i = 0; i < AMD64_XMM_NREG; ++i)
4881                                         if (call->used_fregs & (1 << i))
4882                                                 nregs ++;
4883                                 if (ins->sreg1 == AMD64_RAX) {
4884                                         amd64_mov_reg_reg (code, AMD64_R11, AMD64_RAX, 8);
4885                                         ins->sreg1 = AMD64_R11;
4886                                 }
4887                                 if (!nregs)
4888                                         amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
4889                                 else
4890                                         amd64_mov_reg_imm (code, AMD64_RAX, nregs);
4891                         }
4892
4893                         amd64_call_reg (code, ins->sreg1);
4894                         ins->flags |= MONO_INST_GC_CALLSITE;
4895                         ins->backend.pc_offset = code - cfg->native_code;
4896                         if (call->stack_usage && !CALLCONV_IS_STDCALL (call->signature->call_convention) && !cfg->arch.no_pushes)
4897                                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, call->stack_usage);
4898                         code = emit_move_return_value (cfg, ins, code);
4899                         break;
4900                 case OP_FCALL_MEMBASE:
4901                 case OP_LCALL_MEMBASE:
4902                 case OP_VCALL_MEMBASE:
4903                 case OP_VCALL2_MEMBASE:
4904                 case OP_VOIDCALL_MEMBASE:
4905                 case OP_CALL_MEMBASE:
4906                         call = (MonoCallInst*)ins;
4907
4908                         amd64_call_membase (code, ins->sreg1, ins->inst_offset);
4909                         ins->flags |= MONO_INST_GC_CALLSITE;
4910                         ins->backend.pc_offset = code - cfg->native_code;
4911                         if (call->stack_usage && !CALLCONV_IS_STDCALL (call->signature->call_convention) && !cfg->arch.no_pushes)
4912                                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, call->stack_usage);
4913                         code = emit_move_return_value (cfg, ins, code);
4914                         break;
4915                 case OP_DYN_CALL: {
4916                         int i;
4917                         MonoInst *var = cfg->dyn_call_var;
4918
4919                         g_assert (var->opcode == OP_REGOFFSET);
4920
4921                         /* r11 = args buffer filled by mono_arch_get_dyn_call_args () */
4922                         amd64_mov_reg_reg (code, AMD64_R11, ins->sreg1, 8);
4923                         /* r10 = ftn */
4924                         amd64_mov_reg_reg (code, AMD64_R10, ins->sreg2, 8);
4925
4926                         /* Save args buffer */
4927                         amd64_mov_membase_reg (code, var->inst_basereg, var->inst_offset, AMD64_R11, 8);
4928
4929                         /* Set argument registers */
4930                         for (i = 0; i < PARAM_REGS; ++i)
4931                                 amd64_mov_reg_membase (code, param_regs [i], AMD64_R11, i * sizeof(mgreg_t), sizeof(mgreg_t));
4932                         
4933                         /* Make the call */
4934                         amd64_call_reg (code, AMD64_R10);
4935
4936                         ins->flags |= MONO_INST_GC_CALLSITE;
4937                         ins->backend.pc_offset = code - cfg->native_code;
4938
4939                         /* Save result */
4940                         amd64_mov_reg_membase (code, AMD64_R11, var->inst_basereg, var->inst_offset, 8);
4941                         amd64_mov_membase_reg (code, AMD64_R11, G_STRUCT_OFFSET (DynCallArgs, res), AMD64_RAX, 8);
4942                         break;
4943                 }
4944                 case OP_AMD64_SAVE_SP_TO_LMF: {
4945                         MonoInst *lmf_var = cfg->arch.lmf_var;
4946                         amd64_mov_membase_reg (code, cfg->frame_reg, lmf_var->inst_offset + G_STRUCT_OFFSET (MonoLMF, rsp), AMD64_RSP, 8);
4947                         break;
4948                 }
4949                 case OP_X86_PUSH:
4950                         g_assert (!cfg->arch.no_pushes);
4951                         amd64_push_reg (code, ins->sreg1);
4952                         break;
4953                 case OP_X86_PUSH_IMM:
4954                         g_assert (!cfg->arch.no_pushes);
4955                         g_assert (amd64_is_imm32 (ins->inst_imm));
4956                         amd64_push_imm (code, ins->inst_imm);
4957                         break;
4958                 case OP_X86_PUSH_MEMBASE:
4959                         g_assert (!cfg->arch.no_pushes);
4960                         amd64_push_membase (code, ins->inst_basereg, ins->inst_offset);
4961                         break;
4962                 case OP_X86_PUSH_OBJ: {
4963                         int size = ALIGN_TO (ins->inst_imm, 8);
4964
4965                         g_assert (!cfg->arch.no_pushes);
4966
4967                         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, size);
4968                         amd64_push_reg (code, AMD64_RDI);
4969                         amd64_push_reg (code, AMD64_RSI);
4970                         amd64_push_reg (code, AMD64_RCX);
4971                         if (ins->inst_offset)
4972                                 amd64_lea_membase (code, AMD64_RSI, ins->inst_basereg, ins->inst_offset);
4973                         else
4974                                 amd64_mov_reg_reg (code, AMD64_RSI, ins->inst_basereg, 8);
4975                         amd64_lea_membase (code, AMD64_RDI, AMD64_RSP, (3 * 8));
4976                         amd64_mov_reg_imm (code, AMD64_RCX, (size >> 3));
4977                         amd64_cld (code);
4978                         amd64_prefix (code, X86_REP_PREFIX);
4979                         amd64_movsd (code);
4980                         amd64_pop_reg (code, AMD64_RCX);
4981                         amd64_pop_reg (code, AMD64_RSI);
4982                         amd64_pop_reg (code, AMD64_RDI);
4983                         break;
4984                 }
4985                 case OP_X86_LEA:
4986                         amd64_lea_memindex (code, ins->dreg, ins->sreg1, ins->inst_imm, ins->sreg2, ins->backend.shift_amount);
4987                         break;
4988                 case OP_X86_LEA_MEMBASE:
4989                         amd64_lea_membase (code, ins->dreg, ins->sreg1, ins->inst_imm);
4990                         break;
4991                 case OP_X86_XCHG:
4992                         amd64_xchg_reg_reg (code, ins->sreg1, ins->sreg2, 4);
4993                         break;
4994                 case OP_LOCALLOC:
4995                         /* keep alignment */
4996                         amd64_alu_reg_imm (code, X86_ADD, ins->sreg1, MONO_ARCH_FRAME_ALIGNMENT - 1);
4997                         amd64_alu_reg_imm (code, X86_AND, ins->sreg1, ~(MONO_ARCH_FRAME_ALIGNMENT - 1));
4998                         code = mono_emit_stack_alloc (cfg, code, ins);
4999                         amd64_mov_reg_reg (code, ins->dreg, AMD64_RSP, 8);
5000                         if (cfg->param_area && cfg->arch.no_pushes)
5001                                 amd64_alu_reg_imm (code, X86_ADD, ins->dreg, cfg->param_area);
5002                         break;
5003                 case OP_LOCALLOC_IMM: {
5004                         guint32 size = ins->inst_imm;
5005                         size = (size + (MONO_ARCH_FRAME_ALIGNMENT - 1)) & ~ (MONO_ARCH_FRAME_ALIGNMENT - 1);
5006
5007                         if (ins->flags & MONO_INST_INIT) {
5008                                 if (size < 64) {
5009                                         int i;
5010
5011                                         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, size);
5012                                         amd64_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
5013
5014                                         for (i = 0; i < size; i += 8)
5015                                                 amd64_mov_membase_reg (code, AMD64_RSP, i, ins->dreg, 8);
5016                                         amd64_mov_reg_reg (code, ins->dreg, AMD64_RSP, 8);                                      
5017                                 } else {
5018                                         amd64_mov_reg_imm (code, ins->dreg, size);
5019                                         ins->sreg1 = ins->dreg;
5020
5021                                         code = mono_emit_stack_alloc (cfg, code, ins);
5022                                         amd64_mov_reg_reg (code, ins->dreg, AMD64_RSP, 8);
5023                                 }
5024                         } else {
5025                                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, size);
5026                                 amd64_mov_reg_reg (code, ins->dreg, AMD64_RSP, 8);
5027                         }
5028                         if (cfg->param_area && cfg->arch.no_pushes)
5029                                 amd64_alu_reg_imm (code, X86_ADD, ins->dreg, cfg->param_area);
5030                         break;
5031                 }
5032                 case OP_THROW: {
5033                         amd64_mov_reg_reg (code, AMD64_ARG_REG1, ins->sreg1, 8);
5034                         code = emit_call (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD, 
5035                                              (gpointer)"mono_arch_throw_exception", FALSE);
5036                         ins->flags |= MONO_INST_GC_CALLSITE;
5037                         ins->backend.pc_offset = code - cfg->native_code;
5038                         break;
5039                 }
5040                 case OP_RETHROW: {
5041                         amd64_mov_reg_reg (code, AMD64_ARG_REG1, ins->sreg1, 8);
5042                         code = emit_call (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD, 
5043                                              (gpointer)"mono_arch_rethrow_exception", FALSE);
5044                         ins->flags |= MONO_INST_GC_CALLSITE;
5045                         ins->backend.pc_offset = code - cfg->native_code;
5046                         break;
5047                 }
5048                 case OP_CALL_HANDLER: 
5049                         /* Align stack */
5050                         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
5051                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_BB, ins->inst_target_bb);
5052                         amd64_call_imm (code, 0);
5053                         mono_cfg_add_try_hole (cfg, ins->inst_eh_block, code, bb);
5054                         /* Restore stack alignment */
5055                         amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
5056                         break;
5057                 case OP_START_HANDLER: {
5058                         /* Even though we're saving RSP, use sizeof */
5059                         /* gpointer because spvar is of type IntPtr */
5060                         /* see: mono_create_spvar_for_region */
5061                         MonoInst *spvar = mono_find_spvar_for_region (cfg, bb->region);
5062                         amd64_mov_membase_reg (code, spvar->inst_basereg, spvar->inst_offset, AMD64_RSP, sizeof(gpointer));
5063
5064                         if ((MONO_BBLOCK_IS_IN_REGION (bb, MONO_REGION_FINALLY) ||
5065                                  MONO_BBLOCK_IS_IN_REGION (bb, MONO_REGION_FINALLY)) &&
5066                                 cfg->param_area && cfg->arch.no_pushes) {
5067                                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, ALIGN_TO (cfg->param_area, MONO_ARCH_FRAME_ALIGNMENT));
5068                         }
5069                         break;
5070                 }
5071                 case OP_ENDFINALLY: {
5072                         MonoInst *spvar = mono_find_spvar_for_region (cfg, bb->region);
5073                         amd64_mov_reg_membase (code, AMD64_RSP, spvar->inst_basereg, spvar->inst_offset, sizeof(gpointer));
5074                         amd64_ret (code);
5075                         break;
5076                 }
5077                 case OP_ENDFILTER: {
5078                         MonoInst *spvar = mono_find_spvar_for_region (cfg, bb->region);
5079                         amd64_mov_reg_membase (code, AMD64_RSP, spvar->inst_basereg, spvar->inst_offset, sizeof(gpointer));
5080                         /* The local allocator will put the result into RAX */
5081                         amd64_ret (code);
5082                         break;
5083                 }
5084
5085                 case OP_LABEL:
5086                         ins->inst_c0 = code - cfg->native_code;
5087                         break;
5088                 case OP_BR:
5089                         //g_print ("target: %p, next: %p, curr: %p, last: %p\n", ins->inst_target_bb, bb->next_bb, ins, bb->last_ins);
5090                         //if ((ins->inst_target_bb == bb->next_bb) && ins == bb->last_ins)
5091                         //break;
5092                                 if (ins->inst_target_bb->native_offset) {
5093                                         amd64_jump_code (code, cfg->native_code + ins->inst_target_bb->native_offset); 
5094                                 } else {
5095                                         mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_BB, ins->inst_target_bb);
5096                                         if ((cfg->opt & MONO_OPT_BRANCH) &&
5097                                             x86_is_imm8 (ins->inst_target_bb->max_offset - offset))
5098                                                 x86_jump8 (code, 0);
5099                                         else 
5100                                                 x86_jump32 (code, 0);
5101                         }
5102                         break;
5103                 case OP_BR_REG:
5104                         amd64_jump_reg (code, ins->sreg1);
5105                         break;
5106                 case OP_CEQ:
5107                 case OP_LCEQ:
5108                 case OP_ICEQ:
5109                 case OP_CLT:
5110                 case OP_LCLT:
5111                 case OP_ICLT:
5112                 case OP_CGT:
5113                 case OP_ICGT:
5114                 case OP_LCGT:
5115                 case OP_CLT_UN:
5116                 case OP_LCLT_UN:
5117                 case OP_ICLT_UN:
5118                 case OP_CGT_UN:
5119                 case OP_LCGT_UN:
5120                 case OP_ICGT_UN:
5121                         amd64_set_reg (code, cc_table [mono_opcode_to_cond (ins->opcode)], ins->dreg, cc_signed_table [mono_opcode_to_cond (ins->opcode)]);
5122                         amd64_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
5123                         break;
5124                 case OP_COND_EXC_EQ:
5125                 case OP_COND_EXC_NE_UN:
5126                 case OP_COND_EXC_LT:
5127                 case OP_COND_EXC_LT_UN:
5128                 case OP_COND_EXC_GT:
5129                 case OP_COND_EXC_GT_UN:
5130                 case OP_COND_EXC_GE:
5131                 case OP_COND_EXC_GE_UN:
5132                 case OP_COND_EXC_LE:
5133                 case OP_COND_EXC_LE_UN:
5134                 case OP_COND_EXC_IEQ:
5135                 case OP_COND_EXC_INE_UN:
5136                 case OP_COND_EXC_ILT:
5137                 case OP_COND_EXC_ILT_UN:
5138                 case OP_COND_EXC_IGT:
5139                 case OP_COND_EXC_IGT_UN:
5140                 case OP_COND_EXC_IGE:
5141                 case OP_COND_EXC_IGE_UN:
5142                 case OP_COND_EXC_ILE:
5143                 case OP_COND_EXC_ILE_UN:
5144                         EMIT_COND_SYSTEM_EXCEPTION (cc_table [mono_opcode_to_cond (ins->opcode)], cc_signed_table [mono_opcode_to_cond (ins->opcode)], ins->inst_p1);
5145                         break;
5146                 case OP_COND_EXC_OV:
5147                 case OP_COND_EXC_NO:
5148                 case OP_COND_EXC_C:
5149                 case OP_COND_EXC_NC:
5150                         EMIT_COND_SYSTEM_EXCEPTION (branch_cc_table [ins->opcode - OP_COND_EXC_EQ], 
5151                                                     (ins->opcode < OP_COND_EXC_NE_UN), ins->inst_p1);
5152                         break;
5153                 case OP_COND_EXC_IOV:
5154                 case OP_COND_EXC_INO:
5155                 case OP_COND_EXC_IC:
5156                 case OP_COND_EXC_INC:
5157                         EMIT_COND_SYSTEM_EXCEPTION (branch_cc_table [ins->opcode - OP_COND_EXC_IEQ], 
5158                                                     (ins->opcode < OP_COND_EXC_INE_UN), ins->inst_p1);
5159                         break;
5160
5161                 /* floating point opcodes */
5162                 case OP_R8CONST: {
5163                         double d = *(double *)ins->inst_p0;
5164
5165                         if ((d == 0.0) && (mono_signbit (d) == 0)) {
5166                                 amd64_sse_xorpd_reg_reg (code, ins->dreg, ins->dreg);
5167                         }
5168                         else {
5169                                 mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_R8, ins->inst_p0);
5170                                 amd64_sse_movsd_reg_membase (code, ins->dreg, AMD64_RIP, 0);
5171                         }
5172                         break;
5173                 }
5174                 case OP_R4CONST: {
5175                         float f = *(float *)ins->inst_p0;
5176
5177                         if ((f == 0.0) && (mono_signbit (f) == 0)) {
5178                                 amd64_sse_xorpd_reg_reg (code, ins->dreg, ins->dreg);
5179                         }
5180                         else {
5181                                 mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_R4, ins->inst_p0);
5182                                 amd64_sse_movss_reg_membase (code, ins->dreg, AMD64_RIP, 0);
5183                                 amd64_sse_cvtss2sd_reg_reg (code, ins->dreg, ins->dreg);
5184                         }
5185                         break;
5186                 }
5187                 case OP_STORER8_MEMBASE_REG:
5188                         amd64_sse_movsd_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1);
5189                         break;
5190                 case OP_LOADR8_MEMBASE:
5191                         amd64_sse_movsd_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset);
5192                         break;
5193                 case OP_STORER4_MEMBASE_REG:
5194                         /* This requires a double->single conversion */
5195                         amd64_sse_cvtsd2ss_reg_reg (code, AMD64_XMM15, ins->sreg1);
5196                         amd64_sse_movss_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, AMD64_XMM15);
5197                         break;
5198                 case OP_LOADR4_MEMBASE:
5199                         amd64_sse_movss_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset);
5200                         amd64_sse_cvtss2sd_reg_reg (code, ins->dreg, ins->dreg);
5201                         break;
5202                 case OP_ICONV_TO_R4: /* FIXME: change precision */
5203                 case OP_ICONV_TO_R8:
5204                         amd64_sse_cvtsi2sd_reg_reg_size (code, ins->dreg, ins->sreg1, 4);
5205                         break;
5206                 case OP_LCONV_TO_R4: /* FIXME: change precision */
5207                 case OP_LCONV_TO_R8:
5208                         amd64_sse_cvtsi2sd_reg_reg (code, ins->dreg, ins->sreg1);
5209                         break;
5210                 case OP_FCONV_TO_R4:
5211                         /* FIXME: nothing to do ?? */
5212                         break;
5213                 case OP_FCONV_TO_I1:
5214                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 1, TRUE);
5215                         break;
5216                 case OP_FCONV_TO_U1:
5217                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 1, FALSE);
5218                         break;
5219                 case OP_FCONV_TO_I2:
5220                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 2, TRUE);
5221                         break;
5222                 case OP_FCONV_TO_U2:
5223                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 2, FALSE);
5224                         break;
5225                 case OP_FCONV_TO_U4:
5226                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 4, FALSE);                  
5227                         break;
5228                 case OP_FCONV_TO_I4:
5229                 case OP_FCONV_TO_I:
5230                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 4, TRUE);
5231                         break;
5232                 case OP_FCONV_TO_I8:
5233                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 8, TRUE);
5234                         break;
5235                 case OP_LCONV_TO_R_UN: { 
5236                         guint8 *br [2];
5237
5238                         /* Based on gcc code */
5239                         amd64_test_reg_reg (code, ins->sreg1, ins->sreg1);
5240                         br [0] = code; x86_branch8 (code, X86_CC_S, 0, TRUE);
5241
5242                         /* Positive case */
5243                         amd64_sse_cvtsi2sd_reg_reg (code, ins->dreg, ins->sreg1);
5244                         br [1] = code; x86_jump8 (code, 0);
5245                         amd64_patch (br [0], code);
5246
5247                         /* Negative case */
5248                         /* Save to the red zone */
5249                         amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RAX, 8);
5250                         amd64_mov_membase_reg (code, AMD64_RSP, -16, AMD64_RCX, 8);
5251                         amd64_mov_reg_reg (code, AMD64_RCX, ins->sreg1, 8);
5252                         amd64_mov_reg_reg (code, AMD64_RAX, ins->sreg1, 8);
5253                         amd64_alu_reg_imm (code, X86_AND, AMD64_RCX, 1);
5254                         amd64_shift_reg_imm (code, X86_SHR, AMD64_RAX, 1);
5255                         amd64_alu_reg_imm (code, X86_OR, AMD64_RAX, AMD64_RCX);
5256                         amd64_sse_cvtsi2sd_reg_reg (code, ins->dreg, AMD64_RAX);
5257                         amd64_sse_addsd_reg_reg (code, ins->dreg, ins->dreg);
5258                         /* Restore */
5259                         amd64_mov_reg_membase (code, AMD64_RCX, AMD64_RSP, -16, 8);
5260                         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RSP, -8, 8);
5261                         amd64_patch (br [1], code);
5262                         break;
5263                 }
5264                 case OP_LCONV_TO_OVF_U4:
5265                         amd64_alu_reg_imm (code, X86_CMP, ins->sreg1, 0);
5266                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_LT, TRUE, "OverflowException");
5267                         amd64_mov_reg_reg (code, ins->dreg, ins->sreg1, 8);
5268                         break;
5269                 case OP_LCONV_TO_OVF_I4_UN:
5270                         amd64_alu_reg_imm (code, X86_CMP, ins->sreg1, 0x7fffffff);
5271                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_GT, FALSE, "OverflowException");
5272                         amd64_mov_reg_reg (code, ins->dreg, ins->sreg1, 8);
5273                         break;
5274                 case OP_FMOVE:
5275                         if (ins->dreg != ins->sreg1)
5276                                 amd64_sse_movsd_reg_reg (code, ins->dreg, ins->sreg1);
5277                         break;
5278                 case OP_FADD:
5279                         amd64_sse_addsd_reg_reg (code, ins->dreg, ins->sreg2);
5280                         break;
5281                 case OP_FSUB:
5282                         amd64_sse_subsd_reg_reg (code, ins->dreg, ins->sreg2);
5283                         break;          
5284                 case OP_FMUL:
5285                         amd64_sse_mulsd_reg_reg (code, ins->dreg, ins->sreg2);
5286                         break;          
5287                 case OP_FDIV:
5288                         amd64_sse_divsd_reg_reg (code, ins->dreg, ins->sreg2);
5289                         break;          
5290                 case OP_FNEG: {
5291                         static double r8_0 = -0.0;
5292
5293                         g_assert (ins->sreg1 == ins->dreg);
5294                                         
5295                         mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_R8, &r8_0);
5296                         amd64_sse_xorpd_reg_membase (code, ins->dreg, AMD64_RIP, 0);
5297                         break;
5298                 }
5299                 case OP_SIN:
5300                         EMIT_SSE2_FPFUNC (code, fsin, ins->dreg, ins->sreg1);
5301                         break;          
5302                 case OP_COS:
5303                         EMIT_SSE2_FPFUNC (code, fcos, ins->dreg, ins->sreg1);
5304                         break;          
5305                 case OP_ABS: {
5306                         static guint64 d = 0x7fffffffffffffffUL;
5307
5308                         g_assert (ins->sreg1 == ins->dreg);
5309                                         
5310                         mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_R8, &d);
5311                         amd64_sse_andpd_reg_membase (code, ins->dreg, AMD64_RIP, 0);
5312                         break;          
5313                 }
5314                 case OP_SQRT:
5315                         EMIT_SSE2_FPFUNC (code, fsqrt, ins->dreg, ins->sreg1);
5316                         break;
5317                 case OP_IMIN:
5318                         g_assert (cfg->opt & MONO_OPT_CMOV);
5319                         g_assert (ins->dreg == ins->sreg1);
5320                         amd64_alu_reg_reg_size (code, X86_CMP, ins->sreg1, ins->sreg2, 4);
5321                         amd64_cmov_reg_size (code, X86_CC_GT, TRUE, ins->dreg, ins->sreg2, 4);
5322                         break;
5323                 case OP_IMIN_UN:
5324                         g_assert (cfg->opt & MONO_OPT_CMOV);
5325                         g_assert (ins->dreg == ins->sreg1);
5326                         amd64_alu_reg_reg_size (code, X86_CMP, ins->sreg1, ins->sreg2, 4);
5327                         amd64_cmov_reg_size (code, X86_CC_GT, FALSE, ins->dreg, ins->sreg2, 4);
5328                         break;
5329                 case OP_IMAX:
5330                         g_assert (cfg->opt & MONO_OPT_CMOV);
5331                         g_assert (ins->dreg == ins->sreg1);
5332                         amd64_alu_reg_reg_size (code, X86_CMP, ins->sreg1, ins->sreg2, 4);
5333                         amd64_cmov_reg_size (code, X86_CC_LT, TRUE, ins->dreg, ins->sreg2, 4);
5334                         break;
5335                 case OP_IMAX_UN:
5336                         g_assert (cfg->opt & MONO_OPT_CMOV);
5337                         g_assert (ins->dreg == ins->sreg1);
5338                         amd64_alu_reg_reg_size (code, X86_CMP, ins->sreg1, ins->sreg2, 4);
5339                         amd64_cmov_reg_size (code, X86_CC_LT, FALSE, ins->dreg, ins->sreg2, 4);
5340                         break;
5341                 case OP_LMIN:
5342                         g_assert (cfg->opt & MONO_OPT_CMOV);
5343                         g_assert (ins->dreg == ins->sreg1);
5344                         amd64_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2);
5345                         amd64_cmov_reg (code, X86_CC_GT, TRUE, ins->dreg, ins->sreg2);
5346                         break;
5347                 case OP_LMIN_UN:
5348                         g_assert (cfg->opt & MONO_OPT_CMOV);
5349                         g_assert (ins->dreg == ins->sreg1);
5350                         amd64_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2);
5351                         amd64_cmov_reg (code, X86_CC_GT, FALSE, ins->dreg, ins->sreg2);
5352                         break;
5353                 case OP_LMAX:
5354                         g_assert (cfg->opt & MONO_OPT_CMOV);
5355                         g_assert (ins->dreg == ins->sreg1);
5356                         amd64_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2);
5357                         amd64_cmov_reg (code, X86_CC_LT, TRUE, ins->dreg, ins->sreg2);
5358                         break;
5359                 case OP_LMAX_UN:
5360                         g_assert (cfg->opt & MONO_OPT_CMOV);
5361                         g_assert (ins->dreg == ins->sreg1);
5362                         amd64_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2);
5363                         amd64_cmov_reg (code, X86_CC_LT, FALSE, ins->dreg, ins->sreg2);
5364                         break;  
5365                 case OP_X86_FPOP:
5366                         break;          
5367                 case OP_FCOMPARE:
5368                         /* 
5369                          * The two arguments are swapped because the fbranch instructions
5370                          * depend on this for the non-sse case to work.
5371                          */
5372                         amd64_sse_comisd_reg_reg (code, ins->sreg2, ins->sreg1);
5373                         break;
5374                 case OP_FCEQ: {
5375                         /* zeroing the register at the start results in 
5376                          * shorter and faster code (we can also remove the widening op)
5377                          */
5378                         guchar *unordered_check;
5379                         amd64_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
5380                         amd64_sse_comisd_reg_reg (code, ins->sreg1, ins->sreg2);
5381                         unordered_check = code;
5382                         x86_branch8 (code, X86_CC_P, 0, FALSE);
5383                         amd64_set_reg (code, X86_CC_EQ, ins->dreg, FALSE);
5384                         amd64_patch (unordered_check, code);
5385                         break;
5386                 }
5387                 case OP_FCLT:
5388                 case OP_FCLT_UN:
5389                         /* zeroing the register at the start results in 
5390                          * shorter and faster code (we can also remove the widening op)
5391                          */
5392                         amd64_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
5393                         amd64_sse_comisd_reg_reg (code, ins->sreg2, ins->sreg1);
5394                         if (ins->opcode == OP_FCLT_UN) {
5395                                 guchar *unordered_check = code;
5396                                 guchar *jump_to_end;
5397                                 x86_branch8 (code, X86_CC_P, 0, FALSE);
5398                                 amd64_set_reg (code, X86_CC_GT, ins->dreg, FALSE);
5399                                 jump_to_end = code;
5400                                 x86_jump8 (code, 0);
5401                                 amd64_patch (unordered_check, code);
5402                                 amd64_inc_reg (code, ins->dreg);
5403                                 amd64_patch (jump_to_end, code);
5404                         } else {
5405                                 amd64_set_reg (code, X86_CC_GT, ins->dreg, FALSE);
5406                         }
5407                         break;
5408                 case OP_FCGT:
5409                 case OP_FCGT_UN: {
5410                         /* zeroing the register at the start results in 
5411                          * shorter and faster code (we can also remove the widening op)
5412                          */
5413                         guchar *unordered_check;
5414                         amd64_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
5415                         amd64_sse_comisd_reg_reg (code, ins->sreg2, ins->sreg1);
5416                         if (ins->opcode == OP_FCGT) {
5417                                 unordered_check = code;
5418                                 x86_branch8 (code, X86_CC_P, 0, FALSE);
5419                                 amd64_set_reg (code, X86_CC_LT, ins->dreg, FALSE);
5420                                 amd64_patch (unordered_check, code);
5421                         } else {
5422                                 amd64_set_reg (code, X86_CC_LT, ins->dreg, FALSE);
5423                         }
5424                         break;
5425                 }
5426                 case OP_FCLT_MEMBASE:
5427                 case OP_FCGT_MEMBASE:
5428                 case OP_FCLT_UN_MEMBASE:
5429                 case OP_FCGT_UN_MEMBASE:
5430                 case OP_FCEQ_MEMBASE: {
5431                         guchar *unordered_check, *jump_to_end;
5432                         int x86_cond;
5433
5434                         amd64_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
5435                         amd64_sse_comisd_reg_membase (code, ins->sreg1, ins->sreg2, ins->inst_offset);
5436
5437                         switch (ins->opcode) {
5438                         case OP_FCEQ_MEMBASE:
5439                                 x86_cond = X86_CC_EQ;
5440                                 break;
5441                         case OP_FCLT_MEMBASE:
5442                         case OP_FCLT_UN_MEMBASE:
5443                                 x86_cond = X86_CC_LT;
5444                                 break;
5445                         case OP_FCGT_MEMBASE:
5446                         case OP_FCGT_UN_MEMBASE:
5447                                 x86_cond = X86_CC_GT;
5448                                 break;
5449                         default:
5450                                 g_assert_not_reached ();
5451                         }
5452
5453                         unordered_check = code;
5454                         x86_branch8 (code, X86_CC_P, 0, FALSE);
5455                         amd64_set_reg (code, x86_cond, ins->dreg, FALSE);
5456
5457                         switch (ins->opcode) {
5458                         case OP_FCEQ_MEMBASE:
5459                         case OP_FCLT_MEMBASE:
5460                         case OP_FCGT_MEMBASE:
5461                                 amd64_patch (unordered_check, code);
5462                                 break;
5463                         case OP_FCLT_UN_MEMBASE:
5464                         case OP_FCGT_UN_MEMBASE:
5465                                 jump_to_end = code;
5466                                 x86_jump8 (code, 0);
5467                                 amd64_patch (unordered_check, code);
5468                                 amd64_inc_reg (code, ins->dreg);
5469                                 amd64_patch (jump_to_end, code);
5470                                 break;
5471                         default:
5472                                 break;
5473                         }
5474                         break;
5475                 }
5476                 case OP_FBEQ: {
5477                         guchar *jump = code;
5478                         x86_branch8 (code, X86_CC_P, 0, TRUE);
5479                         EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
5480                         amd64_patch (jump, code);
5481                         break;
5482                 }
5483                 case OP_FBNE_UN:
5484                         /* Branch if C013 != 100 */
5485                         /* branch if !ZF or (PF|CF) */
5486                         EMIT_COND_BRANCH (ins, X86_CC_NE, FALSE);
5487                         EMIT_COND_BRANCH (ins, X86_CC_P, FALSE);
5488                         EMIT_COND_BRANCH (ins, X86_CC_B, FALSE);
5489                         break;
5490                 case OP_FBLT:
5491                         EMIT_COND_BRANCH (ins, X86_CC_GT, FALSE);
5492                         break;
5493                 case OP_FBLT_UN:
5494                         EMIT_COND_BRANCH (ins, X86_CC_P, FALSE);
5495                         EMIT_COND_BRANCH (ins, X86_CC_GT, FALSE);
5496                         break;
5497                 case OP_FBGT:
5498                 case OP_FBGT_UN:
5499                         if (ins->opcode == OP_FBGT) {
5500                                 guchar *br1;
5501
5502                                 /* skip branch if C1=1 */
5503                                 br1 = code;
5504                                 x86_branch8 (code, X86_CC_P, 0, FALSE);
5505                                 /* branch if (C0 | C3) = 1 */
5506                                 EMIT_COND_BRANCH (ins, X86_CC_LT, FALSE);
5507                                 amd64_patch (br1, code);
5508                                 break;
5509                         } else {
5510                                 EMIT_COND_BRANCH (ins, X86_CC_LT, FALSE);
5511                         }
5512                         break;
5513                 case OP_FBGE: {
5514                         /* Branch if C013 == 100 or 001 */
5515                         guchar *br1;
5516
5517                         /* skip branch if C1=1 */
5518                         br1 = code;
5519                         x86_branch8 (code, X86_CC_P, 0, FALSE);
5520                         /* branch if (C0 | C3) = 1 */
5521                         EMIT_COND_BRANCH (ins, X86_CC_BE, FALSE);
5522                         amd64_patch (br1, code);
5523                         break;
5524                 }
5525                 case OP_FBGE_UN:
5526                         /* Branch if C013 == 000 */
5527                         EMIT_COND_BRANCH (ins, X86_CC_LE, FALSE);
5528                         break;
5529                 case OP_FBLE: {
5530                         /* Branch if C013=000 or 100 */
5531                         guchar *br1;
5532
5533                         /* skip branch if C1=1 */
5534                         br1 = code;
5535                         x86_branch8 (code, X86_CC_P, 0, FALSE);
5536                         /* branch if C0=0 */
5537                         EMIT_COND_BRANCH (ins, X86_CC_NB, FALSE);
5538                         amd64_patch (br1, code);
5539                         break;
5540                 }
5541                 case OP_FBLE_UN:
5542                         /* Branch if C013 != 001 */
5543                         EMIT_COND_BRANCH (ins, X86_CC_P, FALSE);
5544                         EMIT_COND_BRANCH (ins, X86_CC_GE, FALSE);
5545                         break;
5546                 case OP_CKFINITE:
5547                         /* Transfer value to the fp stack */
5548                         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 16);
5549                         amd64_movsd_membase_reg (code, AMD64_RSP, 0, ins->sreg1);
5550                         amd64_fld_membase (code, AMD64_RSP, 0, TRUE);
5551
5552                         amd64_push_reg (code, AMD64_RAX);
5553                         amd64_fxam (code);
5554                         amd64_fnstsw (code);
5555                         amd64_alu_reg_imm (code, X86_AND, AMD64_RAX, 0x4100);
5556                         amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, X86_FP_C0);
5557                         amd64_pop_reg (code, AMD64_RAX);
5558                         amd64_fstp (code, 0);
5559                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_EQ, FALSE, "ArithmeticException");
5560                         amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 16);
5561                         break;
5562                 case OP_TLS_GET: {
5563                         code = mono_amd64_emit_tls_get (code, ins->dreg, ins->inst_offset);
5564                         break;
5565                 }
5566                 case OP_TLS_GET_REG:
5567 #ifdef TARGET_OSX
5568                         // FIXME: tls_gs_offset can change too, do these when calculating the tls offset
5569                         if (ins->dreg != ins->sreg1)
5570                                 amd64_mov_reg_reg (code, ins->dreg, ins->sreg1, sizeof (gpointer));
5571                         amd64_shift_reg_imm (code, X86_SHL, ins->dreg, 3);
5572                         if (tls_gs_offset)
5573                                 amd64_alu_reg_imm (code, X86_ADD, ins->dreg, tls_gs_offset);
5574                         x86_prefix (code, X86_GS_PREFIX);
5575                         amd64_mov_reg_membase (code, ins->dreg, ins->dreg, 0, sizeof (gpointer));
5576 #else
5577                         g_assert_not_reached ();
5578 #endif
5579                         break;
5580                 case OP_MEMORY_BARRIER: {
5581                         switch (ins->backend.memory_barrier_kind) {
5582                         case StoreLoadBarrier:
5583                         case FullBarrier:
5584                                 /* http://blogs.sun.com/dave/resource/NHM-Pipeline-Blog-V2.txt */
5585                                 x86_prefix (code, X86_LOCK_PREFIX);
5586                                 amd64_alu_membase_imm (code, X86_ADD, AMD64_RSP, 0, 0);
5587                                 break;
5588                         }
5589                         break;
5590                 }
5591                 case OP_ATOMIC_ADD_I4:
5592                 case OP_ATOMIC_ADD_I8: {
5593                         int dreg = ins->dreg;
5594                         guint32 size = (ins->opcode == OP_ATOMIC_ADD_I4) ? 4 : 8;
5595
5596                         if (dreg == ins->inst_basereg)
5597                                 dreg = AMD64_R11;
5598                         
5599                         if (dreg != ins->sreg2)
5600                                 amd64_mov_reg_reg (code, ins->dreg, ins->sreg2, size);
5601
5602                         x86_prefix (code, X86_LOCK_PREFIX);
5603                         amd64_xadd_membase_reg (code, ins->inst_basereg, ins->inst_offset, dreg, size);
5604
5605                         if (dreg != ins->dreg)
5606                                 amd64_mov_reg_reg (code, ins->dreg, dreg, size);
5607
5608                         break;
5609                 }
5610                 case OP_ATOMIC_ADD_NEW_I4:
5611                 case OP_ATOMIC_ADD_NEW_I8: {
5612                         int dreg = ins->dreg;
5613                         guint32 size = (ins->opcode == OP_ATOMIC_ADD_NEW_I4) ? 4 : 8;
5614
5615                         if ((dreg == ins->sreg2) || (dreg == ins->inst_basereg))
5616                                 dreg = AMD64_R11;
5617
5618                         amd64_mov_reg_reg (code, dreg, ins->sreg2, size);
5619                         amd64_prefix (code, X86_LOCK_PREFIX);
5620                         amd64_xadd_membase_reg (code, ins->inst_basereg, ins->inst_offset, dreg, size);
5621                         /* dreg contains the old value, add with sreg2 value */
5622                         amd64_alu_reg_reg_size (code, X86_ADD, dreg, ins->sreg2, size);
5623                         
5624                         if (ins->dreg != dreg)
5625                                 amd64_mov_reg_reg (code, ins->dreg, dreg, size);
5626
5627                         break;
5628                 }
5629                 case OP_ATOMIC_EXCHANGE_I4:
5630                 case OP_ATOMIC_EXCHANGE_I8: {
5631                         guchar *br[2];
5632                         int sreg2 = ins->sreg2;
5633                         int breg = ins->inst_basereg;
5634                         guint32 size;
5635                         gboolean need_push = FALSE, rdx_pushed = FALSE;
5636
5637                         if (ins->opcode == OP_ATOMIC_EXCHANGE_I8)
5638                                 size = 8;
5639                         else
5640                                 size = 4;
5641
5642                         /* 
5643                          * See http://msdn.microsoft.com/en-us/magazine/cc302329.aspx for
5644                          * an explanation of how this works.
5645                          */
5646
5647                         /* cmpxchg uses eax as comperand, need to make sure we can use it
5648                          * hack to overcome limits in x86 reg allocator 
5649                          * (req: dreg == eax and sreg2 != eax and breg != eax) 
5650                          */
5651                         g_assert (ins->dreg == AMD64_RAX);
5652
5653                         if (breg == AMD64_RAX && ins->sreg2 == AMD64_RAX)
5654                                 /* Highly unlikely, but possible */
5655                                 need_push = TRUE;
5656
5657                         /* The pushes invalidate rsp */
5658                         if ((breg == AMD64_RAX) || need_push) {
5659                                 amd64_mov_reg_reg (code, AMD64_R11, breg, 8);
5660                                 breg = AMD64_R11;
5661                         }
5662
5663                         /* We need the EAX reg for the comparand */
5664                         if (ins->sreg2 == AMD64_RAX) {
5665                                 if (breg != AMD64_R11) {
5666                                         amd64_mov_reg_reg (code, AMD64_R11, AMD64_RAX, 8);
5667                                         sreg2 = AMD64_R11;
5668                                 } else {
5669                                         g_assert (need_push);
5670                                         amd64_push_reg (code, AMD64_RDX);
5671                                         amd64_mov_reg_reg (code, AMD64_RDX, AMD64_RAX, size);
5672                                         sreg2 = AMD64_RDX;
5673                                         rdx_pushed = TRUE;
5674                                 }
5675                         }
5676
5677                         amd64_mov_reg_membase (code, AMD64_RAX, breg, ins->inst_offset, size);
5678
5679                         br [0] = code; amd64_prefix (code, X86_LOCK_PREFIX);
5680                         amd64_cmpxchg_membase_reg_size (code, breg, ins->inst_offset, sreg2, size);
5681                         br [1] = code; amd64_branch8 (code, X86_CC_NE, -1, FALSE);
5682                         amd64_patch (br [1], br [0]);
5683
5684                         if (rdx_pushed)
5685                                 amd64_pop_reg (code, AMD64_RDX);
5686
5687                         break;
5688                 }
5689                 case OP_ATOMIC_CAS_I4:
5690                 case OP_ATOMIC_CAS_I8: {
5691                         guint32 size;
5692
5693                         if (ins->opcode == OP_ATOMIC_CAS_I8)
5694                                 size = 8;
5695                         else
5696                                 size = 4;
5697
5698                         /* 
5699                          * See http://msdn.microsoft.com/en-us/magazine/cc302329.aspx for
5700                          * an explanation of how this works.
5701                          */
5702                         g_assert (ins->sreg3 == AMD64_RAX);
5703                         g_assert (ins->sreg1 != AMD64_RAX);
5704                         g_assert (ins->sreg1 != ins->sreg2);
5705
5706                         amd64_prefix (code, X86_LOCK_PREFIX);
5707                         amd64_cmpxchg_membase_reg_size (code, ins->sreg1, ins->inst_offset, ins->sreg2, size);
5708
5709                         if (ins->dreg != AMD64_RAX)
5710                                 amd64_mov_reg_reg (code, ins->dreg, AMD64_RAX, size);
5711                         break;
5712                 }
5713                 case OP_CARD_TABLE_WBARRIER: {
5714                         int ptr = ins->sreg1;
5715                         int value = ins->sreg2;
5716                         guchar *br = 0;
5717                         int nursery_shift, card_table_shift;
5718                         gpointer card_table_mask;
5719                         size_t nursery_size;
5720
5721                         gpointer card_table = mono_gc_get_card_table (&card_table_shift, &card_table_mask);
5722                         guint64 nursery_start = (guint64)mono_gc_get_nursery (&nursery_shift, &nursery_size);
5723                         guint64 shifted_nursery_start = nursery_start >> nursery_shift;
5724
5725                         /*If either point to the stack we can simply avoid the WB. This happens due to
5726                          * optimizations revealing a stack store that was not visible when op_cardtable was emited.
5727                          */
5728                         if (ins->sreg1 == AMD64_RSP || ins->sreg2 == AMD64_RSP)
5729                                 continue;
5730
5731                         /*
5732                          * We need one register we can clobber, we choose EDX and make sreg1
5733                          * fixed EAX to work around limitations in the local register allocator.
5734                          * sreg2 might get allocated to EDX, but that is not a problem since
5735                          * we use it before clobbering EDX.
5736                          */
5737                         g_assert (ins->sreg1 == AMD64_RAX);
5738
5739                         /*
5740                          * This is the code we produce:
5741                          *
5742                          *   edx = value
5743                          *   edx >>= nursery_shift
5744                          *   cmp edx, (nursery_start >> nursery_shift)
5745                          *   jne done
5746                          *   edx = ptr
5747                          *   edx >>= card_table_shift
5748                          *   edx += cardtable
5749                          *   [edx] = 1
5750                          * done:
5751                          */
5752
5753                         if (mono_gc_card_table_nursery_check ()) {
5754                                 if (value != AMD64_RDX)
5755                                         amd64_mov_reg_reg (code, AMD64_RDX, value, 8);
5756                                 amd64_shift_reg_imm (code, X86_SHR, AMD64_RDX, nursery_shift);
5757                                 if (shifted_nursery_start >> 31) {
5758                                         /*
5759                                          * The value we need to compare against is 64 bits, so we need
5760                                          * another spare register.  We use RBX, which we save and
5761                                          * restore.
5762                                          */
5763                                         amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RBX, 8);
5764                                         amd64_mov_reg_imm (code, AMD64_RBX, shifted_nursery_start);
5765                                         amd64_alu_reg_reg (code, X86_CMP, AMD64_RDX, AMD64_RBX);
5766                                         amd64_mov_reg_membase (code, AMD64_RBX, AMD64_RSP, -8, 8);
5767                                 } else {
5768                                         amd64_alu_reg_imm (code, X86_CMP, AMD64_RDX, shifted_nursery_start);
5769                                 }
5770                                 br = code; x86_branch8 (code, X86_CC_NE, -1, FALSE);
5771                         }
5772                         amd64_mov_reg_reg (code, AMD64_RDX, ptr, 8);
5773                         amd64_shift_reg_imm (code, X86_SHR, AMD64_RDX, card_table_shift);
5774                         if (card_table_mask)
5775                                 amd64_alu_reg_imm (code, X86_AND, AMD64_RDX, (guint32)(guint64)card_table_mask);
5776
5777                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_GC_CARD_TABLE_ADDR, card_table);
5778                         amd64_alu_reg_membase (code, X86_ADD, AMD64_RDX, AMD64_RIP, 0);
5779
5780                         amd64_mov_membase_imm (code, AMD64_RDX, 0, 1, 1);
5781
5782                         if (mono_gc_card_table_nursery_check ())
5783                                 x86_patch (br, code);
5784                         break;
5785                 }
5786 #ifdef MONO_ARCH_SIMD_INTRINSICS
5787                 /* TODO: Some of these IR opcodes are marked as no clobber when they indeed do. */
5788                 case OP_ADDPS:
5789                         amd64_sse_addps_reg_reg (code, ins->sreg1, ins->sreg2);
5790                         break;
5791                 case OP_DIVPS:
5792                         amd64_sse_divps_reg_reg (code, ins->sreg1, ins->sreg2);
5793                         break;
5794                 case OP_MULPS:
5795                         amd64_sse_mulps_reg_reg (code, ins->sreg1, ins->sreg2);
5796                         break;
5797                 case OP_SUBPS:
5798                         amd64_sse_subps_reg_reg (code, ins->sreg1, ins->sreg2);
5799                         break;
5800                 case OP_MAXPS:
5801                         amd64_sse_maxps_reg_reg (code, ins->sreg1, ins->sreg2);
5802                         break;
5803                 case OP_MINPS:
5804                         amd64_sse_minps_reg_reg (code, ins->sreg1, ins->sreg2);
5805                         break;
5806                 case OP_COMPPS:
5807                         g_assert (ins->inst_c0 >= 0 && ins->inst_c0 <= 7);
5808                         amd64_sse_cmpps_reg_reg_imm (code, ins->sreg1, ins->sreg2, ins->inst_c0);
5809                         break;
5810                 case OP_ANDPS:
5811                         amd64_sse_andps_reg_reg (code, ins->sreg1, ins->sreg2);
5812                         break;
5813                 case OP_ANDNPS:
5814                         amd64_sse_andnps_reg_reg (code, ins->sreg1, ins->sreg2);
5815                         break;
5816                 case OP_ORPS:
5817                         amd64_sse_orps_reg_reg (code, ins->sreg1, ins->sreg2);
5818                         break;
5819                 case OP_XORPS:
5820                         amd64_sse_xorps_reg_reg (code, ins->sreg1, ins->sreg2);
5821                         break;
5822                 case OP_SQRTPS:
5823                         amd64_sse_sqrtps_reg_reg (code, ins->dreg, ins->sreg1);
5824                         break;
5825                 case OP_RSQRTPS:
5826                         amd64_sse_rsqrtps_reg_reg (code, ins->dreg, ins->sreg1);
5827                         break;
5828                 case OP_RCPPS:
5829                         amd64_sse_rcpps_reg_reg (code, ins->dreg, ins->sreg1);
5830                         break;
5831                 case OP_ADDSUBPS:
5832                         amd64_sse_addsubps_reg_reg (code, ins->sreg1, ins->sreg2);
5833                         break;
5834                 case OP_HADDPS:
5835                         amd64_sse_haddps_reg_reg (code, ins->sreg1, ins->sreg2);
5836                         break;
5837                 case OP_HSUBPS:
5838                         amd64_sse_hsubps_reg_reg (code, ins->sreg1, ins->sreg2);
5839                         break;
5840                 case OP_DUPPS_HIGH:
5841                         amd64_sse_movshdup_reg_reg (code, ins->dreg, ins->sreg1);
5842                         break;
5843                 case OP_DUPPS_LOW:
5844                         amd64_sse_movsldup_reg_reg (code, ins->dreg, ins->sreg1);
5845                         break;
5846
5847                 case OP_PSHUFLEW_HIGH:
5848                         g_assert (ins->inst_c0 >= 0 && ins->inst_c0 <= 0xFF);
5849                         amd64_sse_pshufhw_reg_reg_imm (code, ins->dreg, ins->sreg1, ins->inst_c0);
5850                         break;
5851                 case OP_PSHUFLEW_LOW:
5852                         g_assert (ins->inst_c0 >= 0 && ins->inst_c0 <= 0xFF);
5853                         amd64_sse_pshuflw_reg_reg_imm (code, ins->dreg, ins->sreg1, ins->inst_c0);
5854                         break;
5855                 case OP_PSHUFLED:
5856                         g_assert (ins->inst_c0 >= 0 && ins->inst_c0 <= 0xFF);
5857                         amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->sreg1, ins->inst_c0);
5858                         break;
5859                 case OP_SHUFPS:
5860                         g_assert (ins->inst_c0 >= 0 && ins->inst_c0 <= 0xFF);
5861                         amd64_sse_shufps_reg_reg_imm (code, ins->sreg1, ins->sreg2, ins->inst_c0);
5862                         break;
5863                 case OP_SHUFPD:
5864                         g_assert (ins->inst_c0 >= 0 && ins->inst_c0 <= 0x3);
5865                         amd64_sse_shufpd_reg_reg_imm (code, ins->sreg1, ins->sreg2, ins->inst_c0);
5866                         break;
5867
5868                 case OP_ADDPD:
5869                         amd64_sse_addpd_reg_reg (code, ins->sreg1, ins->sreg2);
5870                         break;
5871                 case OP_DIVPD:
5872                         amd64_sse_divpd_reg_reg (code, ins->sreg1, ins->sreg2);
5873                         break;
5874                 case OP_MULPD:
5875                         amd64_sse_mulpd_reg_reg (code, ins->sreg1, ins->sreg2);
5876                         break;
5877                 case OP_SUBPD:
5878                         amd64_sse_subpd_reg_reg (code, ins->sreg1, ins->sreg2);
5879                         break;
5880                 case OP_MAXPD:
5881                         amd64_sse_maxpd_reg_reg (code, ins->sreg1, ins->sreg2);
5882                         break;
5883                 case OP_MINPD:
5884                         amd64_sse_minpd_reg_reg (code, ins->sreg1, ins->sreg2);
5885                         break;
5886                 case OP_COMPPD:
5887                         g_assert (ins->inst_c0 >= 0 && ins->inst_c0 <= 7);
5888                         amd64_sse_cmppd_reg_reg_imm (code, ins->sreg1, ins->sreg2, ins->inst_c0);
5889                         break;
5890                 case OP_ANDPD:
5891                         amd64_sse_andpd_reg_reg (code, ins->sreg1, ins->sreg2);
5892                         break;
5893                 case OP_ANDNPD:
5894                         amd64_sse_andnpd_reg_reg (code, ins->sreg1, ins->sreg2);
5895                         break;
5896                 case OP_ORPD:
5897                         amd64_sse_orpd_reg_reg (code, ins->sreg1, ins->sreg2);
5898                         break;
5899                 case OP_XORPD:
5900                         amd64_sse_xorpd_reg_reg (code, ins->sreg1, ins->sreg2);
5901                         break;
5902                 case OP_SQRTPD:
5903                         amd64_sse_sqrtpd_reg_reg (code, ins->dreg, ins->sreg1);
5904                         break;
5905                 case OP_ADDSUBPD:
5906                         amd64_sse_addsubpd_reg_reg (code, ins->sreg1, ins->sreg2);
5907                         break;
5908                 case OP_HADDPD:
5909                         amd64_sse_haddpd_reg_reg (code, ins->sreg1, ins->sreg2);
5910                         break;
5911                 case OP_HSUBPD:
5912                         amd64_sse_hsubpd_reg_reg (code, ins->sreg1, ins->sreg2);
5913                         break;
5914                 case OP_DUPPD:
5915                         amd64_sse_movddup_reg_reg (code, ins->dreg, ins->sreg1);
5916                         break;
5917
5918                 case OP_EXTRACT_MASK:
5919                         amd64_sse_pmovmskb_reg_reg (code, ins->dreg, ins->sreg1);
5920                         break;
5921
5922                 case OP_PAND:
5923                         amd64_sse_pand_reg_reg (code, ins->sreg1, ins->sreg2);
5924                         break;
5925                 case OP_POR:
5926                         amd64_sse_por_reg_reg (code, ins->sreg1, ins->sreg2);
5927                         break;
5928                 case OP_PXOR:
5929                         amd64_sse_pxor_reg_reg (code, ins->sreg1, ins->sreg2);
5930                         break;
5931
5932                 case OP_PADDB:
5933                         amd64_sse_paddb_reg_reg (code, ins->sreg1, ins->sreg2);
5934                         break;
5935                 case OP_PADDW:
5936                         amd64_sse_paddw_reg_reg (code, ins->sreg1, ins->sreg2);
5937                         break;
5938                 case OP_PADDD:
5939                         amd64_sse_paddd_reg_reg (code, ins->sreg1, ins->sreg2);
5940                         break;
5941                 case OP_PADDQ:
5942                         amd64_sse_paddq_reg_reg (code, ins->sreg1, ins->sreg2);
5943                         break;
5944
5945                 case OP_PSUBB:
5946                         amd64_sse_psubb_reg_reg (code, ins->sreg1, ins->sreg2);
5947                         break;
5948                 case OP_PSUBW:
5949                         amd64_sse_psubw_reg_reg (code, ins->sreg1, ins->sreg2);
5950                         break;
5951                 case OP_PSUBD:
5952                         amd64_sse_psubd_reg_reg (code, ins->sreg1, ins->sreg2);
5953                         break;
5954                 case OP_PSUBQ:
5955                         amd64_sse_psubq_reg_reg (code, ins->sreg1, ins->sreg2);
5956                         break;
5957
5958                 case OP_PMAXB_UN:
5959                         amd64_sse_pmaxub_reg_reg (code, ins->sreg1, ins->sreg2);
5960                         break;
5961                 case OP_PMAXW_UN:
5962                         amd64_sse_pmaxuw_reg_reg (code, ins->sreg1, ins->sreg2);
5963                         break;
5964                 case OP_PMAXD_UN:
5965                         amd64_sse_pmaxud_reg_reg (code, ins->sreg1, ins->sreg2);
5966                         break;
5967                 
5968                 case OP_PMAXB:
5969                         amd64_sse_pmaxsb_reg_reg (code, ins->sreg1, ins->sreg2);
5970                         break;
5971                 case OP_PMAXW:
5972                         amd64_sse_pmaxsw_reg_reg (code, ins->sreg1, ins->sreg2);
5973                         break;
5974                 case OP_PMAXD:
5975                         amd64_sse_pmaxsd_reg_reg (code, ins->sreg1, ins->sreg2);
5976                         break;
5977
5978                 case OP_PAVGB_UN:
5979                         amd64_sse_pavgb_reg_reg (code, ins->sreg1, ins->sreg2);
5980                         break;
5981                 case OP_PAVGW_UN:
5982                         amd64_sse_pavgw_reg_reg (code, ins->sreg1, ins->sreg2);
5983                         break;
5984
5985                 case OP_PMINB_UN:
5986                         amd64_sse_pminub_reg_reg (code, ins->sreg1, ins->sreg2);
5987                         break;
5988                 case OP_PMINW_UN:
5989                         amd64_sse_pminuw_reg_reg (code, ins->sreg1, ins->sreg2);
5990                         break;
5991                 case OP_PMIND_UN:
5992                         amd64_sse_pminud_reg_reg (code, ins->sreg1, ins->sreg2);
5993                         break;
5994
5995                 case OP_PMINB:
5996                         amd64_sse_pminsb_reg_reg (code, ins->sreg1, ins->sreg2);
5997                         break;
5998                 case OP_PMINW:
5999                         amd64_sse_pminsw_reg_reg (code, ins->sreg1, ins->sreg2);
6000                         break;
6001                 case OP_PMIND:
6002                         amd64_sse_pminsd_reg_reg (code, ins->sreg1, ins->sreg2);
6003                         break;
6004
6005                 case OP_PCMPEQB:
6006                         amd64_sse_pcmpeqb_reg_reg (code, ins->sreg1, ins->sreg2);
6007                         break;
6008                 case OP_PCMPEQW:
6009                         amd64_sse_pcmpeqw_reg_reg (code, ins->sreg1, ins->sreg2);
6010                         break;
6011                 case OP_PCMPEQD:
6012                         amd64_sse_pcmpeqd_reg_reg (code, ins->sreg1, ins->sreg2);
6013                         break;
6014                 case OP_PCMPEQQ:
6015                         amd64_sse_pcmpeqq_reg_reg (code, ins->sreg1, ins->sreg2);
6016                         break;
6017
6018                 case OP_PCMPGTB:
6019                         amd64_sse_pcmpgtb_reg_reg (code, ins->sreg1, ins->sreg2);
6020                         break;
6021                 case OP_PCMPGTW:
6022                         amd64_sse_pcmpgtw_reg_reg (code, ins->sreg1, ins->sreg2);
6023                         break;
6024                 case OP_PCMPGTD:
6025                         amd64_sse_pcmpgtd_reg_reg (code, ins->sreg1, ins->sreg2);
6026                         break;
6027                 case OP_PCMPGTQ:
6028                         amd64_sse_pcmpgtq_reg_reg (code, ins->sreg1, ins->sreg2);
6029                         break;
6030
6031                 case OP_PSUM_ABS_DIFF:
6032                         amd64_sse_psadbw_reg_reg (code, ins->sreg1, ins->sreg2);
6033                         break;
6034
6035                 case OP_UNPACK_LOWB:
6036                         amd64_sse_punpcklbw_reg_reg (code, ins->sreg1, ins->sreg2);
6037                         break;
6038                 case OP_UNPACK_LOWW:
6039                         amd64_sse_punpcklwd_reg_reg (code, ins->sreg1, ins->sreg2);
6040                         break;
6041                 case OP_UNPACK_LOWD:
6042                         amd64_sse_punpckldq_reg_reg (code, ins->sreg1, ins->sreg2);
6043                         break;
6044                 case OP_UNPACK_LOWQ:
6045                         amd64_sse_punpcklqdq_reg_reg (code, ins->sreg1, ins->sreg2);
6046                         break;
6047                 case OP_UNPACK_LOWPS:
6048                         amd64_sse_unpcklps_reg_reg (code, ins->sreg1, ins->sreg2);
6049                         break;
6050                 case OP_UNPACK_LOWPD:
6051                         amd64_sse_unpcklpd_reg_reg (code, ins->sreg1, ins->sreg2);
6052                         break;
6053
6054                 case OP_UNPACK_HIGHB:
6055                         amd64_sse_punpckhbw_reg_reg (code, ins->sreg1, ins->sreg2);
6056                         break;
6057                 case OP_UNPACK_HIGHW:
6058                         amd64_sse_punpckhwd_reg_reg (code, ins->sreg1, ins->sreg2);
6059                         break;
6060                 case OP_UNPACK_HIGHD:
6061                         amd64_sse_punpckhdq_reg_reg (code, ins->sreg1, ins->sreg2);
6062                         break;
6063                 case OP_UNPACK_HIGHQ:
6064                         amd64_sse_punpckhqdq_reg_reg (code, ins->sreg1, ins->sreg2);
6065                         break;
6066                 case OP_UNPACK_HIGHPS:
6067                         amd64_sse_unpckhps_reg_reg (code, ins->sreg1, ins->sreg2);
6068                         break;
6069                 case OP_UNPACK_HIGHPD:
6070                         amd64_sse_unpckhpd_reg_reg (code, ins->sreg1, ins->sreg2);
6071                         break;
6072
6073                 case OP_PACKW:
6074                         amd64_sse_packsswb_reg_reg (code, ins->sreg1, ins->sreg2);
6075                         break;
6076                 case OP_PACKD:
6077                         amd64_sse_packssdw_reg_reg (code, ins->sreg1, ins->sreg2);
6078                         break;
6079                 case OP_PACKW_UN:
6080                         amd64_sse_packuswb_reg_reg (code, ins->sreg1, ins->sreg2);
6081                         break;
6082                 case OP_PACKD_UN:
6083                         amd64_sse_packusdw_reg_reg (code, ins->sreg1, ins->sreg2);
6084                         break;
6085
6086                 case OP_PADDB_SAT_UN:
6087                         amd64_sse_paddusb_reg_reg (code, ins->sreg1, ins->sreg2);
6088                         break;
6089                 case OP_PSUBB_SAT_UN:
6090                         amd64_sse_psubusb_reg_reg (code, ins->sreg1, ins->sreg2);
6091                         break;
6092                 case OP_PADDW_SAT_UN:
6093                         amd64_sse_paddusw_reg_reg (code, ins->sreg1, ins->sreg2);
6094                         break;
6095                 case OP_PSUBW_SAT_UN:
6096                         amd64_sse_psubusw_reg_reg (code, ins->sreg1, ins->sreg2);
6097                         break;
6098
6099                 case OP_PADDB_SAT:
6100                         amd64_sse_paddsb_reg_reg (code, ins->sreg1, ins->sreg2);
6101                         break;
6102                 case OP_PSUBB_SAT:
6103                         amd64_sse_psubsb_reg_reg (code, ins->sreg1, ins->sreg2);
6104                         break;
6105                 case OP_PADDW_SAT:
6106                         amd64_sse_paddsw_reg_reg (code, ins->sreg1, ins->sreg2);
6107                         break;
6108                 case OP_PSUBW_SAT:
6109                         amd64_sse_psubsw_reg_reg (code, ins->sreg1, ins->sreg2);
6110                         break;
6111                         
6112                 case OP_PMULW:
6113                         amd64_sse_pmullw_reg_reg (code, ins->sreg1, ins->sreg2);
6114                         break;
6115                 case OP_PMULD:
6116                         amd64_sse_pmulld_reg_reg (code, ins->sreg1, ins->sreg2);
6117                         break;
6118                 case OP_PMULQ:
6119                         amd64_sse_pmuludq_reg_reg (code, ins->sreg1, ins->sreg2);
6120                         break;
6121                 case OP_PMULW_HIGH_UN:
6122                         amd64_sse_pmulhuw_reg_reg (code, ins->sreg1, ins->sreg2);
6123                         break;
6124                 case OP_PMULW_HIGH:
6125                         amd64_sse_pmulhw_reg_reg (code, ins->sreg1, ins->sreg2);
6126                         break;
6127
6128                 case OP_PSHRW:
6129                         amd64_sse_psrlw_reg_imm (code, ins->dreg, ins->inst_imm);
6130                         break;
6131                 case OP_PSHRW_REG:
6132                         amd64_sse_psrlw_reg_reg (code, ins->dreg, ins->sreg2);
6133                         break;
6134
6135                 case OP_PSARW:
6136                         amd64_sse_psraw_reg_imm (code, ins->dreg, ins->inst_imm);
6137                         break;
6138                 case OP_PSARW_REG:
6139                         amd64_sse_psraw_reg_reg (code, ins->dreg, ins->sreg2);
6140                         break;
6141
6142                 case OP_PSHLW:
6143                         amd64_sse_psllw_reg_imm (code, ins->dreg, ins->inst_imm);
6144                         break;
6145                 case OP_PSHLW_REG:
6146                         amd64_sse_psllw_reg_reg (code, ins->dreg, ins->sreg2);
6147                         break;
6148
6149                 case OP_PSHRD:
6150                         amd64_sse_psrld_reg_imm (code, ins->dreg, ins->inst_imm);
6151                         break;
6152                 case OP_PSHRD_REG:
6153                         amd64_sse_psrld_reg_reg (code, ins->dreg, ins->sreg2);
6154                         break;
6155
6156                 case OP_PSARD:
6157                         amd64_sse_psrad_reg_imm (code, ins->dreg, ins->inst_imm);
6158                         break;
6159                 case OP_PSARD_REG:
6160                         amd64_sse_psrad_reg_reg (code, ins->dreg, ins->sreg2);
6161                         break;
6162
6163                 case OP_PSHLD:
6164                         amd64_sse_pslld_reg_imm (code, ins->dreg, ins->inst_imm);
6165                         break;
6166                 case OP_PSHLD_REG:
6167                         amd64_sse_pslld_reg_reg (code, ins->dreg, ins->sreg2);
6168                         break;
6169
6170                 case OP_PSHRQ:
6171                         amd64_sse_psrlq_reg_imm (code, ins->dreg, ins->inst_imm);
6172                         break;
6173                 case OP_PSHRQ_REG:
6174                         amd64_sse_psrlq_reg_reg (code, ins->dreg, ins->sreg2);
6175                         break;
6176                 
6177                 /*TODO: This is appart of the sse spec but not added
6178                 case OP_PSARQ:
6179                         amd64_sse_psraq_reg_imm (code, ins->dreg, ins->inst_imm);
6180                         break;
6181                 case OP_PSARQ_REG:
6182                         amd64_sse_psraq_reg_reg (code, ins->dreg, ins->sreg2);
6183                         break;  
6184                 */
6185         
6186                 case OP_PSHLQ:
6187                         amd64_sse_psllq_reg_imm (code, ins->dreg, ins->inst_imm);
6188                         break;
6189                 case OP_PSHLQ_REG:
6190                         amd64_sse_psllq_reg_reg (code, ins->dreg, ins->sreg2);
6191                         break;  
6192                 case OP_CVTDQ2PD:
6193                         amd64_sse_cvtdq2pd_reg_reg (code, ins->dreg, ins->sreg1);
6194                         break;
6195                 case OP_CVTDQ2PS:
6196                         amd64_sse_cvtdq2ps_reg_reg (code, ins->dreg, ins->sreg1);
6197                         break;
6198                 case OP_CVTPD2DQ:
6199                         amd64_sse_cvtpd2dq_reg_reg (code, ins->dreg, ins->sreg1);
6200                         break;
6201                 case OP_CVTPD2PS:
6202                         amd64_sse_cvtpd2ps_reg_reg (code, ins->dreg, ins->sreg1);
6203                         break;
6204                 case OP_CVTPS2DQ:
6205                         amd64_sse_cvtps2dq_reg_reg (code, ins->dreg, ins->sreg1);
6206                         break;
6207                 case OP_CVTPS2PD:
6208                         amd64_sse_cvtps2pd_reg_reg (code, ins->dreg, ins->sreg1);
6209                         break;
6210                 case OP_CVTTPD2DQ:
6211                         amd64_sse_cvttpd2dq_reg_reg (code, ins->dreg, ins->sreg1);
6212                         break;
6213                 case OP_CVTTPS2DQ:
6214                         amd64_sse_cvttps2dq_reg_reg (code, ins->dreg, ins->sreg1);
6215                         break;
6216
6217                 case OP_ICONV_TO_X:
6218                         amd64_movd_xreg_reg_size (code, ins->dreg, ins->sreg1, 4);
6219                         break;
6220                 case OP_EXTRACT_I4:
6221                         amd64_movd_reg_xreg_size (code, ins->dreg, ins->sreg1, 4);
6222                         break;
6223                 case OP_EXTRACT_I8:
6224                         if (ins->inst_c0) {
6225                                 amd64_movhlps_reg_reg (code, AMD64_XMM15, ins->sreg1);
6226                                 amd64_movd_reg_xreg_size (code, ins->dreg, AMD64_XMM15, 8);
6227                         } else {
6228                                 amd64_movd_reg_xreg_size (code, ins->dreg, ins->sreg1, 8);
6229                         }
6230                         break;
6231                 case OP_EXTRACT_I1:
6232                 case OP_EXTRACT_U1:
6233                         amd64_movd_reg_xreg_size (code, ins->dreg, ins->sreg1, 4);
6234                         if (ins->inst_c0)
6235                                 amd64_shift_reg_imm (code, X86_SHR, ins->dreg, ins->inst_c0 * 8);
6236                         amd64_widen_reg (code, ins->dreg, ins->dreg, ins->opcode == OP_EXTRACT_I1, FALSE);
6237                         break;
6238                 case OP_EXTRACT_I2:
6239                 case OP_EXTRACT_U2:
6240                         /*amd64_movd_reg_xreg_size (code, ins->dreg, ins->sreg1, 4);
6241                         if (ins->inst_c0)
6242                                 amd64_shift_reg_imm_size (code, X86_SHR, ins->dreg, 16, 4);*/
6243                         amd64_sse_pextrw_reg_reg_imm (code, ins->dreg, ins->sreg1, ins->inst_c0);
6244                         amd64_widen_reg_size (code, ins->dreg, ins->dreg, ins->opcode == OP_EXTRACT_I2, TRUE, 4);
6245                         break;
6246                 case OP_EXTRACT_R8:
6247                         if (ins->inst_c0)
6248                                 amd64_movhlps_reg_reg (code, ins->dreg, ins->sreg1);
6249                         else
6250                                 amd64_sse_movsd_reg_reg (code, ins->dreg, ins->sreg1);
6251                         break;
6252                 case OP_INSERT_I2:
6253                         amd64_sse_pinsrw_reg_reg_imm (code, ins->sreg1, ins->sreg2, ins->inst_c0);
6254                         break;
6255                 case OP_EXTRACTX_U2:
6256                         amd64_sse_pextrw_reg_reg_imm (code, ins->dreg, ins->sreg1, ins->inst_c0);
6257                         break;
6258                 case OP_INSERTX_U1_SLOW:
6259                         /*sreg1 is the extracted ireg (scratch)
6260                         /sreg2 is the to be inserted ireg (scratch)
6261                         /dreg is the xreg to receive the value*/
6262
6263                         /*clear the bits from the extracted word*/
6264                         amd64_alu_reg_imm (code, X86_AND, ins->sreg1, ins->inst_c0 & 1 ? 0x00FF : 0xFF00);
6265                         /*shift the value to insert if needed*/
6266                         if (ins->inst_c0 & 1)
6267                                 amd64_shift_reg_imm_size (code, X86_SHL, ins->sreg2, 8, 4);
6268                         /*join them together*/
6269                         amd64_alu_reg_reg (code, X86_OR, ins->sreg1, ins->sreg2);
6270                         amd64_sse_pinsrw_reg_reg_imm (code, ins->dreg, ins->sreg1, ins->inst_c0 / 2);
6271                         break;
6272                 case OP_INSERTX_I4_SLOW:
6273                         amd64_sse_pinsrw_reg_reg_imm (code, ins->dreg, ins->sreg2, ins->inst_c0 * 2);
6274                         amd64_shift_reg_imm (code, X86_SHR, ins->sreg2, 16);
6275                         amd64_sse_pinsrw_reg_reg_imm (code, ins->dreg, ins->sreg2, ins->inst_c0 * 2 + 1);
6276                         break;
6277                 case OP_INSERTX_I8_SLOW:
6278                         amd64_movd_xreg_reg_size(code, AMD64_XMM15, ins->sreg2, 8);
6279                         if (ins->inst_c0)
6280                                 amd64_movlhps_reg_reg (code, ins->dreg, AMD64_XMM15);
6281                         else
6282                                 amd64_sse_movsd_reg_reg (code, ins->dreg, AMD64_XMM15);
6283                         break;
6284
6285                 case OP_INSERTX_R4_SLOW:
6286                         switch (ins->inst_c0) {
6287                         case 0:
6288                                 amd64_sse_cvtsd2ss_reg_reg (code, ins->dreg, ins->sreg2);
6289                                 break;
6290                         case 1:
6291                                 amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, mono_simd_shuffle_mask(1, 0, 2, 3));
6292                                 amd64_sse_cvtsd2ss_reg_reg (code, ins->dreg, ins->sreg2);
6293                                 amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, mono_simd_shuffle_mask(1, 0, 2, 3));
6294                                 break;
6295                         case 2:
6296                                 amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, mono_simd_shuffle_mask(2, 1, 0, 3));
6297                                 amd64_sse_cvtsd2ss_reg_reg (code, ins->dreg, ins->sreg2);
6298                                 amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, mono_simd_shuffle_mask(2, 1, 0, 3));
6299                                 break;
6300                         case 3:
6301                                 amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, mono_simd_shuffle_mask(3, 1, 2, 0));
6302                                 amd64_sse_cvtsd2ss_reg_reg (code, ins->dreg, ins->sreg2);
6303                                 amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, mono_simd_shuffle_mask(3, 1, 2, 0));
6304                                 break;
6305                         }
6306                         break;
6307                 case OP_INSERTX_R8_SLOW:
6308                         if (ins->inst_c0)
6309                                 amd64_movlhps_reg_reg (code, ins->dreg, ins->sreg2);
6310                         else
6311                                 amd64_sse_movsd_reg_reg (code, ins->dreg, ins->sreg2);
6312                         break;
6313                 case OP_STOREX_MEMBASE_REG:
6314                 case OP_STOREX_MEMBASE:
6315                         amd64_sse_movups_membase_reg (code, ins->dreg, ins->inst_offset, ins->sreg1);
6316                         break;
6317                 case OP_LOADX_MEMBASE:
6318                         amd64_sse_movups_reg_membase (code, ins->dreg, ins->sreg1, ins->inst_offset);
6319                         break;
6320                 case OP_LOADX_ALIGNED_MEMBASE:
6321                         amd64_sse_movaps_reg_membase (code, ins->dreg, ins->sreg1, ins->inst_offset);
6322                         break;
6323                 case OP_STOREX_ALIGNED_MEMBASE_REG:
6324                         amd64_sse_movaps_membase_reg (code, ins->dreg, ins->inst_offset, ins->sreg1);
6325                         break;
6326                 case OP_STOREX_NTA_MEMBASE_REG:
6327                         amd64_sse_movntps_reg_membase (code, ins->dreg, ins->sreg1, ins->inst_offset);
6328                         break;
6329                 case OP_PREFETCH_MEMBASE:
6330                         amd64_sse_prefetch_reg_membase (code, ins->backend.arg_info, ins->sreg1, ins->inst_offset);
6331                         break;
6332
6333                 case OP_XMOVE:
6334                         /*FIXME the peephole pass should have killed this*/
6335                         if (ins->dreg != ins->sreg1)
6336                                 amd64_sse_movaps_reg_reg (code, ins->dreg, ins->sreg1);
6337                         break;          
6338                 case OP_XZERO:
6339                         amd64_sse_pxor_reg_reg (code, ins->dreg, ins->dreg);
6340                         break;
6341                 case OP_ICONV_TO_R8_RAW:
6342                         amd64_movd_xreg_reg_size (code, ins->dreg, ins->sreg1, 4);
6343                         amd64_sse_cvtss2sd_reg_reg (code, ins->dreg, ins->dreg);
6344                         break;
6345
6346                 case OP_FCONV_TO_R8_X:
6347                         amd64_sse_movsd_reg_reg (code, ins->dreg, ins->sreg1);
6348                         break;
6349
6350                 case OP_XCONV_R8_TO_I4:
6351                         amd64_sse_cvttsd2si_reg_xreg_size (code, ins->dreg, ins->sreg1, 4);
6352                         switch (ins->backend.source_opcode) {
6353                         case OP_FCONV_TO_I1:
6354                                 amd64_widen_reg (code, ins->dreg, ins->dreg, TRUE, FALSE);
6355                                 break;
6356                         case OP_FCONV_TO_U1:
6357                                 amd64_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
6358                                 break;
6359                         case OP_FCONV_TO_I2:
6360                                 amd64_widen_reg (code, ins->dreg, ins->dreg, TRUE, TRUE);
6361                                 break;
6362                         case OP_FCONV_TO_U2:
6363                                 amd64_widen_reg (code, ins->dreg, ins->dreg, FALSE, TRUE);
6364                                 break;
6365                         }                       
6366                         break;
6367
6368                 case OP_EXPAND_I2:
6369                         amd64_sse_pinsrw_reg_reg_imm (code, ins->dreg, ins->sreg1, 0);
6370                         amd64_sse_pinsrw_reg_reg_imm (code, ins->dreg, ins->sreg1, 1);
6371                         amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, 0);
6372                         break;
6373                 case OP_EXPAND_I4:
6374                         amd64_movd_xreg_reg_size (code, ins->dreg, ins->sreg1, 4);
6375                         amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, 0);
6376                         break;
6377                 case OP_EXPAND_I8:
6378                         amd64_movd_xreg_reg_size (code, ins->dreg, ins->sreg1, 8);
6379                         amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, 0x44);
6380                         break;
6381                 case OP_EXPAND_R4:
6382                         amd64_sse_movsd_reg_reg (code, ins->dreg, ins->sreg1);
6383                         amd64_sse_cvtsd2ss_reg_reg (code, ins->dreg, ins->dreg);
6384                         amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, 0);
6385                         break;
6386                 case OP_EXPAND_R8:
6387                         amd64_sse_movsd_reg_reg (code, ins->dreg, ins->sreg1);
6388                         amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, 0x44);
6389                         break;
6390 #endif
6391                 case OP_LIVERANGE_START: {
6392                         if (cfg->verbose_level > 1)
6393                                 printf ("R%d START=0x%x\n", MONO_VARINFO (cfg, ins->inst_c0)->vreg, (int)(code - cfg->native_code));
6394                         MONO_VARINFO (cfg, ins->inst_c0)->live_range_start = code - cfg->native_code;
6395                         break;
6396                 }
6397                 case OP_LIVERANGE_END: {
6398                         if (cfg->verbose_level > 1)
6399                                 printf ("R%d END=0x%x\n", MONO_VARINFO (cfg, ins->inst_c0)->vreg, (int)(code - cfg->native_code));
6400                         MONO_VARINFO (cfg, ins->inst_c0)->live_range_end = code - cfg->native_code;
6401                         break;
6402                 }
6403                 case OP_NACL_GC_SAFE_POINT: {
6404 #if defined(__native_client_codegen__) && defined(__native_client_gc__)
6405                         if (cfg->compile_aot)
6406                                 code = emit_call (cfg, code, MONO_PATCH_INFO_ABS, (gpointer)mono_nacl_gc, TRUE);
6407                         else {
6408                                 guint8 *br [1];
6409
6410                                 amd64_mov_reg_imm_size (code, AMD64_R11, (gpointer)&__nacl_thread_suspension_needed, 4);
6411                                 amd64_test_membase_imm_size (code, AMD64_R11, 0, 0xFFFFFFFF, 4);
6412                                 br[0] = code; x86_branch8 (code, X86_CC_EQ, 0, FALSE);
6413                                 code = emit_call (cfg, code, MONO_PATCH_INFO_ABS, (gpointer)mono_nacl_gc, TRUE);
6414                                 amd64_patch (br[0], code);
6415                         }
6416 #endif
6417                         break;
6418                 }
6419                 case OP_GC_LIVENESS_DEF:
6420                 case OP_GC_LIVENESS_USE:
6421                 case OP_GC_PARAM_SLOT_LIVENESS_DEF:
6422                         ins->backend.pc_offset = code - cfg->native_code;
6423                         break;
6424                 case OP_GC_SPILL_SLOT_LIVENESS_DEF:
6425                         ins->backend.pc_offset = code - cfg->native_code;
6426                         bb->spill_slot_defs = g_slist_prepend_mempool (cfg->mempool, bb->spill_slot_defs, ins);
6427                         break;
6428                 default:
6429                         g_warning ("unknown opcode %s in %s()\n", mono_inst_name (ins->opcode), __FUNCTION__);
6430                         g_assert_not_reached ();
6431                 }
6432
6433                 if ((code - cfg->native_code - offset) > max_len) {
6434 #if !defined(__native_client_codegen__)
6435                         g_warning ("wrong maximal instruction length of instruction %s (expected %d, got %ld)",
6436                                    mono_inst_name (ins->opcode), max_len, code - cfg->native_code - offset);
6437                         g_assert_not_reached ();
6438 #endif
6439                 }
6440                
6441                 last_ins = ins;
6442                 last_offset = offset;
6443         }
6444
6445         cfg->code_len = code - cfg->native_code;
6446 }
6447
6448 #endif /* DISABLE_JIT */
6449
6450 void
6451 mono_arch_register_lowlevel_calls (void)
6452 {
6453         /* The signature doesn't matter */
6454         mono_register_jit_icall (mono_amd64_throw_exception, "mono_amd64_throw_exception", mono_create_icall_signature ("void"), TRUE);
6455 }
6456
6457 void
6458 mono_arch_patch_code (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *ji, MonoCodeManager *dyn_code_mp, gboolean run_cctors)
6459 {
6460         MonoJumpInfo *patch_info;
6461         gboolean compile_aot = !run_cctors;
6462
6463         for (patch_info = ji; patch_info; patch_info = patch_info->next) {
6464                 unsigned char *ip = patch_info->ip.i + code;
6465                 unsigned char *target;
6466
6467                 if (compile_aot) {
6468                         switch (patch_info->type) {
6469                         case MONO_PATCH_INFO_BB:
6470                         case MONO_PATCH_INFO_LABEL:
6471                                 break;
6472                         default:
6473                                 /* No need to patch these */
6474                                 continue;
6475                         }
6476                 }
6477
6478                 target = mono_resolve_patch_target (method, domain, code, patch_info, run_cctors);
6479
6480                 switch (patch_info->type) {
6481                 case MONO_PATCH_INFO_NONE:
6482                         continue;
6483                 case MONO_PATCH_INFO_METHOD_REL:
6484                 case MONO_PATCH_INFO_R8:
6485                 case MONO_PATCH_INFO_R4:
6486                         g_assert_not_reached ();
6487                         continue;
6488                 case MONO_PATCH_INFO_BB:
6489                         break;
6490                 default:
6491                         break;
6492                 }
6493
6494                 /* 
6495                  * Debug code to help track down problems where the target of a near call is
6496                  * is not valid.
6497                  */
6498                 if (amd64_is_near_call (ip)) {
6499                         gint64 disp = (guint8*)target - (guint8*)ip;
6500
6501                         if (!amd64_is_imm32 (disp)) {
6502                                 printf ("TYPE: %d\n", patch_info->type);
6503                                 switch (patch_info->type) {
6504                                 case MONO_PATCH_INFO_INTERNAL_METHOD:
6505                                         printf ("V: %s\n", patch_info->data.name);
6506                                         break;
6507                                 case MONO_PATCH_INFO_METHOD_JUMP:
6508                                 case MONO_PATCH_INFO_METHOD:
6509                                         printf ("V: %s\n", patch_info->data.method->name);
6510                                         break;
6511                                 default:
6512                                         break;
6513                                 }
6514                         }
6515                 }
6516
6517                 amd64_patch (ip, (gpointer)target);
6518         }
6519 }
6520
6521 #ifndef DISABLE_JIT
6522
6523 static int
6524 get_max_epilog_size (MonoCompile *cfg)
6525 {
6526         int max_epilog_size = 16;
6527         
6528         if (cfg->method->save_lmf)
6529                 max_epilog_size += 256;
6530         
6531         if (mono_jit_trace_calls != NULL)
6532                 max_epilog_size += 50;
6533
6534         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
6535                 max_epilog_size += 50;
6536
6537         max_epilog_size += (AMD64_NREG * 2);
6538
6539         return max_epilog_size;
6540 }
6541
6542 /*
6543  * This macro is used for testing whenever the unwinder works correctly at every point
6544  * where an async exception can happen.
6545  */
6546 /* This will generate a SIGSEGV at the given point in the code */
6547 #define async_exc_point(code) do { \
6548     if (mono_inject_async_exc_method && mono_method_desc_full_match (mono_inject_async_exc_method, cfg->method)) { \
6549          if (cfg->arch.async_point_count == mono_inject_async_exc_pos) \
6550              amd64_mov_reg_mem (code, AMD64_RAX, 0, 4); \
6551          cfg->arch.async_point_count ++; \
6552     } \
6553 } while (0)
6554
6555 guint8 *
6556 mono_arch_emit_prolog (MonoCompile *cfg)
6557 {
6558         MonoMethod *method = cfg->method;
6559         MonoBasicBlock *bb;
6560         MonoMethodSignature *sig;
6561         MonoInst *ins;
6562         int alloc_size, pos, i, cfa_offset, quad, max_epilog_size;
6563         guint8 *code;
6564         CallInfo *cinfo;
6565         MonoInst *lmf_var = cfg->arch.lmf_var;
6566         gboolean args_clobbered = FALSE;
6567         gboolean trace = FALSE;
6568 #ifdef __native_client_codegen__
6569         guint alignment_check;
6570 #endif
6571
6572         cfg->code_size =  MAX (cfg->header->code_size * 4, 10240);
6573
6574 #if defined(__default_codegen__)
6575         code = cfg->native_code = g_malloc (cfg->code_size);
6576 #elif defined(__native_client_codegen__)
6577         /* native_code_alloc is not 32-byte aligned, native_code is. */
6578         cfg->native_code_alloc = g_malloc (cfg->code_size + kNaClAlignment);
6579
6580         /* Align native_code to next nearest kNaclAlignment byte. */
6581         cfg->native_code = (uintptr_t)cfg->native_code_alloc + kNaClAlignment;
6582         cfg->native_code = (uintptr_t)cfg->native_code & ~kNaClAlignmentMask;
6583
6584         code = cfg->native_code;
6585
6586         alignment_check = (guint)cfg->native_code & kNaClAlignmentMask;
6587         g_assert (alignment_check == 0);
6588 #endif
6589
6590         if (mono_jit_trace_calls != NULL && mono_trace_eval (method))
6591                 trace = TRUE;
6592
6593         /* Amount of stack space allocated by register saving code */
6594         pos = 0;
6595
6596         /* Offset between RSP and the CFA */
6597         cfa_offset = 0;
6598
6599         /* 
6600          * The prolog consists of the following parts:
6601          * FP present:
6602          * - push rbp, mov rbp, rsp
6603          * - save callee saved regs using pushes
6604          * - allocate frame
6605          * - save rgctx if needed
6606          * - save lmf if needed
6607          * FP not present:
6608          * - allocate frame
6609          * - save rgctx if needed
6610          * - save lmf if needed
6611          * - save callee saved regs using moves
6612          */
6613
6614         // CFA = sp + 8
6615         cfa_offset = 8;
6616         mono_emit_unwind_op_def_cfa (cfg, code, AMD64_RSP, 8);
6617         // IP saved at CFA - 8
6618         mono_emit_unwind_op_offset (cfg, code, AMD64_RIP, -cfa_offset);
6619         async_exc_point (code);
6620         mini_gc_set_slot_type_from_cfa (cfg, -cfa_offset, SLOT_NOREF);
6621
6622         if (!cfg->arch.omit_fp) {
6623                 amd64_push_reg (code, AMD64_RBP);
6624                 cfa_offset += 8;
6625                 mono_emit_unwind_op_def_cfa_offset (cfg, code, cfa_offset);
6626                 mono_emit_unwind_op_offset (cfg, code, AMD64_RBP, - cfa_offset);
6627                 async_exc_point (code);
6628 #ifdef HOST_WIN32
6629                 mono_arch_unwindinfo_add_push_nonvol (&cfg->arch.unwindinfo, cfg->native_code, code, AMD64_RBP);
6630 #endif
6631                 /* These are handled automatically by the stack marking code */
6632                 mini_gc_set_slot_type_from_cfa (cfg, -cfa_offset, SLOT_NOREF);
6633                 
6634                 amd64_mov_reg_reg (code, AMD64_RBP, AMD64_RSP, sizeof(mgreg_t));
6635                 mono_emit_unwind_op_def_cfa_reg (cfg, code, AMD64_RBP);
6636                 async_exc_point (code);
6637 #ifdef HOST_WIN32
6638                 mono_arch_unwindinfo_add_set_fpreg (&cfg->arch.unwindinfo, cfg->native_code, code, AMD64_RBP);
6639 #endif
6640         }
6641
6642         /* Save callee saved registers */
6643         if (!cfg->arch.omit_fp && !method->save_lmf) {
6644                 int offset = cfa_offset;
6645
6646                 for (i = 0; i < AMD64_NREG; ++i)
6647                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
6648                                 amd64_push_reg (code, i);
6649                                 pos += 8; /* AMD64 push inst is always 8 bytes, no way to change it */
6650                                 offset += 8;
6651                                 mono_emit_unwind_op_offset (cfg, code, i, - offset);
6652                                 async_exc_point (code);
6653
6654                                 /* These are handled automatically by the stack marking code */
6655                                 mini_gc_set_slot_type_from_cfa (cfg, - offset, SLOT_NOREF);
6656                         }
6657         }
6658
6659         /* The param area is always at offset 0 from sp */
6660         /* This needs to be allocated here, since it has to come after the spill area */
6661         if (cfg->arch.no_pushes && cfg->param_area) {
6662                 if (cfg->arch.omit_fp)
6663                         // FIXME:
6664                         g_assert_not_reached ();
6665                 cfg->stack_offset += ALIGN_TO (cfg->param_area, sizeof(mgreg_t));
6666         }
6667
6668         if (cfg->arch.omit_fp) {
6669                 /* 
6670                  * On enter, the stack is misaligned by the pushing of the return
6671                  * address. It is either made aligned by the pushing of %rbp, or by
6672                  * this.
6673                  */
6674                 alloc_size = ALIGN_TO (cfg->stack_offset, 8);
6675                 if ((alloc_size % 16) == 0) {
6676                         alloc_size += 8;
6677                         /* Mark the padding slot as NOREF */
6678                         mini_gc_set_slot_type_from_cfa (cfg, -cfa_offset - sizeof (mgreg_t), SLOT_NOREF);
6679                 }
6680         } else {
6681                 alloc_size = ALIGN_TO (cfg->stack_offset, MONO_ARCH_FRAME_ALIGNMENT);
6682                 if (cfg->stack_offset != alloc_size) {
6683                         /* Mark the padding slot as NOREF */
6684                         mini_gc_set_slot_type_from_fp (cfg, -alloc_size + cfg->param_area, SLOT_NOREF);
6685                 }
6686                 cfg->arch.sp_fp_offset = alloc_size;
6687                 alloc_size -= pos;
6688         }
6689
6690         cfg->arch.stack_alloc_size = alloc_size;
6691
6692         /* Allocate stack frame */
6693         if (alloc_size) {
6694                 /* See mono_emit_stack_alloc */
6695 #if defined(HOST_WIN32) || defined(MONO_ARCH_SIGSEGV_ON_ALTSTACK)
6696                 guint32 remaining_size = alloc_size;
6697                 /*FIXME handle unbounded code expansion, we should use a loop in case of more than X interactions*/
6698                 guint32 required_code_size = ((remaining_size / 0x1000) + 1) * 10; /*10 is the max size of amd64_alu_reg_imm + amd64_test_membase_reg*/
6699                 guint32 offset = code - cfg->native_code;
6700                 if (G_UNLIKELY (required_code_size >= (cfg->code_size - offset))) {
6701                         while (required_code_size >= (cfg->code_size - offset))
6702                                 cfg->code_size *= 2;
6703                         cfg->native_code = mono_realloc_native_code (cfg);
6704                         code = cfg->native_code + offset;
6705                         cfg->stat_code_reallocs++;
6706                 }
6707
6708                 while (remaining_size >= 0x1000) {
6709                         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 0x1000);
6710                         if (cfg->arch.omit_fp) {
6711                                 cfa_offset += 0x1000;
6712                                 mono_emit_unwind_op_def_cfa_offset (cfg, code, cfa_offset);
6713                         }
6714                         async_exc_point (code);
6715 #ifdef HOST_WIN32
6716                         if (cfg->arch.omit_fp) 
6717                                 mono_arch_unwindinfo_add_alloc_stack (&cfg->arch.unwindinfo, cfg->native_code, code, 0x1000);
6718 #endif
6719
6720                         amd64_test_membase_reg (code, AMD64_RSP, 0, AMD64_RSP);
6721                         remaining_size -= 0x1000;
6722                 }
6723                 if (remaining_size) {
6724                         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, remaining_size);
6725                         if (cfg->arch.omit_fp) {
6726                                 cfa_offset += remaining_size;
6727                                 mono_emit_unwind_op_def_cfa_offset (cfg, code, cfa_offset);
6728                                 async_exc_point (code);
6729                         }
6730 #ifdef HOST_WIN32
6731                         if (cfg->arch.omit_fp) 
6732                                 mono_arch_unwindinfo_add_alloc_stack (&cfg->arch.unwindinfo, cfg->native_code, code, remaining_size);
6733 #endif
6734                 }
6735 #else
6736                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, alloc_size);
6737                 if (cfg->arch.omit_fp) {
6738                         cfa_offset += alloc_size;
6739                         mono_emit_unwind_op_def_cfa_offset (cfg, code, cfa_offset);
6740                         async_exc_point (code);
6741                 }
6742 #endif
6743         }
6744
6745         /* Stack alignment check */
6746 #if 0
6747         {
6748                 amd64_mov_reg_reg (code, AMD64_RAX, AMD64_RSP, 8);
6749                 amd64_alu_reg_imm (code, X86_AND, AMD64_RAX, 0xf);
6750                 amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, 0);
6751                 x86_branch8 (code, X86_CC_EQ, 2, FALSE);
6752                 amd64_breakpoint (code);
6753         }
6754 #endif
6755
6756 #ifndef TARGET_WIN32
6757         if (mini_get_debug_options ()->init_stacks) {
6758                 /* Fill the stack frame with a dummy value to force deterministic behavior */
6759         
6760                 /* Save registers to the red zone */
6761                 amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RDI, 8);
6762                 amd64_mov_membase_reg (code, AMD64_RSP, -16, AMD64_RCX, 8);
6763
6764                 amd64_mov_reg_imm (code, AMD64_RAX, 0x2a2a2a2a2a2a2a2a);
6765                 amd64_mov_reg_imm (code, AMD64_RCX, alloc_size / 8);
6766                 amd64_mov_reg_reg (code, AMD64_RDI, AMD64_RSP, 8);
6767
6768                 amd64_cld (code);
6769 #if defined(__default_codegen__)
6770                 amd64_prefix (code, X86_REP_PREFIX);
6771                 amd64_stosl (code);
6772 #elif defined(__native_client_codegen__)
6773                 /* NaCl stos pseudo-instruction */
6774                 amd64_codegen_pre (code);
6775                 /* First, clear the upper 32 bits of RDI (mov %edi, %edi)  */
6776                 amd64_mov_reg_reg (code, AMD64_RDI, AMD64_RDI, 4);
6777                 /* Add %r15 to %rdi using lea, condition flags unaffected. */
6778                 amd64_lea_memindex_size (code, AMD64_RDI, AMD64_R15, 0, AMD64_RDI, 0, 8);
6779                 amd64_prefix (code, X86_REP_PREFIX);
6780                 amd64_stosl (code);
6781                 amd64_codegen_post (code);
6782 #endif /* __native_client_codegen__ */
6783
6784                 amd64_mov_reg_membase (code, AMD64_RDI, AMD64_RSP, -8, 8);
6785                 amd64_mov_reg_membase (code, AMD64_RCX, AMD64_RSP, -16, 8);
6786         }
6787 #endif  
6788
6789         /* Save LMF */
6790         if (method->save_lmf) {
6791                 code = emit_setup_lmf (cfg, code, lmf_var->inst_offset, cfa_offset);
6792         }
6793
6794         /* Save callee saved registers */
6795         if (cfg->arch.omit_fp && !method->save_lmf) {
6796                 gint32 save_area_offset = cfg->arch.reg_save_area_offset;
6797
6798                 /* Save caller saved registers after sp is adjusted */
6799                 /* The registers are saved at the bottom of the frame */
6800                 /* FIXME: Optimize this so the regs are saved at the end of the frame in increasing order */
6801                 for (i = 0; i < AMD64_NREG; ++i)
6802                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
6803                                 amd64_mov_membase_reg (code, AMD64_RSP, save_area_offset, i, 8);
6804                                 mono_emit_unwind_op_offset (cfg, code, i, - (cfa_offset - save_area_offset));
6805
6806                                 /* These are handled automatically by the stack marking code */
6807                                 mini_gc_set_slot_type_from_cfa (cfg, - (cfa_offset - save_area_offset), SLOT_NOREF);
6808
6809                                 save_area_offset += 8;
6810                                 async_exc_point (code);
6811                         }
6812         }
6813
6814         /* store runtime generic context */
6815         if (cfg->rgctx_var) {
6816                 g_assert (cfg->rgctx_var->opcode == OP_REGOFFSET &&
6817                                 (cfg->rgctx_var->inst_basereg == AMD64_RBP || cfg->rgctx_var->inst_basereg == AMD64_RSP));
6818
6819                 amd64_mov_membase_reg (code, cfg->rgctx_var->inst_basereg, cfg->rgctx_var->inst_offset, MONO_ARCH_RGCTX_REG, sizeof(gpointer));
6820
6821                 mono_add_var_location (cfg, cfg->rgctx_var, TRUE, MONO_ARCH_RGCTX_REG, 0, 0, code - cfg->native_code);
6822                 mono_add_var_location (cfg, cfg->rgctx_var, FALSE, cfg->rgctx_var->inst_basereg, cfg->rgctx_var->inst_offset, code - cfg->native_code, 0);
6823         }
6824
6825         /* compute max_length in order to use short forward jumps */
6826         max_epilog_size = get_max_epilog_size (cfg);
6827         if (cfg->opt & MONO_OPT_BRANCH) {
6828                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
6829                         MonoInst *ins;
6830                         int max_length = 0;
6831
6832                         if (cfg->prof_options & MONO_PROFILE_COVERAGE)
6833                                 max_length += 6;
6834                         /* max alignment for loops */
6835                         if ((cfg->opt & MONO_OPT_LOOP) && bb_is_loop_start (bb))
6836                                 max_length += LOOP_ALIGNMENT;
6837 #ifdef __native_client_codegen__
6838                         /* max alignment for native client */
6839                         max_length += kNaClAlignment;
6840 #endif
6841
6842                         MONO_BB_FOR_EACH_INS (bb, ins) {
6843 #ifdef __native_client_codegen__
6844                                 {
6845                                         int space_in_block = kNaClAlignment -
6846                                                 ((max_length + cfg->code_len) & kNaClAlignmentMask);
6847                                         int max_len = ((guint8 *)ins_get_spec (ins->opcode))[MONO_INST_LEN];
6848                                         if (space_in_block < max_len && max_len < kNaClAlignment) {
6849                                                 max_length += space_in_block;
6850                                         }
6851                                 }
6852 #endif  /*__native_client_codegen__*/
6853                                 max_length += ((guint8 *)ins_get_spec (ins->opcode))[MONO_INST_LEN];
6854                         }
6855
6856                         /* Take prolog and epilog instrumentation into account */
6857                         if (bb == cfg->bb_entry || bb == cfg->bb_exit)
6858                                 max_length += max_epilog_size;
6859                         
6860                         bb->max_length = max_length;
6861                 }
6862         }
6863
6864         sig = mono_method_signature (method);
6865         pos = 0;
6866
6867         cinfo = cfg->arch.cinfo;
6868
6869         if (sig->ret->type != MONO_TYPE_VOID) {
6870                 /* Save volatile arguments to the stack */
6871                 if (cfg->vret_addr && (cfg->vret_addr->opcode != OP_REGVAR))
6872                         amd64_mov_membase_reg (code, cfg->vret_addr->inst_basereg, cfg->vret_addr->inst_offset, cinfo->ret.reg, 8);
6873         }
6874
6875         /* Keep this in sync with emit_load_volatile_arguments */
6876         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6877                 ArgInfo *ainfo = cinfo->args + i;
6878                 gint32 stack_offset;
6879                 MonoType *arg_type;
6880
6881                 ins = cfg->args [i];
6882
6883                 if ((ins->flags & MONO_INST_IS_DEAD) && !trace)
6884                         /* Unused arguments */
6885                         continue;
6886
6887                 if (sig->hasthis && (i == 0))
6888                         arg_type = &mono_defaults.object_class->byval_arg;
6889                 else
6890                         arg_type = sig->params [i - sig->hasthis];
6891
6892                 stack_offset = ainfo->offset + ARGS_OFFSET;
6893
6894                 if (cfg->globalra) {
6895                         /* All the other moves are done by the register allocator */
6896                         switch (ainfo->storage) {
6897                         case ArgInFloatSSEReg:
6898                                 amd64_sse_cvtss2sd_reg_reg (code, ainfo->reg, ainfo->reg);
6899                                 break;
6900                         case ArgValuetypeInReg:
6901                                 for (quad = 0; quad < 2; quad ++) {
6902                                         switch (ainfo->pair_storage [quad]) {
6903                                         case ArgInIReg:
6904                                                 amd64_mov_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof(mgreg_t)), ainfo->pair_regs [quad], sizeof(mgreg_t));
6905                                                 break;
6906                                         case ArgInFloatSSEReg:
6907                                                 amd64_movss_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof(mgreg_t)), ainfo->pair_regs [quad]);
6908                                                 break;
6909                                         case ArgInDoubleSSEReg:
6910                                                 amd64_movsd_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof(mgreg_t)), ainfo->pair_regs [quad]);
6911                                                 break;
6912                                         case ArgNone:
6913                                                 break;
6914                                         default:
6915                                                 g_assert_not_reached ();
6916                                         }
6917                                 }
6918                                 break;
6919                         default:
6920                                 break;
6921                         }
6922
6923                         continue;
6924                 }
6925
6926                 /* Save volatile arguments to the stack */
6927                 if (ins->opcode != OP_REGVAR) {
6928                         switch (ainfo->storage) {
6929                         case ArgInIReg: {
6930                                 guint32 size = 8;
6931
6932                                 /* FIXME: I1 etc */
6933                                 /*
6934                                 if (stack_offset & 0x1)
6935                                         size = 1;
6936                                 else if (stack_offset & 0x2)
6937                                         size = 2;
6938                                 else if (stack_offset & 0x4)
6939                                         size = 4;
6940                                 else
6941                                         size = 8;
6942                                 */
6943                                 amd64_mov_membase_reg (code, ins->inst_basereg, ins->inst_offset, ainfo->reg, size);
6944
6945                                 /*
6946                                  * Save the original location of 'this',
6947                                  * get_generic_info_from_stack_frame () needs this to properly look up
6948                                  * the argument value during the handling of async exceptions.
6949                                  */
6950                                 if (ins == cfg->args [0]) {
6951                                         mono_add_var_location (cfg, ins, TRUE, ainfo->reg, 0, 0, code - cfg->native_code);
6952                                         mono_add_var_location (cfg, ins, FALSE, ins->inst_basereg, ins->inst_offset, code - cfg->native_code, 0);
6953                                 }
6954                                 break;
6955                         }
6956                         case ArgInFloatSSEReg:
6957                                 amd64_movss_membase_reg (code, ins->inst_basereg, ins->inst_offset, ainfo->reg);
6958                                 break;
6959                         case ArgInDoubleSSEReg:
6960                                 amd64_movsd_membase_reg (code, ins->inst_basereg, ins->inst_offset, ainfo->reg);
6961                                 break;
6962                         case ArgValuetypeInReg:
6963                                 for (quad = 0; quad < 2; quad ++) {
6964                                         switch (ainfo->pair_storage [quad]) {
6965                                         case ArgInIReg:
6966                                                 amd64_mov_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof(mgreg_t)), ainfo->pair_regs [quad], sizeof(mgreg_t));
6967                                                 break;
6968                                         case ArgInFloatSSEReg:
6969                                                 amd64_movss_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof(mgreg_t)), ainfo->pair_regs [quad]);
6970                                                 break;
6971                                         case ArgInDoubleSSEReg:
6972                                                 amd64_movsd_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof(mgreg_t)), ainfo->pair_regs [quad]);
6973                                                 break;
6974                                         case ArgNone:
6975                                                 break;
6976                                         default:
6977                                                 g_assert_not_reached ();
6978                                         }
6979                                 }
6980                                 break;
6981                         case ArgValuetypeAddrInIReg:
6982                                 if (ainfo->pair_storage [0] == ArgInIReg)
6983                                         amd64_mov_membase_reg (code, ins->inst_left->inst_basereg, ins->inst_left->inst_offset, ainfo->pair_regs [0],  sizeof (gpointer));
6984                                 break;
6985                         default:
6986                                 break;
6987                         }
6988                 } else {
6989                         /* Argument allocated to (non-volatile) register */
6990                         switch (ainfo->storage) {
6991                         case ArgInIReg:
6992                                 amd64_mov_reg_reg (code, ins->dreg, ainfo->reg, 8);
6993                                 break;
6994                         case ArgOnStack:
6995                                 amd64_mov_reg_membase (code, ins->dreg, AMD64_RBP, ARGS_OFFSET + ainfo->offset, 8);
6996                                 break;
6997                         default:
6998                                 g_assert_not_reached ();
6999                         }
7000
7001                         if (ins == cfg->args [0]) {
7002                                 mono_add_var_location (cfg, ins, TRUE, ainfo->reg, 0, 0, code - cfg->native_code);
7003                                 mono_add_var_location (cfg, ins, TRUE, ins->dreg, 0, code - cfg->native_code, 0);
7004                         }
7005                 }
7006         }
7007
7008         if (method->save_lmf) {
7009                 code = emit_save_lmf (cfg, code, lmf_var->inst_offset, &args_clobbered);
7010         }
7011
7012         if (trace) {
7013                 args_clobbered = TRUE;
7014                 code = mono_arch_instrument_prolog (cfg, mono_trace_enter_method, code, TRUE);
7015         }
7016
7017         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
7018                 args_clobbered = TRUE;
7019
7020         /*
7021          * Optimize the common case of the first bblock making a call with the same
7022          * arguments as the method. This works because the arguments are still in their
7023          * original argument registers.
7024          * FIXME: Generalize this
7025          */
7026         if (!args_clobbered) {
7027                 MonoBasicBlock *first_bb = cfg->bb_entry;
7028                 MonoInst *next;
7029
7030                 next = mono_bb_first_ins (first_bb);
7031                 if (!next && first_bb->next_bb) {
7032                         first_bb = first_bb->next_bb;
7033                         next = mono_bb_first_ins (first_bb);
7034                 }
7035
7036                 if (first_bb->in_count > 1)
7037                         next = NULL;
7038
7039                 for (i = 0; next && i < sig->param_count + sig->hasthis; ++i) {
7040                         ArgInfo *ainfo = cinfo->args + i;
7041                         gboolean match = FALSE;
7042                         
7043                         ins = cfg->args [i];
7044                         if (ins->opcode != OP_REGVAR) {
7045                                 switch (ainfo->storage) {
7046                                 case ArgInIReg: {
7047                                         if (((next->opcode == OP_LOAD_MEMBASE) || (next->opcode == OP_LOADI4_MEMBASE)) && next->inst_basereg == ins->inst_basereg && next->inst_offset == ins->inst_offset) {
7048                                                 if (next->dreg == ainfo->reg) {
7049                                                         NULLIFY_INS (next);
7050                                                         match = TRUE;
7051                                                 } else {
7052                                                         next->opcode = OP_MOVE;
7053                                                         next->sreg1 = ainfo->reg;
7054                                                         /* Only continue if the instruction doesn't change argument regs */
7055                                                         if (next->dreg == ainfo->reg || next->dreg == AMD64_RAX)
7056                                                                 match = TRUE;
7057                                                 }
7058                                         }
7059                                         break;
7060                                 }
7061                                 default:
7062                                         break;
7063                                 }
7064                         } else {
7065                                 /* Argument allocated to (non-volatile) register */
7066                                 switch (ainfo->storage) {
7067                                 case ArgInIReg:
7068                                         if (next->opcode == OP_MOVE && next->sreg1 == ins->dreg && next->dreg == ainfo->reg) {
7069                                                 NULLIFY_INS (next);
7070                                                 match = TRUE;
7071                                         }
7072                                         break;
7073                                 default:
7074                                         break;
7075                                 }
7076                         }
7077
7078                         if (match) {
7079                                 next = next->next;
7080                                 //next = mono_inst_list_next (&next->node, &first_bb->ins_list);
7081                                 if (!next)
7082                                         break;
7083                         }
7084                 }
7085         }
7086
7087         if (cfg->gen_seq_points) {
7088                 MonoInst *info_var = cfg->arch.seq_point_info_var;
7089
7090                 /* Initialize seq_point_info_var */
7091                 if (cfg->compile_aot) {
7092                         /* Initialize the variable from a GOT slot */
7093                         /* Same as OP_AOTCONST */
7094                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_SEQ_POINT_INFO, cfg->method);
7095                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, sizeof(gpointer));
7096                         g_assert (info_var->opcode == OP_REGOFFSET);
7097                         amd64_mov_membase_reg (code, info_var->inst_basereg, info_var->inst_offset, AMD64_R11, 8);
7098                 }
7099
7100                 /* Initialize ss_trigger_page_var */
7101                 ins = cfg->arch.ss_trigger_page_var;
7102
7103                 g_assert (ins->opcode == OP_REGOFFSET);
7104
7105                 if (cfg->compile_aot) {
7106                         amd64_mov_reg_membase (code, AMD64_R11, info_var->inst_basereg, info_var->inst_offset, 8);
7107                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, G_STRUCT_OFFSET (SeqPointInfo, ss_trigger_page), 8);
7108                 } else {
7109                         amd64_mov_reg_imm (code, AMD64_R11, (guint64)ss_trigger_page);
7110                 }
7111                 amd64_mov_membase_reg (code, ins->inst_basereg, ins->inst_offset, AMD64_R11, 8);
7112         }
7113
7114         cfg->code_len = code - cfg->native_code;
7115
7116         g_assert (cfg->code_len < cfg->code_size);
7117
7118         return code;
7119 }
7120
7121 void
7122 mono_arch_emit_epilog (MonoCompile *cfg)
7123 {
7124         MonoMethod *method = cfg->method;
7125         int quad, pos, i;
7126         guint8 *code;
7127         int max_epilog_size;
7128         CallInfo *cinfo;
7129         gint32 lmf_offset = cfg->arch.lmf_var ? ((MonoInst*)cfg->arch.lmf_var)->inst_offset : -1;
7130         
7131         max_epilog_size = get_max_epilog_size (cfg);
7132
7133         while (cfg->code_len + max_epilog_size > (cfg->code_size - 16)) {
7134                 cfg->code_size *= 2;
7135                 cfg->native_code = mono_realloc_native_code (cfg);
7136                 cfg->stat_code_reallocs++;
7137         }
7138
7139         code = cfg->native_code + cfg->code_len;
7140
7141         if (mono_jit_trace_calls != NULL && mono_trace_eval (method))
7142                 code = mono_arch_instrument_epilog (cfg, mono_trace_leave_method, code, TRUE);
7143
7144         /* the code restoring the registers must be kept in sync with OP_JMP */
7145         pos = 0;
7146         
7147         if (method->save_lmf) {
7148                 /* check if we need to restore protection of the stack after a stack overflow */
7149                 if (mono_get_jit_tls_offset () != -1) {
7150                         guint8 *patch;
7151                         code = mono_amd64_emit_tls_get (code, AMD64_RCX, mono_get_jit_tls_offset ());
7152                         /* we load the value in a separate instruction: this mechanism may be
7153                          * used later as a safer way to do thread interruption
7154                          */
7155                         amd64_mov_reg_membase (code, AMD64_RCX, AMD64_RCX, G_STRUCT_OFFSET (MonoJitTlsData, restore_stack_prot), 8);
7156                         x86_alu_reg_imm (code, X86_CMP, X86_ECX, 0);
7157                         patch = code;
7158                         x86_branch8 (code, X86_CC_Z, 0, FALSE);
7159                         /* note that the call trampoline will preserve eax/edx */
7160                         x86_call_reg (code, X86_ECX);
7161                         x86_patch (patch, code);
7162                 } else {
7163                         /* FIXME: maybe save the jit tls in the prolog */
7164                 }
7165
7166                 code = emit_restore_lmf (cfg, code, lmf_offset);
7167
7168                 /* Restore caller saved regs */
7169                 if (cfg->used_int_regs & (1 << AMD64_RBP)) {
7170                         amd64_mov_reg_membase (code, AMD64_RBP, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbp), 8);
7171                 }
7172                 if (cfg->used_int_regs & (1 << AMD64_RBX)) {
7173                         amd64_mov_reg_membase (code, AMD64_RBX, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbx), 8);
7174                 }
7175                 if (cfg->used_int_regs & (1 << AMD64_R12)) {
7176                         amd64_mov_reg_membase (code, AMD64_R12, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r12), 8);
7177                 }
7178                 if (cfg->used_int_regs & (1 << AMD64_R13)) {
7179                         amd64_mov_reg_membase (code, AMD64_R13, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r13), 8);
7180                 }
7181                 if (cfg->used_int_regs & (1 << AMD64_R14)) {
7182                         amd64_mov_reg_membase (code, AMD64_R14, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r14), 8);
7183                 }
7184                 if (cfg->used_int_regs & (1 << AMD64_R15)) {
7185 #if defined(__default_codegen__)
7186                         amd64_mov_reg_membase (code, AMD64_R15, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r15), 8);
7187 #elif defined(__native_client_codegen__)
7188                         g_assert_not_reached();
7189 #endif
7190                 }
7191 #ifdef HOST_WIN32
7192                 if (cfg->used_int_regs & (1 << AMD64_RDI)) {
7193                         amd64_mov_reg_membase (code, AMD64_RDI, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rdi), 8);
7194                 }
7195                 if (cfg->used_int_regs & (1 << AMD64_RSI)) {
7196                         amd64_mov_reg_membase (code, AMD64_RSI, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rsi), 8);
7197                 }
7198 #endif
7199         } else {
7200
7201                 if (cfg->arch.omit_fp) {
7202                         gint32 save_area_offset = cfg->arch.reg_save_area_offset;
7203
7204                         for (i = 0; i < AMD64_NREG; ++i)
7205                                 if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
7206                                         amd64_mov_reg_membase (code, i, AMD64_RSP, save_area_offset, 8);
7207                                         save_area_offset += 8;
7208                                 }
7209                 }
7210                 else {
7211                         for (i = 0; i < AMD64_NREG; ++i)
7212                                 if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i)))
7213                                         pos -= sizeof(mgreg_t);
7214
7215                         if (pos) {
7216                                 if (pos == - sizeof(mgreg_t)) {
7217                                         /* Only one register, so avoid lea */
7218                                         for (i = AMD64_NREG - 1; i > 0; --i)
7219                                                 if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
7220                                                         amd64_mov_reg_membase (code, i, AMD64_RBP, pos, 8);
7221                                                 }
7222                                 }
7223                                 else {
7224                                         amd64_lea_membase (code, AMD64_RSP, AMD64_RBP, pos);
7225
7226                                         /* Pop registers in reverse order */
7227                                         for (i = AMD64_NREG - 1; i > 0; --i)
7228                                                 if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
7229                                                         amd64_pop_reg (code, i);
7230                                                 }
7231                                 }
7232                         }
7233                 }
7234         }
7235
7236         /* Load returned vtypes into registers if needed */
7237         cinfo = cfg->arch.cinfo;
7238         if (cinfo->ret.storage == ArgValuetypeInReg) {
7239                 ArgInfo *ainfo = &cinfo->ret;
7240                 MonoInst *inst = cfg->ret;
7241
7242                 for (quad = 0; quad < 2; quad ++) {
7243                         switch (ainfo->pair_storage [quad]) {
7244                         case ArgInIReg:
7245                                 amd64_mov_reg_membase (code, ainfo->pair_regs [quad], inst->inst_basereg, inst->inst_offset + (quad * sizeof(mgreg_t)), sizeof(mgreg_t));
7246                                 break;
7247                         case ArgInFloatSSEReg:
7248                                 amd64_movss_reg_membase (code, ainfo->pair_regs [quad], inst->inst_basereg, inst->inst_offset + (quad * sizeof(mgreg_t)));
7249                                 break;
7250                         case ArgInDoubleSSEReg:
7251                                 amd64_movsd_reg_membase (code, ainfo->pair_regs [quad], inst->inst_basereg, inst->inst_offset + (quad * sizeof(mgreg_t)));
7252                                 break;
7253                         case ArgNone:
7254                                 break;
7255                         default:
7256                                 g_assert_not_reached ();
7257                         }
7258                 }
7259         }
7260
7261         if (cfg->arch.omit_fp) {
7262                 if (cfg->arch.stack_alloc_size)
7263                         amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, cfg->arch.stack_alloc_size);
7264         } else {
7265                 amd64_leave (code);
7266         }
7267         async_exc_point (code);
7268         amd64_ret (code);
7269
7270         cfg->code_len = code - cfg->native_code;
7271
7272         g_assert (cfg->code_len < cfg->code_size);
7273 }
7274
7275 void
7276 mono_arch_emit_exceptions (MonoCompile *cfg)
7277 {
7278         MonoJumpInfo *patch_info;
7279         int nthrows, i;
7280         guint8 *code;
7281         MonoClass *exc_classes [16];
7282         guint8 *exc_throw_start [16], *exc_throw_end [16];
7283         guint32 code_size = 0;
7284
7285         /* Compute needed space */
7286         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7287                 if (patch_info->type == MONO_PATCH_INFO_EXC)
7288                         code_size += 40;
7289                 if (patch_info->type == MONO_PATCH_INFO_R8)
7290                         code_size += 8 + 15; /* sizeof (double) + alignment */
7291                 if (patch_info->type == MONO_PATCH_INFO_R4)
7292                         code_size += 4 + 15; /* sizeof (float) + alignment */
7293                 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR)
7294                         code_size += 8 + 7; /*sizeof (void*) + alignment */
7295         }
7296
7297 #ifdef __native_client_codegen__
7298         /* Give us extra room on Native Client.  This could be   */
7299         /* more carefully calculated, but bundle alignment makes */
7300         /* it much trickier, so *2 like other places is good.    */
7301         code_size *= 2;
7302 #endif
7303
7304         while (cfg->code_len + code_size > (cfg->code_size - 16)) {
7305                 cfg->code_size *= 2;
7306                 cfg->native_code = mono_realloc_native_code (cfg);
7307                 cfg->stat_code_reallocs++;
7308         }
7309
7310         code = cfg->native_code + cfg->code_len;
7311
7312         /* add code to raise exceptions */
7313         nthrows = 0;
7314         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7315                 switch (patch_info->type) {
7316                 case MONO_PATCH_INFO_EXC: {
7317                         MonoClass *exc_class;
7318                         guint8 *buf, *buf2;
7319                         guint32 throw_ip;
7320
7321                         amd64_patch (patch_info->ip.i + cfg->native_code, code);
7322
7323                         exc_class = mono_class_from_name (mono_defaults.corlib, "System", patch_info->data.name);
7324                         g_assert (exc_class);
7325                         throw_ip = patch_info->ip.i;
7326
7327                         //x86_breakpoint (code);
7328                         /* Find a throw sequence for the same exception class */
7329                         for (i = 0; i < nthrows; ++i)
7330                                 if (exc_classes [i] == exc_class)
7331                                         break;
7332                         if (i < nthrows) {
7333                                 amd64_mov_reg_imm (code, AMD64_ARG_REG2, (exc_throw_end [i] - cfg->native_code) - throw_ip);
7334                                 x86_jump_code (code, exc_throw_start [i]);
7335                                 patch_info->type = MONO_PATCH_INFO_NONE;
7336                         }
7337                         else {
7338                                 buf = code;
7339                                 amd64_mov_reg_imm_size (code, AMD64_ARG_REG2, 0xf0f0f0f0, 4);
7340                                 buf2 = code;
7341
7342                                 if (nthrows < 16) {
7343                                         exc_classes [nthrows] = exc_class;
7344                                         exc_throw_start [nthrows] = code;
7345                                 }
7346                                 amd64_mov_reg_imm (code, AMD64_ARG_REG1, exc_class->type_token - MONO_TOKEN_TYPE_DEF);
7347
7348                                 patch_info->type = MONO_PATCH_INFO_NONE;
7349
7350                                 code = emit_call_body (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD, "mono_arch_throw_corlib_exception");
7351
7352                                 amd64_mov_reg_imm (buf, AMD64_ARG_REG2, (code - cfg->native_code) - throw_ip);
7353                                 while (buf < buf2)
7354                                         x86_nop (buf);
7355
7356                                 if (nthrows < 16) {
7357                                         exc_throw_end [nthrows] = code;
7358                                         nthrows ++;
7359                                 }
7360                         }
7361                         break;
7362                 }
7363                 default:
7364                         /* do nothing */
7365                         break;
7366                 }
7367                 g_assert(code < cfg->native_code + cfg->code_size);
7368         }
7369
7370         /* Handle relocations with RIP relative addressing */
7371         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7372                 gboolean remove = FALSE;
7373                 guint8 *orig_code = code;
7374
7375                 switch (patch_info->type) {
7376                 case MONO_PATCH_INFO_R8:
7377                 case MONO_PATCH_INFO_R4: {
7378                         guint8 *pos, *patch_pos;
7379                         guint32 target_pos;
7380
7381                         /* The SSE opcodes require a 16 byte alignment */
7382 #if defined(__default_codegen__)
7383                         code = (guint8*)ALIGN_TO (code, 16);
7384 #elif defined(__native_client_codegen__)
7385                         {
7386                                 /* Pad this out with HLT instructions  */
7387                                 /* or we can get garbage bytes emitted */
7388                                 /* which will fail validation          */
7389                                 guint8 *aligned_code;
7390                                 /* extra align to make room for  */
7391                                 /* mov/push below                      */
7392                                 int extra_align = patch_info->type == MONO_PATCH_INFO_R8 ? 2 : 1;
7393                                 aligned_code = (guint8*)ALIGN_TO (code + extra_align, 16);
7394                                 /* The technique of hiding data in an  */
7395                                 /* instruction has a problem here: we  */
7396                                 /* need the data aligned to a 16-byte  */
7397                                 /* boundary but the instruction cannot */
7398                                 /* cross the bundle boundary. so only  */
7399                                 /* odd multiples of 16 can be used     */
7400                                 if ((intptr_t)aligned_code % kNaClAlignment == 0) {
7401                                         aligned_code += 16;
7402                                 }
7403                                 while (code < aligned_code) {
7404                                         *(code++) = 0xf4; /* hlt */
7405                                 }
7406                         }       
7407 #endif
7408
7409                         pos = cfg->native_code + patch_info->ip.i;
7410                         if (IS_REX (pos [1])) {
7411                                 patch_pos = pos + 5;
7412                                 target_pos = code - pos - 9;
7413                         }
7414                         else {
7415                                 patch_pos = pos + 4;
7416                                 target_pos = code - pos - 8;
7417                         }
7418
7419                         if (patch_info->type == MONO_PATCH_INFO_R8) {
7420 #ifdef __native_client_codegen__
7421                                 /* Hide 64-bit data in a         */
7422                                 /* "mov imm64, r11" instruction. */
7423                                 /* write it before the start of  */
7424                                 /* the data*/
7425                                 *(code-2) = 0x49; /* prefix      */
7426                                 *(code-1) = 0xbb; /* mov X, %r11 */
7427 #endif
7428                                 *(double*)code = *(double*)patch_info->data.target;
7429                                 code += sizeof (double);
7430                         } else {
7431 #ifdef __native_client_codegen__
7432                                 /* Hide 32-bit data in a        */
7433                                 /* "push imm32" instruction.    */
7434                                 *(code-1) = 0x68; /* push */
7435 #endif
7436                                 *(float*)code = *(float*)patch_info->data.target;
7437                                 code += sizeof (float);
7438                         }
7439
7440                         *(guint32*)(patch_pos) = target_pos;
7441
7442                         remove = TRUE;
7443                         break;
7444                 }
7445                 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR: {
7446                         guint8 *pos;
7447
7448                         if (cfg->compile_aot)
7449                                 continue;
7450
7451                         /*loading is faster against aligned addresses.*/
7452                         code = (guint8*)ALIGN_TO (code, 8);
7453                         memset (orig_code, 0, code - orig_code);
7454
7455                         pos = cfg->native_code + patch_info->ip.i;
7456
7457                         /*alu_op [rex] modr/m imm32 - 7 or 8 bytes */
7458                         if (IS_REX (pos [1]))
7459                                 *(guint32*)(pos + 4) = (guint8*)code - pos - 8;
7460                         else
7461                                 *(guint32*)(pos + 3) = (guint8*)code - pos - 7;
7462
7463                         *(gpointer*)code = (gpointer)patch_info->data.target;
7464                         code += sizeof (gpointer);
7465
7466                         remove = TRUE;
7467                         break;
7468                 }
7469                 default:
7470                         break;
7471                 }
7472
7473                 if (remove) {
7474                         if (patch_info == cfg->patch_info)
7475                                 cfg->patch_info = patch_info->next;
7476                         else {
7477                                 MonoJumpInfo *tmp;
7478
7479                                 for (tmp = cfg->patch_info; tmp->next != patch_info; tmp = tmp->next)
7480                                         ;
7481                                 tmp->next = patch_info->next;
7482                         }
7483                 }
7484                 g_assert (code < cfg->native_code + cfg->code_size);
7485         }
7486
7487         cfg->code_len = code - cfg->native_code;
7488
7489         g_assert (cfg->code_len < cfg->code_size);
7490
7491 }
7492
7493 #endif /* DISABLE_JIT */
7494
7495 void*
7496 mono_arch_instrument_prolog (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments)
7497 {
7498         guchar *code = p;
7499         CallInfo *cinfo = NULL;
7500         MonoMethodSignature *sig;
7501         MonoInst *inst;
7502         int i, n, stack_area = 0;
7503
7504         /* Keep this in sync with mono_arch_get_argument_info */
7505
7506         if (enable_arguments) {
7507                 /* Allocate a new area on the stack and save arguments there */
7508                 sig = mono_method_signature (cfg->method);
7509
7510                 cinfo = get_call_info (cfg->generic_sharing_context, cfg->mempool, sig);
7511
7512                 n = sig->param_count + sig->hasthis;
7513
7514                 stack_area = ALIGN_TO (n * 8, 16);
7515
7516                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, stack_area);
7517
7518                 for (i = 0; i < n; ++i) {
7519                         inst = cfg->args [i];
7520
7521                         if (inst->opcode == OP_REGVAR)
7522                                 amd64_mov_membase_reg (code, AMD64_RSP, (i * 8), inst->dreg, 8);
7523                         else {
7524                                 amd64_mov_reg_membase (code, AMD64_R11, inst->inst_basereg, inst->inst_offset, 8);
7525                                 amd64_mov_membase_reg (code, AMD64_RSP, (i * 8), AMD64_R11, 8);
7526                         }
7527                 }
7528         }
7529
7530         mono_add_patch_info (cfg, code-cfg->native_code, MONO_PATCH_INFO_METHODCONST, cfg->method);
7531         amd64_set_reg_template (code, AMD64_ARG_REG1);
7532         amd64_mov_reg_reg (code, AMD64_ARG_REG2, AMD64_RSP, 8);
7533         code = emit_call (cfg, code, MONO_PATCH_INFO_ABS, (gpointer)func, TRUE);
7534
7535         if (enable_arguments)
7536                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, stack_area);
7537
7538         return code;
7539 }
7540
7541 enum {
7542         SAVE_NONE,
7543         SAVE_STRUCT,
7544         SAVE_EAX,
7545         SAVE_EAX_EDX,
7546         SAVE_XMM
7547 };
7548
7549 void*
7550 mono_arch_instrument_epilog_full (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments, gboolean preserve_argument_registers)
7551 {
7552         guchar *code = p;
7553         int save_mode = SAVE_NONE;
7554         MonoMethod *method = cfg->method;
7555         MonoType *ret_type = mini_type_get_underlying_type (NULL, mono_method_signature (method)->ret);
7556         int i;
7557         
7558         switch (ret_type->type) {
7559         case MONO_TYPE_VOID:
7560                 /* special case string .ctor icall */
7561                 if (strcmp (".ctor", method->name) && method->klass == mono_defaults.string_class)
7562                         save_mode = SAVE_EAX;
7563                 else
7564                         save_mode = SAVE_NONE;
7565                 break;
7566         case MONO_TYPE_I8:
7567         case MONO_TYPE_U8:
7568                 save_mode = SAVE_EAX;
7569                 break;
7570         case MONO_TYPE_R4:
7571         case MONO_TYPE_R8:
7572                 save_mode = SAVE_XMM;
7573                 break;
7574         case MONO_TYPE_GENERICINST:
7575                 if (!mono_type_generic_inst_is_valuetype (ret_type)) {
7576                         save_mode = SAVE_EAX;
7577                         break;
7578                 }
7579                 /* Fall through */
7580         case MONO_TYPE_VALUETYPE:
7581                 save_mode = SAVE_STRUCT;
7582                 break;
7583         default:
7584                 save_mode = SAVE_EAX;
7585                 break;
7586         }
7587
7588         /* Save the result and copy it into the proper argument register */
7589         switch (save_mode) {
7590         case SAVE_EAX:
7591                 amd64_push_reg (code, AMD64_RAX);
7592                 /* Align stack */
7593                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
7594                 if (enable_arguments)
7595                         amd64_mov_reg_reg (code, AMD64_ARG_REG2, AMD64_RAX, 8);
7596                 break;
7597         case SAVE_STRUCT:
7598                 /* FIXME: */
7599                 if (enable_arguments)
7600                         amd64_mov_reg_imm (code, AMD64_ARG_REG2, 0);
7601                 break;
7602         case SAVE_XMM:
7603                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
7604                 amd64_movsd_membase_reg (code, AMD64_RSP, 0, AMD64_XMM0);
7605                 /* Align stack */
7606                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
7607                 /* 
7608                  * The result is already in the proper argument register so no copying
7609                  * needed.
7610                  */
7611                 break;
7612         case SAVE_NONE:
7613                 break;
7614         default:
7615                 g_assert_not_reached ();
7616         }
7617
7618         /* Set %al since this is a varargs call */
7619         if (save_mode == SAVE_XMM)
7620                 amd64_mov_reg_imm (code, AMD64_RAX, 1);
7621         else
7622                 amd64_mov_reg_imm (code, AMD64_RAX, 0);
7623
7624         if (preserve_argument_registers) {
7625                 for (i = 0; i < PARAM_REGS; ++i)
7626                         amd64_push_reg (code, param_regs [i]);
7627         }
7628
7629         mono_add_patch_info (cfg, code-cfg->native_code, MONO_PATCH_INFO_METHODCONST, method);
7630         amd64_set_reg_template (code, AMD64_ARG_REG1);
7631         code = emit_call (cfg, code, MONO_PATCH_INFO_ABS, (gpointer)func, TRUE);
7632
7633         if (preserve_argument_registers) {
7634                 for (i = PARAM_REGS - 1; i >= 0; --i)
7635                         amd64_pop_reg (code, param_regs [i]);
7636         }
7637
7638         /* Restore result */
7639         switch (save_mode) {
7640         case SAVE_EAX:
7641                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
7642                 amd64_pop_reg (code, AMD64_RAX);
7643                 break;
7644         case SAVE_STRUCT:
7645                 /* FIXME: */
7646                 break;
7647         case SAVE_XMM:
7648                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
7649                 amd64_movsd_reg_membase (code, AMD64_XMM0, AMD64_RSP, 0);
7650                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
7651                 break;
7652         case SAVE_NONE:
7653                 break;
7654         default:
7655                 g_assert_not_reached ();
7656         }
7657
7658         return code;
7659 }
7660
7661 void
7662 mono_arch_flush_icache (guint8 *code, gint size)
7663 {
7664         /* Not needed */
7665 }
7666
7667 void
7668 mono_arch_flush_register_windows (void)
7669 {
7670 }
7671
7672 gboolean 
7673 mono_arch_is_inst_imm (gint64 imm)
7674 {
7675         return amd64_is_imm32 (imm);
7676 }
7677
7678 /*
7679  * Determine whenever the trap whose info is in SIGINFO is caused by
7680  * integer overflow.
7681  */
7682 gboolean
7683 mono_arch_is_int_overflow (void *sigctx, void *info)
7684 {
7685         MonoContext ctx;
7686         guint8* rip;
7687         int reg;
7688         gint64 value;
7689
7690         mono_arch_sigctx_to_monoctx (sigctx, &ctx);
7691
7692         rip = (guint8*)ctx.rip;
7693
7694         if (IS_REX (rip [0])) {
7695                 reg = amd64_rex_b (rip [0]);
7696                 rip ++;
7697         }
7698         else
7699                 reg = 0;
7700
7701         if ((rip [0] == 0xf7) && (x86_modrm_mod (rip [1]) == 0x3) && (x86_modrm_reg (rip [1]) == 0x7)) {
7702                 /* idiv REG */
7703                 reg += x86_modrm_rm (rip [1]);
7704
7705                 switch (reg) {
7706                 case AMD64_RAX:
7707                         value = ctx.rax;
7708                         break;
7709                 case AMD64_RBX:
7710                         value = ctx.rbx;
7711                         break;
7712                 case AMD64_RCX:
7713                         value = ctx.rcx;
7714                         break;
7715                 case AMD64_RDX:
7716                         value = ctx.rdx;
7717                         break;
7718                 case AMD64_RBP:
7719                         value = ctx.rbp;
7720                         break;
7721                 case AMD64_RSP:
7722                         value = ctx.rsp;
7723                         break;
7724                 case AMD64_RSI:
7725                         value = ctx.rsi;
7726                         break;
7727                 case AMD64_RDI:
7728                         value = ctx.rdi;
7729                         break;
7730                 case AMD64_R12:
7731                         value = ctx.r12;
7732                         break;
7733                 case AMD64_R13:
7734                         value = ctx.r13;
7735                         break;
7736                 case AMD64_R14:
7737                         value = ctx.r14;
7738                         break;
7739                 case AMD64_R15:
7740                         value = ctx.r15;
7741                         break;
7742                 default:
7743                         g_assert_not_reached ();
7744                         reg = -1;
7745                 }                       
7746
7747                 if (value == -1)
7748                         return TRUE;
7749         }
7750
7751         return FALSE;
7752 }
7753
7754 guint32
7755 mono_arch_get_patch_offset (guint8 *code)
7756 {
7757         return 3;
7758 }
7759
7760 /**
7761  * mono_breakpoint_clean_code:
7762  *
7763  * Copy @size bytes from @code - @offset to the buffer @buf. If the debugger inserted software
7764  * breakpoints in the original code, they are removed in the copy.
7765  *
7766  * Returns TRUE if no sw breakpoint was present.
7767  */
7768 gboolean
7769 mono_breakpoint_clean_code (guint8 *method_start, guint8 *code, int offset, guint8 *buf, int size)
7770 {
7771         int i;
7772         gboolean can_write = TRUE;
7773         /*
7774          * If method_start is non-NULL we need to perform bound checks, since we access memory
7775          * at code - offset we could go before the start of the method and end up in a different
7776          * page of memory that is not mapped or read incorrect data anyway. We zero-fill the bytes
7777          * instead.
7778          */
7779         if (!method_start || code - offset >= method_start) {
7780                 memcpy (buf, code - offset, size);
7781         } else {
7782                 int diff = code - method_start;
7783                 memset (buf, 0, size);
7784                 memcpy (buf + offset - diff, method_start, diff + size - offset);
7785         }
7786         code -= offset;
7787         for (i = 0; i < MONO_BREAKPOINT_ARRAY_SIZE; ++i) {
7788                 int idx = mono_breakpoint_info_index [i];
7789                 guint8 *ptr;
7790                 if (idx < 1)
7791                         continue;
7792                 ptr = mono_breakpoint_info [idx].address;
7793                 if (ptr >= code && ptr < code + size) {
7794                         guint8 saved_byte = mono_breakpoint_info [idx].saved_byte;
7795                         can_write = FALSE;
7796                         /*g_print ("patching %p with 0x%02x (was: 0x%02x)\n", ptr, saved_byte, buf [ptr - code]);*/
7797                         buf [ptr - code] = saved_byte;
7798                 }
7799         }
7800         return can_write;
7801 }
7802
7803 #if defined(__native_client_codegen__)
7804 /* For membase calls, we want the base register. for Native Client,  */
7805 /* all indirect calls have the following sequence with the given sizes: */
7806 /* mov %eXX,%eXX                                [2-3]   */
7807 /* mov disp(%r15,%rXX,scale),%r11d              [4-8]   */
7808 /* and $0xffffffffffffffe0,%r11d                [4]     */
7809 /* add %r15,%r11                                [3]     */
7810 /* callq *%r11                                  [3]     */
7811
7812
7813 /* Determine if code points to a NaCl call-through-register sequence, */
7814 /* (i.e., the last 3 instructions listed above) */
7815 int
7816 is_nacl_call_reg_sequence(guint8* code)
7817 {
7818         const char *sequence = "\x41\x83\xe3\xe0" /* and */
7819                                "\x4d\x03\xdf"     /* add */
7820                                "\x41\xff\xd3";   /* call */
7821         return memcmp(code, sequence, 10) == 0;
7822 }
7823
7824 /* Determine if code points to the first opcode of the mov membase component */
7825 /* of an indirect call sequence (i.e. the first 2 instructions listed above) */
7826 /* (there could be a REX prefix before the opcode but it is ignored) */
7827 static int
7828 is_nacl_indirect_call_membase_sequence(guint8* code)
7829 {
7830                /* Check for mov opcode, reg-reg addressing mode (mod = 3), */
7831         return code[0] == 0x8b && amd64_modrm_mod(code[1]) == 3 &&
7832                /* and that src reg = dest reg */
7833                amd64_modrm_reg(code[1]) == amd64_modrm_rm(code[1]) &&
7834                /* Check that next inst is mov, uses SIB byte (rm = 4), */
7835                IS_REX(code[2]) &&
7836                code[3] == 0x8b && amd64_modrm_rm(code[4]) == 4 &&
7837                /* and has dst of r11 and base of r15 */
7838                (amd64_modrm_reg(code[4]) + amd64_rex_r(code[2])) == AMD64_R11 &&
7839                (amd64_sib_base(code[5]) + amd64_rex_b(code[2])) == AMD64_R15;
7840 }
7841 #endif /* __native_client_codegen__ */
7842
7843 int
7844 mono_arch_get_this_arg_reg (guint8 *code)
7845 {
7846         return AMD64_ARG_REG1;
7847 }
7848
7849 gpointer
7850 mono_arch_get_this_arg_from_call (mgreg_t *regs, guint8 *code)
7851 {
7852         return (gpointer)regs [mono_arch_get_this_arg_reg (code)];
7853 }
7854
7855 #define MAX_ARCH_DELEGATE_PARAMS 10
7856
7857 static gpointer
7858 get_delegate_invoke_impl (gboolean has_target, guint32 param_count, guint32 *code_len)
7859 {
7860         guint8 *code, *start;
7861         int i;
7862
7863         if (has_target) {
7864                 start = code = mono_global_codeman_reserve (64);
7865
7866                 /* Replace the this argument with the target */
7867                 amd64_mov_reg_reg (code, AMD64_RAX, AMD64_ARG_REG1, 8);
7868                 amd64_mov_reg_membase (code, AMD64_ARG_REG1, AMD64_RAX, G_STRUCT_OFFSET (MonoDelegate, target), 8);
7869                 amd64_jump_membase (code, AMD64_RAX, G_STRUCT_OFFSET (MonoDelegate, method_ptr));
7870
7871                 g_assert ((code - start) < 64);
7872         } else {
7873                 start = code = mono_global_codeman_reserve (64);
7874
7875                 if (param_count == 0) {
7876                         amd64_jump_membase (code, AMD64_ARG_REG1, G_STRUCT_OFFSET (MonoDelegate, method_ptr));
7877                 } else {
7878                         /* We have to shift the arguments left */
7879                         amd64_mov_reg_reg (code, AMD64_RAX, AMD64_ARG_REG1, 8);
7880                         for (i = 0; i < param_count; ++i) {
7881 #ifdef HOST_WIN32
7882                                 if (i < 3)
7883                                         amd64_mov_reg_reg (code, param_regs [i], param_regs [i + 1], 8);
7884                                 else
7885                                         amd64_mov_reg_membase (code, param_regs [i], AMD64_RSP, 0x28, 8);
7886 #else
7887                                 amd64_mov_reg_reg (code, param_regs [i], param_regs [i + 1], 8);
7888 #endif
7889                         }
7890
7891                         amd64_jump_membase (code, AMD64_RAX, G_STRUCT_OFFSET (MonoDelegate, method_ptr));
7892                 }
7893                 g_assert ((code - start) < 64);
7894         }
7895
7896         nacl_global_codeman_validate(&start, 64, &code);
7897
7898         mono_debug_add_delegate_trampoline (start, code - start);
7899
7900         if (code_len)
7901                 *code_len = code - start;
7902
7903
7904         if (mono_jit_map_is_enabled ()) {
7905                 char *buff;
7906                 if (has_target)
7907                         buff = (char*)"delegate_invoke_has_target";
7908                 else
7909                         buff = g_strdup_printf ("delegate_invoke_no_target_%d", param_count);
7910                 mono_emit_jit_tramp (start, code - start, buff);
7911                 if (!has_target)
7912                         g_free (buff);
7913         }
7914
7915         return start;
7916 }
7917
7918 /*
7919  * mono_arch_get_delegate_invoke_impls:
7920  *
7921  *   Return a list of MonoTrampInfo structures for the delegate invoke impl
7922  * trampolines.
7923  */
7924 GSList*
7925 mono_arch_get_delegate_invoke_impls (void)
7926 {
7927         GSList *res = NULL;
7928         guint8 *code;
7929         guint32 code_len;
7930         int i;
7931         char *tramp_name;
7932
7933         code = get_delegate_invoke_impl (TRUE, 0, &code_len);
7934         res = g_slist_prepend (res, mono_tramp_info_create ("delegate_invoke_impl_has_target", code, code_len, NULL, NULL));
7935
7936         for (i = 0; i < MAX_ARCH_DELEGATE_PARAMS; ++i) {
7937                 code = get_delegate_invoke_impl (FALSE, i, &code_len);
7938                 tramp_name = g_strdup_printf ("delegate_invoke_impl_target_%d", i);
7939                 res = g_slist_prepend (res, mono_tramp_info_create (tramp_name, code, code_len, NULL, NULL));
7940                 g_free (tramp_name);
7941         }
7942
7943         return res;
7944 }
7945
7946 gpointer
7947 mono_arch_get_delegate_invoke_impl (MonoMethodSignature *sig, gboolean has_target)
7948 {
7949         guint8 *code, *start;
7950         int i;
7951
7952         if (sig->param_count > MAX_ARCH_DELEGATE_PARAMS)
7953                 return NULL;
7954
7955         /* FIXME: Support more cases */
7956         if (MONO_TYPE_ISSTRUCT (sig->ret))
7957                 return NULL;
7958
7959         if (has_target) {
7960                 static guint8* cached = NULL;
7961
7962                 if (cached)
7963                         return cached;
7964
7965                 if (mono_aot_only)
7966                         start = mono_aot_get_trampoline ("delegate_invoke_impl_has_target");
7967                 else
7968                         start = get_delegate_invoke_impl (TRUE, 0, NULL);
7969
7970                 mono_memory_barrier ();
7971
7972                 cached = start;
7973         } else {
7974                 static guint8* cache [MAX_ARCH_DELEGATE_PARAMS + 1] = {NULL};
7975                 for (i = 0; i < sig->param_count; ++i)
7976                         if (!mono_is_regsize_var (sig->params [i]))
7977                                 return NULL;
7978                 if (sig->param_count > 4)
7979                         return NULL;
7980
7981                 code = cache [sig->param_count];
7982                 if (code)
7983                         return code;
7984
7985                 if (mono_aot_only) {
7986                         char *name = g_strdup_printf ("delegate_invoke_impl_target_%d", sig->param_count);
7987                         start = mono_aot_get_trampoline (name);
7988                         g_free (name);
7989                 } else {
7990                         start = get_delegate_invoke_impl (FALSE, sig->param_count, NULL);
7991                 }
7992
7993                 mono_memory_barrier ();
7994
7995                 cache [sig->param_count] = start;
7996         }
7997
7998         return start;
7999 }
8000 void
8001 mono_arch_finish_init (void)
8002 {
8003 #ifdef HOST_WIN32
8004         /* 
8005          * We need to init this multiple times, since when we are first called, the key might not
8006          * be initialized yet.
8007          */
8008         appdomain_tls_offset = mono_domain_get_tls_key ();
8009         lmf_tls_offset = mono_get_jit_tls_key ();
8010         lmf_addr_tls_offset = mono_get_jit_tls_key ();
8011
8012         /* Only 64 tls entries can be accessed using inline code */
8013         if (appdomain_tls_offset >= 64)
8014                 appdomain_tls_offset = -1;
8015         if (lmf_tls_offset >= 64)
8016                 lmf_tls_offset = -1;
8017         if (lmf_addr_tls_offset >= 64)
8018                 lmf_addr_tls_offset = -1;
8019 #else
8020 #ifdef MONO_XEN_OPT
8021         optimize_for_xen = access ("/proc/xen", F_OK) == 0;
8022 #endif
8023         appdomain_tls_offset = mono_domain_get_tls_offset ();
8024         lmf_tls_offset = mono_get_lmf_tls_offset ();
8025         lmf_addr_tls_offset = mono_get_lmf_addr_tls_offset ();
8026 #endif
8027 }
8028
8029 void
8030 mono_arch_free_jit_tls_data (MonoJitTlsData *tls)
8031 {
8032 }
8033
8034 #ifdef MONO_ARCH_HAVE_IMT
8035
8036 #if defined(__default_codegen__)
8037 #define CMP_SIZE (6 + 1)
8038 #define CMP_REG_REG_SIZE (4 + 1)
8039 #define BR_SMALL_SIZE 2
8040 #define BR_LARGE_SIZE 6
8041 #define MOV_REG_IMM_SIZE 10
8042 #define MOV_REG_IMM_32BIT_SIZE 6
8043 #define JUMP_REG_SIZE (2 + 1)
8044 #elif defined(__native_client_codegen__)
8045 /* NaCl N-byte instructions can be padded up to N-1 bytes */
8046 #define CMP_SIZE ((6 + 1) * 2 - 1)
8047 #define CMP_REG_REG_SIZE ((4 + 1) * 2 - 1)
8048 #define BR_SMALL_SIZE (2 * 2 - 1)
8049 #define BR_LARGE_SIZE (6 * 2 - 1)
8050 #define MOV_REG_IMM_SIZE (10 * 2 - 1)
8051 #define MOV_REG_IMM_32BIT_SIZE (6 * 2 - 1)
8052 /* Jump reg for NaCl adds a mask (+4) and add (+3) */
8053 #define JUMP_REG_SIZE ((2 + 1 + 4 + 3) * 2 - 1)
8054 /* Jump membase's size is large and unpredictable    */
8055 /* in native client, just pad it out a whole bundle. */
8056 #define JUMP_MEMBASE_SIZE (kNaClAlignment)
8057 #endif
8058
8059 static int
8060 imt_branch_distance (MonoIMTCheckItem **imt_entries, int start, int target)
8061 {
8062         int i, distance = 0;
8063         for (i = start; i < target; ++i)
8064                 distance += imt_entries [i]->chunk_size;
8065         return distance;
8066 }
8067
8068 /*
8069  * LOCKING: called with the domain lock held
8070  */
8071 gpointer
8072 mono_arch_build_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count,
8073         gpointer fail_tramp)
8074 {
8075         int i;
8076         int size = 0;
8077         guint8 *code, *start;
8078         gboolean vtable_is_32bit = ((gsize)(vtable) == (gsize)(int)(gsize)(vtable));
8079
8080         for (i = 0; i < count; ++i) {
8081                 MonoIMTCheckItem *item = imt_entries [i];
8082                 if (item->is_equals) {
8083                         if (item->check_target_idx) {
8084                                 if (!item->compare_done) {
8085                                         if (amd64_is_imm32 (item->key))
8086                                                 item->chunk_size += CMP_SIZE;
8087                                         else
8088                                                 item->chunk_size += MOV_REG_IMM_SIZE + CMP_REG_REG_SIZE;
8089                                 }
8090                                 if (item->has_target_code) {
8091                                         item->chunk_size += MOV_REG_IMM_SIZE;
8092                                 } else {
8093                                         if (vtable_is_32bit)
8094                                                 item->chunk_size += MOV_REG_IMM_32BIT_SIZE;
8095                                         else
8096                                                 item->chunk_size += MOV_REG_IMM_SIZE;
8097 #ifdef __native_client_codegen__
8098                                         item->chunk_size += JUMP_MEMBASE_SIZE;
8099 #endif
8100                                 }
8101                                 item->chunk_size += BR_SMALL_SIZE + JUMP_REG_SIZE;
8102                         } else {
8103                                 if (fail_tramp) {
8104                                         item->chunk_size += MOV_REG_IMM_SIZE * 3 + CMP_REG_REG_SIZE +
8105                                                 BR_SMALL_SIZE + JUMP_REG_SIZE * 2;
8106                                 } else {
8107                                         if (vtable_is_32bit)
8108                                                 item->chunk_size += MOV_REG_IMM_32BIT_SIZE;
8109                                         else
8110                                                 item->chunk_size += MOV_REG_IMM_SIZE;
8111                                         item->chunk_size += JUMP_REG_SIZE;
8112                                         /* with assert below:
8113                                          * item->chunk_size += CMP_SIZE + BR_SMALL_SIZE + 1;
8114                                          */
8115 #ifdef __native_client_codegen__
8116                                         item->chunk_size += JUMP_MEMBASE_SIZE;
8117 #endif
8118                                 }
8119                         }
8120                 } else {
8121                         if (amd64_is_imm32 (item->key))
8122                                 item->chunk_size += CMP_SIZE;
8123                         else
8124                                 item->chunk_size += MOV_REG_IMM_SIZE + CMP_REG_REG_SIZE;
8125                         item->chunk_size += BR_LARGE_SIZE;
8126                         imt_entries [item->check_target_idx]->compare_done = TRUE;
8127                 }
8128                 size += item->chunk_size;
8129         }
8130 #if defined(__native_client__) && defined(__native_client_codegen__)
8131         /* In Native Client, we don't re-use thunks, allocate from the */
8132         /* normal code manager paths. */
8133         code = mono_domain_code_reserve (domain, size);
8134 #else
8135         if (fail_tramp)
8136                 code = mono_method_alloc_generic_virtual_thunk (domain, size);
8137         else
8138                 code = mono_domain_code_reserve (domain, size);
8139 #endif
8140         start = code;
8141         for (i = 0; i < count; ++i) {
8142                 MonoIMTCheckItem *item = imt_entries [i];
8143                 item->code_target = code;
8144                 if (item->is_equals) {
8145                         gboolean fail_case = !item->check_target_idx && fail_tramp;
8146
8147                         if (item->check_target_idx || fail_case) {
8148                                 if (!item->compare_done || fail_case) {
8149                                         if (amd64_is_imm32 (item->key))
8150                                                 amd64_alu_reg_imm_size (code, X86_CMP, MONO_ARCH_IMT_REG, (guint32)(gssize)item->key, sizeof(gpointer));
8151                                         else {
8152                                                 amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, item->key);
8153                                                 amd64_alu_reg_reg (code, X86_CMP, MONO_ARCH_IMT_REG, MONO_ARCH_IMT_SCRATCH_REG);
8154                                         }
8155                                 }
8156                                 item->jmp_code = code;
8157                                 amd64_branch8 (code, X86_CC_NE, 0, FALSE);
8158                                 if (item->has_target_code) {
8159                                         amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, item->value.target_code);
8160                                         amd64_jump_reg (code, MONO_ARCH_IMT_SCRATCH_REG);
8161                                 } else {
8162                                         amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, & (vtable->vtable [item->value.vtable_slot]));
8163                                         amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
8164                                 }
8165
8166                                 if (fail_case) {
8167                                         amd64_patch (item->jmp_code, code);
8168                                         amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, fail_tramp);
8169                                         amd64_jump_reg (code, MONO_ARCH_IMT_SCRATCH_REG);
8170                                         item->jmp_code = NULL;
8171                                 }
8172                         } else {
8173                                 /* enable the commented code to assert on wrong method */
8174 #if 0
8175                                 if (amd64_is_imm32 (item->key))
8176                                         amd64_alu_reg_imm_size (code, X86_CMP, MONO_ARCH_IMT_REG, (guint32)(gssize)item->key, sizeof(gpointer));
8177                                 else {
8178                                         amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, item->key);
8179                                         amd64_alu_reg_reg (code, X86_CMP, MONO_ARCH_IMT_REG, MONO_ARCH_IMT_SCRATCH_REG);
8180                                 }
8181                                 item->jmp_code = code;
8182                                 amd64_branch8 (code, X86_CC_NE, 0, FALSE);
8183                                 /* See the comment below about R10 */
8184                                 amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, & (vtable->vtable [item->value.vtable_slot]));
8185                                 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
8186                                 amd64_patch (item->jmp_code, code);
8187                                 amd64_breakpoint (code);
8188                                 item->jmp_code = NULL;
8189 #else
8190                                 /* We're using R10 (MONO_ARCH_IMT_SCRATCH_REG) here because R11 (MONO_ARCH_IMT_REG)
8191                                    needs to be preserved.  R10 needs
8192                                    to be preserved for calls which
8193                                    require a runtime generic context,
8194                                    but interface calls don't. */
8195                                 amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, & (vtable->vtable [item->value.vtable_slot]));
8196                                 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
8197 #endif
8198                         }
8199                 } else {
8200                         if (amd64_is_imm32 (item->key))
8201                                 amd64_alu_reg_imm_size (code, X86_CMP, MONO_ARCH_IMT_REG, (guint32)(gssize)item->key, sizeof (gpointer));
8202                         else {
8203                                 amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, item->key);
8204                                 amd64_alu_reg_reg (code, X86_CMP, MONO_ARCH_IMT_REG, MONO_ARCH_IMT_SCRATCH_REG);
8205                         }
8206                         item->jmp_code = code;
8207                         if (x86_is_imm8 (imt_branch_distance (imt_entries, i, item->check_target_idx)))
8208                                 x86_branch8 (code, X86_CC_GE, 0, FALSE);
8209                         else
8210                                 x86_branch32 (code, X86_CC_GE, 0, FALSE);
8211                 }
8212                 g_assert (code - item->code_target <= item->chunk_size);
8213         }
8214         /* patch the branches to get to the target items */
8215         for (i = 0; i < count; ++i) {
8216                 MonoIMTCheckItem *item = imt_entries [i];
8217                 if (item->jmp_code) {
8218                         if (item->check_target_idx) {
8219                                 amd64_patch (item->jmp_code, imt_entries [item->check_target_idx]->code_target);
8220                         }
8221                 }
8222         }
8223
8224         if (!fail_tramp)
8225                 mono_stats.imt_thunks_size += code - start;
8226         g_assert (code - start <= size);
8227
8228         nacl_domain_code_validate(domain, &start, size, &code);
8229
8230         return start;
8231 }
8232
8233 MonoMethod*
8234 mono_arch_find_imt_method (mgreg_t *regs, guint8 *code)
8235 {
8236         return (MonoMethod*)regs [MONO_ARCH_IMT_REG];
8237 }
8238 #endif
8239
8240 MonoVTable*
8241 mono_arch_find_static_call_vtable (mgreg_t *regs, guint8 *code)
8242 {
8243         return (MonoVTable*) regs [MONO_ARCH_RGCTX_REG];
8244 }
8245
8246 GSList*
8247 mono_arch_get_cie_program (void)
8248 {
8249         GSList *l = NULL;
8250
8251         mono_add_unwind_op_def_cfa (l, (guint8*)NULL, (guint8*)NULL, AMD64_RSP, 8);
8252         mono_add_unwind_op_offset (l, (guint8*)NULL, (guint8*)NULL, AMD64_RIP, -8);
8253
8254         return l;
8255 }
8256
8257 MonoInst*
8258 mono_arch_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
8259 {
8260         MonoInst *ins = NULL;
8261         int opcode = 0;
8262
8263         if (cmethod->klass == mono_defaults.math_class) {
8264                 if (strcmp (cmethod->name, "Sin") == 0) {
8265                         opcode = OP_SIN;
8266                 } else if (strcmp (cmethod->name, "Cos") == 0) {
8267                         opcode = OP_COS;
8268                 } else if (strcmp (cmethod->name, "Sqrt") == 0) {
8269                         opcode = OP_SQRT;
8270                 } else if (strcmp (cmethod->name, "Abs") == 0 && fsig->params [0]->type == MONO_TYPE_R8) {
8271                         opcode = OP_ABS;
8272                 }
8273                 
8274                 if (opcode) {
8275                         MONO_INST_NEW (cfg, ins, opcode);
8276                         ins->type = STACK_R8;
8277                         ins->dreg = mono_alloc_freg (cfg);
8278                         ins->sreg1 = args [0]->dreg;
8279                         MONO_ADD_INS (cfg->cbb, ins);
8280                 }
8281
8282                 opcode = 0;
8283                 if (cfg->opt & MONO_OPT_CMOV) {
8284                         if (strcmp (cmethod->name, "Min") == 0) {
8285                                 if (fsig->params [0]->type == MONO_TYPE_I4)
8286                                         opcode = OP_IMIN;
8287                                 if (fsig->params [0]->type == MONO_TYPE_U4)
8288                                         opcode = OP_IMIN_UN;
8289                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
8290                                         opcode = OP_LMIN;
8291                                 else if (fsig->params [0]->type == MONO_TYPE_U8)
8292                                         opcode = OP_LMIN_UN;
8293                         } else if (strcmp (cmethod->name, "Max") == 0) {
8294                                 if (fsig->params [0]->type == MONO_TYPE_I4)
8295                                         opcode = OP_IMAX;
8296                                 if (fsig->params [0]->type == MONO_TYPE_U4)
8297                                         opcode = OP_IMAX_UN;
8298                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
8299                                         opcode = OP_LMAX;
8300                                 else if (fsig->params [0]->type == MONO_TYPE_U8)
8301                                         opcode = OP_LMAX_UN;
8302                         }
8303                 }
8304                 
8305                 if (opcode) {
8306                         MONO_INST_NEW (cfg, ins, opcode);
8307                         ins->type = fsig->params [0]->type == MONO_TYPE_I4 ? STACK_I4 : STACK_I8;
8308                         ins->dreg = mono_alloc_ireg (cfg);
8309                         ins->sreg1 = args [0]->dreg;
8310                         ins->sreg2 = args [1]->dreg;
8311                         MONO_ADD_INS (cfg->cbb, ins);
8312                 }
8313
8314 #if 0
8315                 /* OP_FREM is not IEEE compatible */
8316                 else if (strcmp (cmethod->name, "IEEERemainder") == 0) {
8317                         MONO_INST_NEW (cfg, ins, OP_FREM);
8318                         ins->inst_i0 = args [0];
8319                         ins->inst_i1 = args [1];
8320                 }
8321 #endif
8322         }
8323
8324         /* 
8325          * Can't implement CompareExchange methods this way since they have
8326          * three arguments.
8327          */
8328
8329         return ins;
8330 }
8331
8332 gboolean
8333 mono_arch_print_tree (MonoInst *tree, int arity)
8334 {
8335         return 0;
8336 }
8337
8338 MonoInst* mono_arch_get_domain_intrinsic (MonoCompile* cfg)
8339 {
8340         MonoInst* ins;
8341         
8342         if (appdomain_tls_offset == -1)
8343                 return NULL;
8344         
8345         MONO_INST_NEW (cfg, ins, OP_TLS_GET);
8346         ins->inst_offset = appdomain_tls_offset;
8347         return ins;
8348 }
8349
8350 #define _CTX_REG(ctx,fld,i) ((&ctx->fld)[i])
8351
8352 mgreg_t
8353 mono_arch_context_get_int_reg (MonoContext *ctx, int reg)
8354 {
8355         switch (reg) {
8356         case AMD64_RCX: return ctx->rcx;
8357         case AMD64_RDX: return ctx->rdx;
8358         case AMD64_RBX: return ctx->rbx;
8359         case AMD64_RBP: return ctx->rbp;
8360         case AMD64_RSP: return ctx->rsp;
8361         default:
8362                 if (reg < 8)
8363                         return _CTX_REG (ctx, rax, reg);
8364                 else if (reg >= 12)
8365                         return _CTX_REG (ctx, r12, reg - 12);
8366                 else
8367                         g_assert_not_reached ();
8368         }
8369 }
8370
8371 void
8372 mono_arch_context_set_int_reg (MonoContext *ctx, int reg, mgreg_t val)
8373 {
8374         switch (reg) {
8375         case AMD64_RCX:
8376                 ctx->rcx = val;
8377                 break;
8378         case AMD64_RDX: 
8379                 ctx->rdx = val;
8380                 break;
8381         case AMD64_RBX:
8382                 ctx->rbx = val;
8383                 break;
8384         case AMD64_RBP:
8385                 ctx->rbp = val;
8386                 break;
8387         case AMD64_RSP:
8388                 ctx->rsp = val;
8389                 break;
8390         default:
8391                 if (reg < 8)
8392                         _CTX_REG (ctx, rax, reg) = val;
8393                 else if (reg >= 12)
8394                         _CTX_REG (ctx, r12, reg - 12) = val;
8395                 else
8396                         g_assert_not_reached ();
8397         }
8398 }
8399
8400 /*MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD*/
8401 gpointer
8402 mono_arch_install_handler_block_guard (MonoJitInfo *ji, MonoJitExceptionInfo *clause, MonoContext *ctx, gpointer new_value)
8403 {
8404         int offset;
8405         gpointer *sp, old_value;
8406         char *bp;
8407         const unsigned char *handler;
8408
8409         /*Decode the first instruction to figure out where did we store the spvar*/
8410         /*Our jit MUST generate the following:
8411          mov    %rsp, ?(%rbp)
8412
8413          Which is encoded as: REX.W 0x89 mod_rm
8414          mod_rm (rsp, rbp, imm) which can be: (imm will never be zero)
8415                 mod (reg + imm8):  01 reg(rsp): 100 rm(rbp): 101 -> 01100101 (0x65)
8416                 mod (reg + imm32): 10 reg(rsp): 100 rm(rbp): 101 -> 10100101 (0xA5)
8417
8418         FIXME can we generate frameless methods on this case?
8419
8420         */
8421         handler = clause->handler_start;
8422
8423         /*REX.W*/
8424         if (*handler != 0x48)
8425                 return NULL;
8426         ++handler;
8427
8428         /*mov r, r/m */
8429         if (*handler != 0x89)
8430                 return NULL;
8431         ++handler;
8432
8433         if (*handler == 0x65)
8434                 offset = *(signed char*)(handler + 1);
8435         else if (*handler == 0xA5)
8436                 offset = *(int*)(handler + 1);
8437         else
8438                 return NULL;
8439
8440         /*Load the spvar*/
8441         bp = MONO_CONTEXT_GET_BP (ctx);
8442         sp = *(gpointer*)(bp + offset);
8443
8444         old_value = *sp;
8445         if (old_value < ji->code_start || (char*)old_value > ((char*)ji->code_start + ji->code_size))
8446                 return old_value;
8447
8448         *sp = new_value;
8449
8450         return old_value;
8451 }
8452
8453 /*
8454  * mono_arch_emit_load_aotconst:
8455  *
8456  *   Emit code to load the contents of the GOT slot identified by TRAMP_TYPE and
8457  * TARGET from the mscorlib GOT in full-aot code.
8458  * On AMD64, the result is placed into R11.
8459  */
8460 guint8*
8461 mono_arch_emit_load_aotconst (guint8 *start, guint8 *code, MonoJumpInfo **ji, int tramp_type, gconstpointer target)
8462 {
8463         *ji = mono_patch_info_list_prepend (*ji, code - start, tramp_type, target);
8464         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, 8);
8465
8466         return code;
8467 }
8468
8469 /*
8470  * mono_arch_get_trampolines:
8471  *
8472  *   Return a list of MonoTrampInfo structures describing arch specific trampolines
8473  * for AOT.
8474  */
8475 GSList *
8476 mono_arch_get_trampolines (gboolean aot)
8477 {
8478         return mono_amd64_get_exception_trampolines (aot);
8479 }
8480
8481 /* Soft Debug support */
8482 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
8483
8484 /*
8485  * mono_arch_set_breakpoint:
8486  *
8487  *   Set a breakpoint at the native code corresponding to JI at NATIVE_OFFSET.
8488  * The location should contain code emitted by OP_SEQ_POINT.
8489  */
8490 void
8491 mono_arch_set_breakpoint (MonoJitInfo *ji, guint8 *ip)
8492 {
8493         guint8 *code = ip;
8494         guint8 *orig_code = code;
8495
8496         if (ji->from_aot) {
8497                 guint32 native_offset = ip - (guint8*)ji->code_start;
8498                 SeqPointInfo *info = mono_arch_get_seq_point_info (mono_domain_get (), ji->code_start);
8499
8500                 g_assert (info->bp_addrs [native_offset] == 0);
8501                 info->bp_addrs [native_offset] = bp_trigger_page;
8502         } else {
8503                 /* 
8504                  * In production, we will use int3 (has to fix the size in the md 
8505                  * file). But that could confuse gdb, so during development, we emit a SIGSEGV
8506                  * instead.
8507                  */
8508                 g_assert (code [0] == 0x90);
8509                 if (breakpoint_size == 8) {
8510                         amd64_mov_reg_mem (code, AMD64_R11, (guint64)bp_trigger_page, 4);
8511                 } else {
8512                         amd64_mov_reg_imm_size (code, AMD64_R11, (guint64)bp_trigger_page, 8);
8513                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 0, 4);
8514                 }
8515
8516                 g_assert (code - orig_code == breakpoint_size);
8517         }
8518 }
8519
8520 /*
8521  * mono_arch_clear_breakpoint:
8522  *
8523  *   Clear the breakpoint at IP.
8524  */
8525 void
8526 mono_arch_clear_breakpoint (MonoJitInfo *ji, guint8 *ip)
8527 {
8528         guint8 *code = ip;
8529         int i;
8530
8531         if (ji->from_aot) {
8532                 guint32 native_offset = ip - (guint8*)ji->code_start;
8533                 SeqPointInfo *info = mono_arch_get_seq_point_info (mono_domain_get (), ji->code_start);
8534
8535                 g_assert (info->bp_addrs [native_offset] == 0);
8536                 info->bp_addrs [native_offset] = info;
8537         } else {
8538                 for (i = 0; i < breakpoint_size; ++i)
8539                         x86_nop (code);
8540         }
8541 }
8542
8543 gboolean
8544 mono_arch_is_breakpoint_event (void *info, void *sigctx)
8545 {
8546 #ifdef HOST_WIN32
8547         EXCEPTION_RECORD* einfo = (EXCEPTION_RECORD*)info;
8548         return FALSE;
8549 #else
8550         siginfo_t* sinfo = (siginfo_t*) info;
8551         /* Sometimes the address is off by 4 */
8552         if (sinfo->si_addr >= bp_trigger_page && (guint8*)sinfo->si_addr <= (guint8*)bp_trigger_page + 128)
8553                 return TRUE;
8554         else
8555                 return FALSE;
8556 #endif
8557 }
8558
8559 /*
8560  * mono_arch_skip_breakpoint:
8561  *
8562  *   Modify CTX so the ip is placed after the breakpoint instruction, so when
8563  * we resume, the instruction is not executed again.
8564  */
8565 void
8566 mono_arch_skip_breakpoint (MonoContext *ctx, MonoJitInfo *ji)
8567 {
8568         if (ji->from_aot) {
8569                 /* amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 0, 8) */
8570                 MONO_CONTEXT_SET_IP (ctx, (guint8*)MONO_CONTEXT_GET_IP (ctx) + 3);
8571         } else {
8572                 MONO_CONTEXT_SET_IP (ctx, (guint8*)MONO_CONTEXT_GET_IP (ctx) + breakpoint_fault_size);
8573         }
8574 }
8575         
8576 /*
8577  * mono_arch_start_single_stepping:
8578  *
8579  *   Start single stepping.
8580  */
8581 void
8582 mono_arch_start_single_stepping (void)
8583 {
8584         mono_mprotect (ss_trigger_page, mono_pagesize (), 0);
8585 }
8586         
8587 /*
8588  * mono_arch_stop_single_stepping:
8589  *
8590  *   Stop single stepping.
8591  */
8592 void
8593 mono_arch_stop_single_stepping (void)
8594 {
8595         mono_mprotect (ss_trigger_page, mono_pagesize (), MONO_MMAP_READ);
8596 }
8597
8598 /*
8599  * mono_arch_is_single_step_event:
8600  *
8601  *   Return whenever the machine state in SIGCTX corresponds to a single
8602  * step event.
8603  */
8604 gboolean
8605 mono_arch_is_single_step_event (void *info, void *sigctx)
8606 {
8607 #ifdef HOST_WIN32
8608         EXCEPTION_RECORD* einfo = (EXCEPTION_RECORD*)info;
8609         return FALSE;
8610 #else
8611         siginfo_t* sinfo = (siginfo_t*) info;
8612         /* Sometimes the address is off by 4 */
8613         if (sinfo->si_addr >= ss_trigger_page && (guint8*)sinfo->si_addr <= (guint8*)ss_trigger_page + 128)
8614                 return TRUE;
8615         else
8616                 return FALSE;
8617 #endif
8618 }
8619
8620 /*
8621  * mono_arch_skip_single_step:
8622  *
8623  *   Modify CTX so the ip is placed after the single step trigger instruction,
8624  * we resume, the instruction is not executed again.
8625  */
8626 void
8627 mono_arch_skip_single_step (MonoContext *ctx)
8628 {
8629         MONO_CONTEXT_SET_IP (ctx, (guint8*)MONO_CONTEXT_GET_IP (ctx) + single_step_fault_size);
8630 }
8631
8632 /*
8633  * mono_arch_create_seq_point_info:
8634  *
8635  *   Return a pointer to a data structure which is used by the sequence
8636  * point implementation in AOTed code.
8637  */
8638 gpointer
8639 mono_arch_get_seq_point_info (MonoDomain *domain, guint8 *code)
8640 {
8641         SeqPointInfo *info;
8642         MonoJitInfo *ji;
8643         int i;
8644
8645         // FIXME: Add a free function
8646
8647         mono_domain_lock (domain);
8648         info = g_hash_table_lookup (domain_jit_info (domain)->arch_seq_points,
8649                                                                 code);
8650         mono_domain_unlock (domain);
8651
8652         if (!info) {
8653                 ji = mono_jit_info_table_find (domain, (char*)code);
8654                 g_assert (ji);
8655
8656                 // FIXME: Optimize the size
8657                 info = g_malloc0 (sizeof (SeqPointInfo) + (ji->code_size * sizeof (gpointer)));
8658
8659                 info->ss_trigger_page = ss_trigger_page;
8660                 info->bp_trigger_page = bp_trigger_page;
8661                 /* Initialize to a valid address */
8662                 for (i = 0; i < ji->code_size; ++i)
8663                         info->bp_addrs [i] = info;
8664
8665                 mono_domain_lock (domain);
8666                 g_hash_table_insert (domain_jit_info (domain)->arch_seq_points,
8667                                                          code, info);
8668                 mono_domain_unlock (domain);
8669         }
8670
8671         return info;
8672 }
8673
8674 #endif