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