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