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