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