2004-11-09 Zoltan Varga <vargaz@freemail.hu>
[mono.git] / mono / mini / mini-x86.c
1 /*
2  * mini-x86.c: x86 backend for the Mono code generator
3  *
4  * Authors:
5  *   Paolo Molaro (lupus@ximian.com)
6  *   Dietmar Maurer (dietmar@ximian.com)
7  *   Patrik Torstensson
8  *
9  * (C) 2003 Ximian, Inc.
10  */
11 #include "mini.h"
12 #include <string.h>
13 #include <math.h>
14
15 #include <mono/metadata/appdomain.h>
16 #include <mono/metadata/debug-helpers.h>
17 #include <mono/metadata/threads.h>
18 #include <mono/metadata/profiler-private.h>
19 #include <mono/utils/mono-math.h>
20
21 #include "trace.h"
22 #include "mini-x86.h"
23 #include "inssel.h"
24 #include "cpu-pentium.h"
25
26 static gint lmf_tls_offset = -1;
27 static gint appdomain_tls_offset = -1;
28 static gint thread_tls_offset = -1;
29
30 #ifdef PLATFORM_WIN32
31 /* Under windows, the default pinvoke calling convention is stdcall */
32 #define CALLCONV_IS_STDCALL(call_conv) (((call_conv) == MONO_CALL_STDCALL) || ((call_conv) == MONO_CALL_DEFAULT))
33 #else
34 #define CALLCONV_IS_STDCALL(call_conv) ((call_conv) == MONO_CALL_STDCALL)
35 #endif
36
37 #define SIGNAL_STACK_SIZE (64 * 1024)
38
39 const char*
40 mono_arch_regname (int reg) {
41         switch (reg) {
42         case X86_EAX: return "%eax";
43         case X86_EBX: return "%ebx";
44         case X86_ECX: return "%ecx";
45         case X86_EDX: return "%edx";
46         case X86_ESP: return "%esp";    case X86_EBP: return "%ebp";
47         case X86_EDI: return "%edi";
48         case X86_ESI: return "%esi";
49         }
50         return "unknown";
51 }
52
53 /*
54  * mono_arch_get_argument_info:
55  * @csig:  a method signature
56  * @param_count: the number of parameters to consider
57  * @arg_info: an array to store the result infos
58  *
59  * Gathers information on parameters such as size, alignment and
60  * padding. arg_info should be large enought to hold param_count + 1 entries. 
61  *
62  * Returns the size of the activation frame.
63  */
64 int
65 mono_arch_get_argument_info (MonoMethodSignature *csig, int param_count, MonoJitArgumentInfo *arg_info)
66 {
67         int k, frame_size = 0;
68         int size, align, pad;
69         int offset = 8;
70
71         if (MONO_TYPE_ISSTRUCT (csig->ret)) { 
72                 frame_size += sizeof (gpointer);
73                 offset += 4;
74         }
75
76         arg_info [0].offset = offset;
77
78         if (csig->hasthis) {
79                 frame_size += sizeof (gpointer);
80                 offset += 4;
81         }
82
83         arg_info [0].size = frame_size;
84
85         for (k = 0; k < param_count; k++) {
86                 
87                 if (csig->pinvoke)
88                         size = mono_type_native_stack_size (csig->params [k], &align);
89                 else
90                         size = mono_type_stack_size (csig->params [k], &align);
91
92                 /* ignore alignment for now */
93                 align = 1;
94
95                 frame_size += pad = (align - (frame_size & (align - 1))) & (align - 1); 
96                 arg_info [k].pad = pad;
97                 frame_size += size;
98                 arg_info [k + 1].pad = 0;
99                 arg_info [k + 1].size = size;
100                 offset += pad;
101                 arg_info [k + 1].offset = offset;
102                 offset += size;
103         }
104
105         align = MONO_ARCH_FRAME_ALIGNMENT;
106         frame_size += pad = (align - (frame_size & (align - 1))) & (align - 1);
107         arg_info [k].pad = pad;
108
109         return frame_size;
110 }
111
112 static const guchar cpuid_impl [] = {
113         0x55,                           /* push   %ebp */
114         0x89, 0xe5,                     /* mov    %esp,%ebp */
115         0x53,                           /* push   %ebx */
116         0x8b, 0x45, 0x08,               /* mov    0x8(%ebp),%eax */
117         0x0f, 0xa2,                     /* cpuid   */
118         0x50,                           /* push   %eax */
119         0x8b, 0x45, 0x10,               /* mov    0x10(%ebp),%eax */
120         0x89, 0x18,                     /* mov    %ebx,(%eax) */
121         0x8b, 0x45, 0x14,               /* mov    0x14(%ebp),%eax */
122         0x89, 0x08,                     /* mov    %ecx,(%eax) */
123         0x8b, 0x45, 0x18,               /* mov    0x18(%ebp),%eax */
124         0x89, 0x10,                     /* mov    %edx,(%eax) */
125         0x58,                           /* pop    %eax */
126         0x8b, 0x55, 0x0c,               /* mov    0xc(%ebp),%edx */
127         0x89, 0x02,                     /* mov    %eax,(%edx) */
128         0x5b,                           /* pop    %ebx */
129         0xc9,                           /* leave   */
130         0xc3,                           /* ret     */
131 };
132
133 typedef void (*CpuidFunc) (int id, int* p_eax, int* p_ebx, int* p_ecx, int* p_edx);
134
135 static int 
136 cpuid (int id, int* p_eax, int* p_ebx, int* p_ecx, int* p_edx)
137 {
138         int have_cpuid = 0;
139         __asm__  __volatile__ (
140                 "pushfl\n"
141                 "popl %%eax\n"
142                 "movl %%eax, %%edx\n"
143                 "xorl $0x200000, %%eax\n"
144                 "pushl %%eax\n"
145                 "popfl\n"
146                 "pushfl\n"
147                 "popl %%eax\n"
148                 "xorl %%edx, %%eax\n"
149                 "andl $0x200000, %%eax\n"
150                 "movl %%eax, %0"
151                 : "=r" (have_cpuid)
152                 :
153                 : "%eax", "%edx"
154         );
155
156         if (have_cpuid) {
157                 CpuidFunc func = (CpuidFunc)cpuid_impl;
158                 func (id, p_eax, p_ebx, p_ecx, p_edx);
159                 /*
160                  * We use this approach because of issues with gcc and pic code, see:
161                  * http://gcc.gnu.org/cgi-bin/gnatsweb.pl?cmd=view%20audit-trail&database=gcc&pr=7329
162                 __asm__ __volatile__ ("cpuid"
163                         : "=a" (*p_eax), "=b" (*p_ebx), "=c" (*p_ecx), "=d" (*p_edx)
164                         : "a" (id));
165                 */
166                 return 1;
167         }
168         return 0;
169 }
170
171 /*
172  * Initialize the cpu to execute managed code.
173  */
174 void
175 mono_arch_cpu_init (void)
176 {
177         guint16 fpcw;
178
179         /* spec compliance requires running with double precision */
180         __asm__  __volatile__ ("fnstcw %0\n": "=m" (fpcw));
181         fpcw &= ~X86_FPCW_PRECC_MASK;
182         fpcw |= X86_FPCW_PREC_DOUBLE;
183         __asm__  __volatile__ ("fldcw %0\n": : "m" (fpcw));
184         __asm__  __volatile__ ("fnstcw %0\n": "=m" (fpcw));
185
186 }
187
188 /*
189  * This function returns the optimizations supported on this cpu.
190  */
191 guint32
192 mono_arch_cpu_optimizazions (guint32 *exclude_mask)
193 {
194         int eax, ebx, ecx, edx;
195         guint32 opts = 0;
196         
197         *exclude_mask = 0;
198         /* Feature Flags function, flags returned in EDX. */
199         if (cpuid (1, &eax, &ebx, &ecx, &edx)) {
200                 if (edx & (1 << 15)) {
201                         opts |= MONO_OPT_CMOV;
202                         if (edx & 1)
203                                 opts |= MONO_OPT_FCMOV;
204                         else
205                                 *exclude_mask |= MONO_OPT_FCMOV;
206                 } else
207                         *exclude_mask |= MONO_OPT_CMOV;
208         }
209         return opts;
210 }
211
212 /*
213  * Determine whenever the trap whose info is in SIGINFO is caused by
214  * integer overflow.
215  */
216 gboolean
217 mono_arch_is_int_overflow (void *sigctx)
218 {
219         struct sigcontext *ctx = (struct sigcontext*)sigctx;
220         guint8* ip;
221
222         ip = (guint8*)ctx->SC_EIP;
223
224         if ((ip [0] == 0xf7) && (x86_modrm_mod (ip [1]) == 0x3) && (x86_modrm_reg (ip [1]) == 0x7)) {
225                 gint32 reg;
226
227                 /* idiv REG */
228                 switch (x86_modrm_rm (ip [1])) {
229                 case X86_ECX:
230                         reg = ctx->SC_ECX;
231                         break;
232                 case X86_EBX:
233                         reg = ctx->SC_EBX;
234                         break;
235                 default:
236                         g_assert_not_reached ();
237                         reg = -1;
238                 }
239
240                 if (reg == -1)
241                         return TRUE;
242         }
243                         
244         return FALSE;
245 }
246
247 static gboolean
248 is_regsize_var (MonoType *t) {
249         if (t->byref)
250                 return TRUE;
251         switch (mono_type_get_underlying_type (t)->type) {
252         case MONO_TYPE_I4:
253         case MONO_TYPE_U4:
254         case MONO_TYPE_I:
255         case MONO_TYPE_U:
256         case MONO_TYPE_PTR:
257                 return TRUE;
258         case MONO_TYPE_OBJECT:
259         case MONO_TYPE_STRING:
260         case MONO_TYPE_CLASS:
261         case MONO_TYPE_SZARRAY:
262         case MONO_TYPE_ARRAY:
263                 return TRUE;
264         case MONO_TYPE_VALUETYPE:
265                 return FALSE;
266         }
267         return FALSE;
268 }
269
270 GList *
271 mono_arch_get_allocatable_int_vars (MonoCompile *cfg)
272 {
273         GList *vars = NULL;
274         int i;
275
276         for (i = 0; i < cfg->num_varinfo; i++) {
277                 MonoInst *ins = cfg->varinfo [i];
278                 MonoMethodVar *vmv = MONO_VARINFO (cfg, i);
279
280                 /* unused vars */
281                 if (vmv->range.first_use.abs_pos >= vmv->range.last_use.abs_pos)
282                         continue;
283
284                 if ((ins->flags & (MONO_INST_IS_DEAD|MONO_INST_VOLATILE|MONO_INST_INDIRECT)) || 
285                     (ins->opcode != OP_LOCAL && ins->opcode != OP_ARG))
286                         continue;
287
288                 /* we dont allocate I1 to registers because there is no simply way to sign extend 
289                  * 8bit quantities in caller saved registers on x86 */
290                 if (is_regsize_var (ins->inst_vtype) || (ins->inst_vtype->type == MONO_TYPE_BOOLEAN) || 
291                     (ins->inst_vtype->type == MONO_TYPE_U1) || (ins->inst_vtype->type == MONO_TYPE_U2)||
292                     (ins->inst_vtype->type == MONO_TYPE_I2) || (ins->inst_vtype->type == MONO_TYPE_CHAR)) {
293                         g_assert (MONO_VARINFO (cfg, i)->reg == -1);
294                         g_assert (i == vmv->idx);
295                         vars = g_list_prepend (vars, vmv);
296                 }
297         }
298
299         vars = mono_varlist_sort (cfg, vars, 0);
300
301         return vars;
302 }
303
304 GList *
305 mono_arch_get_global_int_regs (MonoCompile *cfg)
306 {
307         GList *regs = NULL;
308
309         /* we can use 3 registers for global allocation */
310         regs = g_list_prepend (regs, (gpointer)X86_EBX);
311         regs = g_list_prepend (regs, (gpointer)X86_ESI);
312         regs = g_list_prepend (regs, (gpointer)X86_EDI);
313
314         return regs;
315 }
316
317 /*
318  * mono_arch_regalloc_cost:
319  *
320  *  Return the cost, in number of memory references, of the action of 
321  * allocating the variable VMV into a register during global register
322  * allocation.
323  */
324 guint32
325 mono_arch_regalloc_cost (MonoCompile *cfg, MonoMethodVar *vmv)
326 {
327         MonoInst *ins = cfg->varinfo [vmv->idx];
328
329         if (cfg->method->save_lmf)
330                 /* The register is already saved */
331                 return (ins->opcode == OP_ARG) ? 1 : 0;
332         else
333                 /* push+pop+possible load if it is an argument */
334                 return (ins->opcode == OP_ARG) ? 3 : 2;
335 }
336  
337 /*
338  * Set var information according to the calling convention. X86 version.
339  * The locals var stuff should most likely be split in another method.
340  */
341 void
342 mono_arch_allocate_vars (MonoCompile *m)
343 {
344         MonoMethodSignature *sig;
345         MonoMethodHeader *header;
346         MonoInst *inst;
347         int i, offset, size, align, curinst;
348
349         header = mono_method_get_header (m->method);
350
351         sig = m->method->signature;
352
353         offset = 8;
354         curinst = 0;
355         if (MONO_TYPE_ISSTRUCT (sig->ret)) {
356                 m->ret->opcode = OP_REGOFFSET;
357                 m->ret->inst_basereg = X86_EBP;
358                 m->ret->inst_offset = offset;
359                 offset += sizeof (gpointer);
360         } else {
361                 /* FIXME: handle long and FP values */
362                 switch (sig->ret->type) {
363                 case MONO_TYPE_VOID:
364                         break;
365                 default:
366                         m->ret->opcode = OP_REGVAR;
367                         m->ret->inst_c0 = X86_EAX;
368                         break;
369                 }
370         }
371         if (sig->hasthis) {
372                 inst = m->varinfo [curinst];
373                 if (inst->opcode != OP_REGVAR) {
374                         inst->opcode = OP_REGOFFSET;
375                         inst->inst_basereg = X86_EBP;
376                 }
377                 inst->inst_offset = offset;
378                 offset += sizeof (gpointer);
379                 curinst++;
380         }
381
382         if (sig->call_convention == MONO_CALL_VARARG) {
383                 m->sig_cookie = offset;
384                 offset += sizeof (gpointer);
385         }
386
387         for (i = 0; i < sig->param_count; ++i) {
388                 inst = m->varinfo [curinst];
389                 if (inst->opcode != OP_REGVAR) {
390                         inst->opcode = OP_REGOFFSET;
391                         inst->inst_basereg = X86_EBP;
392                 }
393                 inst->inst_offset = offset;
394                 size = mono_type_size (sig->params [i], &align);
395                 size += 4 - 1;
396                 size &= ~(4 - 1);
397                 offset += size;
398                 curinst++;
399         }
400
401         offset = 0;
402
403         /* reserve space to save LMF and caller saved registers */
404
405         if (m->method->save_lmf) {
406                 offset += sizeof (MonoLMF);
407         } else {
408                 if (m->used_int_regs & (1 << X86_EBX)) {
409                         offset += 4;
410                 }
411
412                 if (m->used_int_regs & (1 << X86_EDI)) {
413                         offset += 4;
414                 }
415
416                 if (m->used_int_regs & (1 << X86_ESI)) {
417                         offset += 4;
418                 }
419         }
420
421         for (i = curinst; i < m->num_varinfo; ++i) {
422                 inst = m->varinfo [i];
423
424                 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR)
425                         continue;
426
427                 /* inst->unused indicates native sized value types, this is used by the
428                 * pinvoke wrappers when they call functions returning structure */
429                 if (inst->unused && MONO_TYPE_ISSTRUCT (inst->inst_vtype) && inst->inst_vtype->type != MONO_TYPE_TYPEDBYREF)
430                         size = mono_class_native_size (inst->inst_vtype->data.klass, &align);
431                 else
432                         size = mono_type_size (inst->inst_vtype, &align);
433
434                 offset += size;
435                 offset += align - 1;
436                 offset &= ~(align - 1);
437                 inst->opcode = OP_REGOFFSET;
438                 inst->inst_basereg = X86_EBP;
439                 inst->inst_offset = -offset;
440                 //g_print ("allocating local %d to %d\n", i, -offset);
441         }
442         offset += (MONO_ARCH_FRAME_ALIGNMENT - 1);
443         offset &= ~(MONO_ARCH_FRAME_ALIGNMENT - 1);
444
445         /* change sign? */
446         m->stack_offset = -offset;
447 }
448
449 /* Fixme: we need an alignment solution for enter_method and mono_arch_call_opcode,
450  * currently alignment in mono_arch_call_opcode is computed without arch_get_argument_info 
451  */
452
453 /* 
454  * take the arguments and generate the arch-specific
455  * instructions to properly call the function in call.
456  * This includes pushing, moving arguments to the right register
457  * etc.
458  * Issue: who does the spilling if needed, and when?
459  */
460 MonoCallInst*
461 mono_arch_call_opcode (MonoCompile *cfg, MonoBasicBlock* bb, MonoCallInst *call, int is_virtual) {
462         MonoInst *arg, *in;
463         MonoMethodSignature *sig;
464         int i, n, stack_size, type;
465         MonoType *ptype;
466
467         stack_size = 0;
468         /* add the vararg cookie before the non-implicit args */
469         if (call->signature->call_convention == MONO_CALL_VARARG) {
470                 MonoInst *sig_arg;
471                 /* FIXME: Add support for signature tokens to AOT */
472                 cfg->disable_aot = TRUE;
473                 MONO_INST_NEW (cfg, arg, OP_OUTARG);
474                 MONO_INST_NEW (cfg, sig_arg, OP_ICONST);
475                 sig_arg->inst_p0 = call->signature;
476                 arg->inst_left = sig_arg;
477                 arg->type = STACK_PTR;
478                 /* prepend, so they get reversed */
479                 arg->next = call->out_args;
480                 call->out_args = arg;
481                 stack_size += sizeof (gpointer);
482         }
483         sig = call->signature;
484         n = sig->param_count + sig->hasthis;
485
486         if (sig->ret && MONO_TYPE_ISSTRUCT (sig->ret))
487                 stack_size += sizeof (gpointer);
488         for (i = 0; i < n; ++i) {
489                 if (is_virtual && i == 0) {
490                         /* the argument will be attached to the call instrucion */
491                         in = call->args [i];
492                         stack_size += 4;
493                 } else {
494                         MONO_INST_NEW (cfg, arg, OP_OUTARG);
495                         in = call->args [i];
496                         arg->cil_code = in->cil_code;
497                         arg->inst_left = in;
498                         arg->type = in->type;
499                         /* prepend, so they get reversed */
500                         arg->next = call->out_args;
501                         call->out_args = arg;
502                         if (i >= sig->hasthis) {
503                                 ptype = mono_type_get_underlying_type (sig->params [i - sig->hasthis]);
504                                 if (ptype->byref)
505                                         type = MONO_TYPE_U;
506                                 else
507                                         type = ptype->type;
508                                 /* FIXME: validate arguments... */
509                                 switch (type) {
510                                 case MONO_TYPE_I:
511                                 case MONO_TYPE_U:
512                                 case MONO_TYPE_BOOLEAN:
513                                 case MONO_TYPE_CHAR:
514                                 case MONO_TYPE_I1:
515                                 case MONO_TYPE_U1:
516                                 case MONO_TYPE_I2:
517                                 case MONO_TYPE_U2:
518                                 case MONO_TYPE_I4:
519                                 case MONO_TYPE_U4:
520                                 case MONO_TYPE_STRING:
521                                 case MONO_TYPE_CLASS:
522                                 case MONO_TYPE_OBJECT:
523                                 case MONO_TYPE_PTR:
524                                 case MONO_TYPE_FNPTR:
525                                 case MONO_TYPE_ARRAY:
526                                 case MONO_TYPE_SZARRAY:
527                                         stack_size += 4;
528                                         break;
529                                 case MONO_TYPE_I8:
530                                 case MONO_TYPE_U8:
531                                         stack_size += 8;
532                                         break;
533                                 case MONO_TYPE_R4:
534                                         stack_size += 4;
535                                         arg->opcode = OP_OUTARG_R4;
536                                         break;
537                                 case MONO_TYPE_R8:
538                                         stack_size += 8;
539                                         arg->opcode = OP_OUTARG_R8;
540                                         break;
541                                 case MONO_TYPE_VALUETYPE: {
542                                         int size;
543                                         if (sig->pinvoke) 
544                                                 size = mono_type_native_stack_size (&in->klass->byval_arg, NULL);
545                                         else 
546                                                 size = mono_type_stack_size (&in->klass->byval_arg, NULL);
547
548                                         stack_size += size;
549                                         arg->opcode = OP_OUTARG_VT;
550                                         arg->klass = in->klass;
551                                         arg->unused = sig->pinvoke;
552                                         arg->inst_imm = size; 
553                                         break;
554                                 }
555                                 case MONO_TYPE_TYPEDBYREF:
556                                         stack_size += sizeof (MonoTypedRef);
557                                         arg->opcode = OP_OUTARG_VT;
558                                         arg->klass = in->klass;
559                                         arg->unused = sig->pinvoke;
560                                         arg->inst_imm = sizeof (MonoTypedRef); 
561                                         break;
562                                 default:
563                                         g_error ("unknown type 0x%02x in mono_arch_call_opcode\n", type);
564                                 }
565                         } else {
566                                 /* the this argument */
567                                 stack_size += 4;
568                         }
569                 }
570         }
571         /* if the function returns a struct, the called method already does a ret $0x4 */
572         if (sig->ret && MONO_TYPE_ISSTRUCT (sig->ret))
573                 stack_size -= 4;
574         call->stack_usage = stack_size;
575         /* 
576          * should set more info in call, such as the stack space
577          * used by the args that needs to be added back to esp
578          */
579
580         return call;
581 }
582
583 /*
584  * Allow tracing to work with this interface (with an optional argument)
585  */
586
587 /*
588  * This may be needed on some archs or for debugging support.
589  */
590 void
591 mono_arch_instrument_mem_needs (MonoMethod *method, int *stack, int *code)
592 {
593         /* no stack room needed now (may be needed for FASTCALL-trace support) */
594         *stack = 0;
595         /* split prolog-epilog requirements? */
596         *code = 50; /* max bytes needed: check this number */
597 }
598
599 void*
600 mono_arch_instrument_prolog (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments)
601 {
602         guchar *code = p;
603
604         /* if some args are passed in registers, we need to save them here */
605         x86_push_reg (code, X86_EBP);
606         mono_add_patch_info (cfg, code-cfg->native_code, MONO_PATCH_INFO_METHODCONST, cfg->method);
607         x86_push_imm (code, cfg->method);
608         mono_add_patch_info (cfg, code-cfg->native_code, MONO_PATCH_INFO_ABS, func);
609         x86_call_code (code, 0);
610         x86_alu_reg_imm (code, X86_ADD, X86_ESP, 8);
611
612         return code;
613 }
614
615 enum {
616         SAVE_NONE,
617         SAVE_STRUCT,
618         SAVE_EAX,
619         SAVE_EAX_EDX,
620         SAVE_FP
621 };
622
623 void*
624 mono_arch_instrument_epilog (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments)
625 {
626         guchar *code = p;
627         int arg_size = 0, save_mode = SAVE_NONE;
628         MonoMethod *method = cfg->method;
629         
630         switch (mono_type_get_underlying_type (method->signature->ret)->type) {
631         case MONO_TYPE_VOID:
632                 /* special case string .ctor icall */
633                 if (strcmp (".ctor", method->name) && method->klass == mono_defaults.string_class)
634                         save_mode = SAVE_EAX;
635                 else
636                         save_mode = SAVE_NONE;
637                 break;
638         case MONO_TYPE_I8:
639         case MONO_TYPE_U8:
640                 save_mode = SAVE_EAX_EDX;
641                 break;
642         case MONO_TYPE_R4:
643         case MONO_TYPE_R8:
644                 save_mode = SAVE_FP;
645                 break;
646         case MONO_TYPE_VALUETYPE:
647                 save_mode = SAVE_STRUCT;
648                 break;
649         default:
650                 save_mode = SAVE_EAX;
651                 break;
652         }
653
654         switch (save_mode) {
655         case SAVE_EAX_EDX:
656                 x86_push_reg (code, X86_EDX);
657                 x86_push_reg (code, X86_EAX);
658                 if (enable_arguments) {
659                         x86_push_reg (code, X86_EDX);
660                         x86_push_reg (code, X86_EAX);
661                         arg_size = 8;
662                 }
663                 break;
664         case SAVE_EAX:
665                 x86_push_reg (code, X86_EAX);
666                 if (enable_arguments) {
667                         x86_push_reg (code, X86_EAX);
668                         arg_size = 4;
669                 }
670                 break;
671         case SAVE_FP:
672                 x86_alu_reg_imm (code, X86_SUB, X86_ESP, 8);
673                 x86_fst_membase (code, X86_ESP, 0, TRUE, TRUE);
674                 if (enable_arguments) {
675                         x86_alu_reg_imm (code, X86_SUB, X86_ESP, 8);
676                         x86_fst_membase (code, X86_ESP, 0, TRUE, TRUE);
677                         arg_size = 8;
678                 }
679                 break;
680         case SAVE_STRUCT:
681                 if (enable_arguments) {
682                         x86_push_membase (code, X86_EBP, 8);
683                         arg_size = 4;
684                 }
685                 break;
686         case SAVE_NONE:
687         default:
688                 break;
689         }
690
691
692         mono_add_patch_info (cfg, code-cfg->native_code, MONO_PATCH_INFO_METHODCONST, method);
693         x86_push_imm (code, method);
694         mono_add_patch_info (cfg, code-cfg->native_code, MONO_PATCH_INFO_ABS, func);
695         x86_call_code (code, 0);
696         x86_alu_reg_imm (code, X86_ADD, X86_ESP, arg_size + 4);
697
698         switch (save_mode) {
699         case SAVE_EAX_EDX:
700                 x86_pop_reg (code, X86_EAX);
701                 x86_pop_reg (code, X86_EDX);
702                 break;
703         case SAVE_EAX:
704                 x86_pop_reg (code, X86_EAX);
705                 break;
706         case SAVE_FP:
707                 x86_fld_membase (code, X86_ESP, 0, TRUE);
708                 x86_alu_reg_imm (code, X86_ADD, X86_ESP, 8);
709                 break;
710         case SAVE_NONE:
711         default:
712                 break;
713         }
714
715         return code;
716 }
717
718 #define EMIT_COND_BRANCH(ins,cond,sign) \
719 if (ins->flags & MONO_INST_BRLABEL) { \
720         if (ins->inst_i0->inst_c0) { \
721                 x86_branch (code, cond, cfg->native_code + ins->inst_i0->inst_c0, sign); \
722         } else { \
723                 mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_LABEL, ins->inst_i0); \
724                 if ((cfg->opt & MONO_OPT_BRANCH) && \
725                     x86_is_imm8 (ins->inst_i0->inst_c1 - cpos)) \
726                         x86_branch8 (code, cond, 0, sign); \
727                 else \
728                         x86_branch32 (code, cond, 0, sign); \
729         } \
730 } else { \
731         if (ins->inst_true_bb->native_offset) { \
732                 x86_branch (code, cond, cfg->native_code + ins->inst_true_bb->native_offset, sign); \
733         } else { \
734                 mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_BB, ins->inst_true_bb); \
735                 if ((cfg->opt & MONO_OPT_BRANCH) && \
736                     x86_is_imm8 (ins->inst_true_bb->max_offset - cpos)) \
737                         x86_branch8 (code, cond, 0, sign); \
738                 else \
739                         x86_branch32 (code, cond, 0, sign); \
740         } \
741 }
742
743 /* emit an exception if condition is fail */
744 #define EMIT_COND_SYSTEM_EXCEPTION(cond,signed,exc_name)            \
745         do {                                                        \
746                 mono_add_patch_info (cfg, code - cfg->native_code,   \
747                                     MONO_PATCH_INFO_EXC, exc_name);  \
748                 x86_branch32 (code, cond, 0, signed);               \
749         } while (0); 
750
751 #define EMIT_FPCOMPARE(code) do { \
752         x86_fcompp (code); \
753         x86_fnstsw (code); \
754 } while (0); 
755
756 /* FIXME: Add more instructions */
757 #define INST_IGNORES_CFLAGS(ins) (((ins)->opcode == CEE_BR) || ((ins)->opcode == OP_STORE_MEMBASE_IMM))
758
759 static void
760 peephole_pass (MonoCompile *cfg, MonoBasicBlock *bb)
761 {
762         MonoInst *ins, *last_ins = NULL;
763         ins = bb->code;
764
765         while (ins) {
766
767                 switch (ins->opcode) {
768                 case OP_ICONST:
769                         /* reg = 0 -> XOR (reg, reg) */
770                         /* XOR sets cflags on x86, so we cant do it always */
771                         if (ins->inst_c0 == 0 && ins->next && INST_IGNORES_CFLAGS (ins->next)) {
772                                 ins->opcode = CEE_XOR;
773                                 ins->sreg1 = ins->dreg;
774                                 ins->sreg2 = ins->dreg;
775                         }
776                         break;
777                 case OP_MUL_IMM: 
778                         /* remove unnecessary multiplication with 1 */
779                         if (ins->inst_imm == 1) {
780                                 if (ins->dreg != ins->sreg1) {
781                                         ins->opcode = OP_MOVE;
782                                 } else {
783                                         last_ins->next = ins->next;
784                                         ins = ins->next;
785                                         continue;
786                                 }
787                         }
788                         break;
789                 case OP_COMPARE_IMM:
790                         /* OP_COMPARE_IMM (reg, 0) 
791                          * --> 
792                          * OP_X86_TEST_NULL (reg) 
793                          */
794                         if (!ins->inst_imm)
795                                 ins->opcode = OP_X86_TEST_NULL;
796                         break;
797                 case OP_X86_COMPARE_MEMBASE_IMM:
798                         /* 
799                          * OP_STORE_MEMBASE_REG reg, offset(basereg)
800                          * OP_X86_COMPARE_MEMBASE_IMM offset(basereg), imm
801                          * -->
802                          * OP_STORE_MEMBASE_REG reg, offset(basereg)
803                          * OP_COMPARE_IMM reg, imm
804                          *
805                          * Note: if imm = 0 then OP_COMPARE_IMM replaced with OP_X86_TEST_NULL
806                          */
807                         if (last_ins && (last_ins->opcode == OP_STOREI4_MEMBASE_REG) &&
808                             ins->inst_basereg == last_ins->inst_destbasereg &&
809                             ins->inst_offset == last_ins->inst_offset) {
810                                         ins->opcode = OP_COMPARE_IMM;
811                                         ins->sreg1 = last_ins->sreg1;
812
813                                         /* check if we can remove cmp reg,0 with test null */
814                                         if (!ins->inst_imm)
815                                                 ins->opcode = OP_X86_TEST_NULL;
816                                 }
817
818                         break;
819                 case OP_LOAD_MEMBASE:
820                 case OP_LOADI4_MEMBASE:
821                         /* 
822                          * Note: if reg1 = reg2 the load op is removed
823                          *
824                          * OP_STORE_MEMBASE_REG reg1, offset(basereg) 
825                          * OP_LOAD_MEMBASE offset(basereg), reg2
826                          * -->
827                          * OP_STORE_MEMBASE_REG reg1, offset(basereg)
828                          * OP_MOVE reg1, reg2
829                          */
830                         if (last_ins && (last_ins->opcode == OP_STOREI4_MEMBASE_REG 
831                                          || last_ins->opcode == OP_STORE_MEMBASE_REG) &&
832                             ins->inst_basereg == last_ins->inst_destbasereg &&
833                             ins->inst_offset == last_ins->inst_offset) {
834                                 if (ins->dreg == last_ins->sreg1) {
835                                         last_ins->next = ins->next;                             
836                                         ins = ins->next;                                
837                                         continue;
838                                 } else {
839                                         //static int c = 0; printf ("MATCHX %s %d\n", cfg->method->name,c++);
840                                         ins->opcode = OP_MOVE;
841                                         ins->sreg1 = last_ins->sreg1;
842                                 }
843
844                         /* 
845                          * Note: reg1 must be different from the basereg in the second load
846                          * Note: if reg1 = reg2 is equal then second load is removed
847                          *
848                          * OP_LOAD_MEMBASE offset(basereg), reg1
849                          * OP_LOAD_MEMBASE offset(basereg), reg2
850                          * -->
851                          * OP_LOAD_MEMBASE offset(basereg), reg1
852                          * OP_MOVE reg1, reg2
853                          */
854                         } if (last_ins && (last_ins->opcode == OP_LOADI4_MEMBASE
855                                            || last_ins->opcode == OP_LOAD_MEMBASE) &&
856                               ins->inst_basereg != last_ins->dreg &&
857                               ins->inst_basereg == last_ins->inst_basereg &&
858                               ins->inst_offset == last_ins->inst_offset) {
859
860                                 if (ins->dreg == last_ins->dreg) {
861                                         last_ins->next = ins->next;                             
862                                         ins = ins->next;                                
863                                         continue;
864                                 } else {
865                                         ins->opcode = OP_MOVE;
866                                         ins->sreg1 = last_ins->dreg;
867                                 }
868
869                                 //g_assert_not_reached ();
870
871 #if 0
872                         /* 
873                          * OP_STORE_MEMBASE_IMM imm, offset(basereg) 
874                          * OP_LOAD_MEMBASE offset(basereg), reg
875                          * -->
876                          * OP_STORE_MEMBASE_IMM imm, offset(basereg) 
877                          * OP_ICONST reg, imm
878                          */
879                         } else if (last_ins && (last_ins->opcode == OP_STOREI4_MEMBASE_IMM
880                                                 || last_ins->opcode == OP_STORE_MEMBASE_IMM) &&
881                                    ins->inst_basereg == last_ins->inst_destbasereg &&
882                                    ins->inst_offset == last_ins->inst_offset) {
883                                 //static int c = 0; printf ("MATCHX %s %d\n", cfg->method->name,c++);
884                                 ins->opcode = OP_ICONST;
885                                 ins->inst_c0 = last_ins->inst_imm;
886                                 g_assert_not_reached (); // check this rule
887 #endif
888                         }
889                         break;
890                 case OP_LOADU1_MEMBASE:
891                 case OP_LOADI1_MEMBASE:
892                         /* 
893                          * Note: if reg1 = reg2 the load op is removed
894                          *
895                          * OP_STORE_MEMBASE_REG reg1, offset(basereg) 
896                          * OP_LOAD_MEMBASE offset(basereg), reg2
897                          * -->
898                          * OP_STORE_MEMBASE_REG reg1, offset(basereg)
899                          * OP_MOVE reg1, reg2
900                          */
901                         if (last_ins && (last_ins->opcode == OP_STOREI1_MEMBASE_REG) &&
902                                         ins->inst_basereg == last_ins->inst_destbasereg &&
903                                         ins->inst_offset == last_ins->inst_offset) {
904                                 if (ins->dreg == last_ins->sreg1) {
905                                         last_ins->next = ins->next;                             
906                                         ins = ins->next;                                
907                                         continue;
908                                 } else {
909                                         //static int c = 0; printf ("MATCHX %s %d\n", cfg->method->name,c++);
910                                         ins->opcode = OP_MOVE;
911                                         ins->sreg1 = last_ins->sreg1;
912                                 }
913                         }
914                         break;
915                 case OP_LOADU2_MEMBASE:
916                 case OP_LOADI2_MEMBASE:
917                         /* 
918                          * Note: if reg1 = reg2 the load op is removed
919                          *
920                          * OP_STORE_MEMBASE_REG reg1, offset(basereg) 
921                          * OP_LOAD_MEMBASE offset(basereg), reg2
922                          * -->
923                          * OP_STORE_MEMBASE_REG reg1, offset(basereg)
924                          * OP_MOVE reg1, reg2
925                          */
926                         if (last_ins && (last_ins->opcode == OP_STOREI2_MEMBASE_REG) &&
927                                         ins->inst_basereg == last_ins->inst_destbasereg &&
928                                         ins->inst_offset == last_ins->inst_offset) {
929                                 if (ins->dreg == last_ins->sreg1) {
930                                         last_ins->next = ins->next;                             
931                                         ins = ins->next;                                
932                                         continue;
933                                 } else {
934                                         //static int c = 0; printf ("MATCHX %s %d\n", cfg->method->name,c++);
935                                         ins->opcode = OP_MOVE;
936                                         ins->sreg1 = last_ins->sreg1;
937                                 }
938                         }
939                         break;
940                 case CEE_CONV_I4:
941                 case CEE_CONV_U4:
942                 case OP_MOVE:
943                         /*
944                          * Removes:
945                          *
946                          * OP_MOVE reg, reg 
947                          */
948                         if (ins->dreg == ins->sreg1) {
949                                 if (last_ins)
950                                         last_ins->next = ins->next;                             
951                                 ins = ins->next;
952                                 continue;
953                         }
954                         /* 
955                          * Removes:
956                          *
957                          * OP_MOVE sreg, dreg 
958                          * OP_MOVE dreg, sreg
959                          */
960                         if (last_ins && last_ins->opcode == OP_MOVE &&
961                             ins->sreg1 == last_ins->dreg &&
962                             ins->dreg == last_ins->sreg1) {
963                                 last_ins->next = ins->next;                             
964                                 ins = ins->next;                                
965                                 continue;
966                         }
967                         break;
968                 }
969                 last_ins = ins;
970                 ins = ins->next;
971         }
972         bb->last_ins = last_ins;
973 }
974
975 static const int 
976 branch_cc_table [] = {
977         X86_CC_EQ, X86_CC_GE, X86_CC_GT, X86_CC_LE, X86_CC_LT,
978         X86_CC_NE, X86_CC_GE, X86_CC_GT, X86_CC_LE, X86_CC_LT,
979         X86_CC_O, X86_CC_NO, X86_CC_C, X86_CC_NC
980 };
981
982 #define DEBUG(a) if (cfg->verbose_level > 1) a
983 //#define DEBUG(a)
984
985 /*
986  * returns the offset used by spillvar. It allocates a new
987  * spill variable if necessary. 
988  */
989 static int
990 mono_spillvar_offset (MonoCompile *cfg, int spillvar)
991 {
992         MonoSpillInfo **si, *info;
993         int i = 0;
994
995         si = &cfg->spill_info; 
996         
997         while (i <= spillvar) {
998
999                 if (!*si) {
1000                         *si = info = mono_mempool_alloc (cfg->mempool, sizeof (MonoSpillInfo));
1001                         info->next = NULL;
1002                         cfg->stack_offset -= sizeof (gpointer);
1003                         info->offset = cfg->stack_offset;
1004                 }
1005
1006                 if (i == spillvar)
1007                         return (*si)->offset;
1008
1009                 i++;
1010                 si = &(*si)->next;
1011         }
1012
1013         g_assert_not_reached ();
1014         return 0;
1015 }
1016
1017 /*
1018  * returns the offset used by spillvar. It allocates a new
1019  * spill float variable if necessary. 
1020  * (same as mono_spillvar_offset but for float)
1021  */
1022 static int
1023 mono_spillvar_offset_float (MonoCompile *cfg, int spillvar)
1024 {
1025         MonoSpillInfo **si, *info;
1026         int i = 0;
1027
1028         si = &cfg->spill_info_float; 
1029         
1030         while (i <= spillvar) {
1031
1032                 if (!*si) {
1033                         *si = info = mono_mempool_alloc (cfg->mempool, sizeof (MonoSpillInfo));
1034                         info->next = NULL;
1035                         cfg->stack_offset -= sizeof (double);
1036                         info->offset = cfg->stack_offset;
1037                 }
1038
1039                 if (i == spillvar)
1040                         return (*si)->offset;
1041
1042                 i++;
1043                 si = &(*si)->next;
1044         }
1045
1046         g_assert_not_reached ();
1047         return 0;
1048 }
1049
1050 /*
1051  * Creates a store for spilled floating point items
1052  */
1053 static MonoInst*
1054 create_spilled_store_float (MonoCompile *cfg, int spill, int reg, MonoInst *ins)
1055 {
1056         MonoInst *store;
1057         MONO_INST_NEW (cfg, store, OP_STORER8_MEMBASE_REG);
1058         store->sreg1 = reg;
1059         store->inst_destbasereg = X86_EBP;
1060         store->inst_offset = mono_spillvar_offset_float (cfg, spill);
1061
1062         DEBUG (g_print ("SPILLED FLOAT STORE (%d at 0x%08x(%%sp)) (from %d)\n", spill, store->inst_offset, reg));
1063         return store;
1064 }
1065
1066 /*
1067  * Creates a load for spilled floating point items 
1068  */
1069 static MonoInst*
1070 create_spilled_load_float (MonoCompile *cfg, int spill, int reg, MonoInst *ins)
1071 {
1072         MonoInst *load;
1073         MONO_INST_NEW (cfg, load, OP_LOADR8_SPILL_MEMBASE);
1074         load->dreg = reg;
1075         load->inst_basereg = X86_EBP;
1076         load->inst_offset = mono_spillvar_offset_float (cfg, spill);
1077
1078         DEBUG (g_print ("SPILLED FLOAT LOAD (%d at 0x%08x(%%sp)) (from %d)\n", spill, load->inst_offset, reg));
1079         return load;
1080 }
1081
1082 #define reg_is_freeable(r) ((r) >= 0 && (r) <= 7 && X86_IS_CALLEE ((r)))
1083
1084 typedef struct {
1085         int born_in;
1086         int killed_in;
1087         int last_use;
1088         int prev_use;
1089         int flags;              /* used to track fp spill/load */
1090 } RegTrack;
1091
1092 static const char*const * ins_spec = pentium_desc;
1093
1094 static void
1095 print_ins (int i, MonoInst *ins)
1096 {
1097         const char *spec = ins_spec [ins->opcode];
1098         g_print ("\t%-2d %s", i, mono_inst_name (ins->opcode));
1099         if (spec [MONO_INST_DEST]) {
1100                 if (ins->dreg >= MONO_MAX_IREGS)
1101                         g_print (" R%d <-", ins->dreg);
1102                 else
1103                         g_print (" %s <-", mono_arch_regname (ins->dreg));
1104         }
1105         if (spec [MONO_INST_SRC1]) {
1106                 if (ins->sreg1 >= MONO_MAX_IREGS)
1107                         g_print (" R%d", ins->sreg1);
1108                 else
1109                         g_print (" %s", mono_arch_regname (ins->sreg1));
1110         }
1111         if (spec [MONO_INST_SRC2]) {
1112                 if (ins->sreg2 >= MONO_MAX_IREGS)
1113                         g_print (" R%d", ins->sreg2);
1114                 else
1115                         g_print (" %s", mono_arch_regname (ins->sreg2));
1116         }
1117         if (spec [MONO_INST_CLOB])
1118                 g_print (" clobbers: %c", spec [MONO_INST_CLOB]);
1119         g_print ("\n");
1120 }
1121
1122 static void
1123 print_regtrack (RegTrack *t, int num)
1124 {
1125         int i;
1126         char buf [32];
1127         const char *r;
1128         
1129         for (i = 0; i < num; ++i) {
1130                 if (!t [i].born_in)
1131                         continue;
1132                 if (i >= MONO_MAX_IREGS) {
1133                         g_snprintf (buf, sizeof(buf), "R%d", i);
1134                         r = buf;
1135                 } else
1136                         r = mono_arch_regname (i);
1137                 g_print ("liveness: %s [%d - %d]\n", r, t [i].born_in, t[i].last_use);
1138         }
1139 }
1140
1141 typedef struct InstList InstList;
1142
1143 struct InstList {
1144         InstList *prev;
1145         InstList *next;
1146         MonoInst *data;
1147 };
1148
1149 static inline InstList*
1150 inst_list_prepend (MonoMemPool *pool, InstList *list, MonoInst *data)
1151 {
1152         InstList *item = mono_mempool_alloc (pool, sizeof (InstList));
1153         item->data = data;
1154         item->prev = NULL;
1155         item->next = list;
1156         if (list)
1157                 list->prev = item;
1158         return item;
1159 }
1160
1161 /*
1162  * Force the spilling of the variable in the symbolic register 'reg'.
1163  */
1164 static int
1165 get_register_force_spilling (MonoCompile *cfg, InstList *item, MonoInst *ins, int reg)
1166 {
1167         MonoInst *load;
1168         int i, sel, spill;
1169         
1170         sel = cfg->rs->iassign [reg];
1171         /*i = cfg->rs->isymbolic [sel];
1172         g_assert (i == reg);*/
1173         i = reg;
1174         spill = ++cfg->spill_count;
1175         cfg->rs->iassign [i] = -spill - 1;
1176         mono_regstate_free_int (cfg->rs, sel);
1177         /* we need to create a spill var and insert a load to sel after the current instruction */
1178         MONO_INST_NEW (cfg, load, OP_LOAD_MEMBASE);
1179         load->dreg = sel;
1180         load->inst_basereg = X86_EBP;
1181         load->inst_offset = mono_spillvar_offset (cfg, spill);
1182         if (item->prev) {
1183                 while (ins->next != item->prev->data)
1184                         ins = ins->next;
1185         }
1186         load->next = ins->next;
1187         ins->next = load;
1188         DEBUG (g_print ("SPILLED LOAD (%d at 0x%08x(%%ebp)) R%d (freed %s)\n", spill, load->inst_offset, i, mono_arch_regname (sel)));
1189         i = mono_regstate_alloc_int (cfg->rs, 1 << sel);
1190         g_assert (i == sel);
1191
1192         return sel;
1193 }
1194
1195 static int
1196 get_register_spilling (MonoCompile *cfg, InstList *item, MonoInst *ins, guint32 regmask, int reg)
1197 {
1198         MonoInst *load;
1199         int i, sel, spill;
1200
1201         DEBUG (g_print ("\tstart regmask to assign R%d: 0x%08x (R%d <- R%d R%d)\n", reg, regmask, ins->dreg, ins->sreg1, ins->sreg2));
1202         /* exclude the registers in the current instruction */
1203         if (reg != ins->sreg1 && (reg_is_freeable (ins->sreg1) || (ins->sreg1 >= MONO_MAX_IREGS && cfg->rs->iassign [ins->sreg1] >= 0))) {
1204                 if (ins->sreg1 >= MONO_MAX_IREGS)
1205                         regmask &= ~ (1 << cfg->rs->iassign [ins->sreg1]);
1206                 else
1207                         regmask &= ~ (1 << ins->sreg1);
1208                 DEBUG (g_print ("\t\texcluding sreg1 %s\n", mono_arch_regname (ins->sreg1)));
1209         }
1210         if (reg != ins->sreg2 && (reg_is_freeable (ins->sreg2) || (ins->sreg2 >= MONO_MAX_IREGS && cfg->rs->iassign [ins->sreg2] >= 0))) {
1211                 if (ins->sreg2 >= MONO_MAX_IREGS)
1212                         regmask &= ~ (1 << cfg->rs->iassign [ins->sreg2]);
1213                 else
1214                         regmask &= ~ (1 << ins->sreg2);
1215                 DEBUG (g_print ("\t\texcluding sreg2 %s %d\n", mono_arch_regname (ins->sreg2), ins->sreg2));
1216         }
1217         if (reg != ins->dreg && reg_is_freeable (ins->dreg)) {
1218                 regmask &= ~ (1 << ins->dreg);
1219                 DEBUG (g_print ("\t\texcluding dreg %s\n", mono_arch_regname (ins->dreg)));
1220         }
1221
1222         DEBUG (g_print ("\t\tavailable regmask: 0x%08x\n", regmask));
1223         g_assert (regmask); /* need at least a register we can free */
1224         sel = -1;
1225         /* we should track prev_use and spill the register that's farther */
1226         for (i = 0; i < MONO_MAX_IREGS; ++i) {
1227                 if (regmask & (1 << i)) {
1228                         sel = i;
1229                         DEBUG (g_print ("\t\tselected register %s has assignment %d\n", mono_arch_regname (sel), cfg->rs->iassign [sel]));
1230                         break;
1231                 }
1232         }
1233         i = cfg->rs->isymbolic [sel];
1234         spill = ++cfg->spill_count;
1235         cfg->rs->iassign [i] = -spill - 1;
1236         mono_regstate_free_int (cfg->rs, sel);
1237         /* we need to create a spill var and insert a load to sel after the current instruction */
1238         MONO_INST_NEW (cfg, load, OP_LOAD_MEMBASE);
1239         load->dreg = sel;
1240         load->inst_basereg = X86_EBP;
1241         load->inst_offset = mono_spillvar_offset (cfg, spill);
1242         if (item->prev) {
1243                 while (ins->next != item->prev->data)
1244                         ins = ins->next;
1245         }
1246         load->next = ins->next;
1247         ins->next = load;
1248         DEBUG (g_print ("\tSPILLED LOAD (%d at 0x%08x(%%ebp)) R%d (freed %s)\n", spill, load->inst_offset, i, mono_arch_regname (sel)));
1249         i = mono_regstate_alloc_int (cfg->rs, 1 << sel);
1250         g_assert (i == sel);
1251         
1252         return sel;
1253 }
1254
1255 static MonoInst*
1256 create_copy_ins (MonoCompile *cfg, int dest, int src, MonoInst *ins)
1257 {
1258         MonoInst *copy;
1259         MONO_INST_NEW (cfg, copy, OP_MOVE);
1260         copy->dreg = dest;
1261         copy->sreg1 = src;
1262         if (ins) {
1263                 copy->next = ins->next;
1264                 ins->next = copy;
1265         }
1266         DEBUG (g_print ("\tforced copy from %s to %s\n", mono_arch_regname (src), mono_arch_regname (dest)));
1267         return copy;
1268 }
1269
1270 static MonoInst*
1271 create_spilled_store (MonoCompile *cfg, int spill, int reg, int prev_reg, MonoInst *ins)
1272 {
1273         MonoInst *store;
1274         MONO_INST_NEW (cfg, store, OP_STORE_MEMBASE_REG);
1275         store->sreg1 = reg;
1276         store->inst_destbasereg = X86_EBP;
1277         store->inst_offset = mono_spillvar_offset (cfg, spill);
1278         if (ins) {
1279                 store->next = ins->next;
1280                 ins->next = store;
1281         }
1282         DEBUG (g_print ("\tSPILLED STORE (%d at 0x%08x(%%ebp)) R%d (from %s)\n", spill, store->inst_offset, prev_reg, mono_arch_regname (reg)));
1283         return store;
1284 }
1285
1286 static void
1287 insert_before_ins (MonoInst *ins, InstList *item, MonoInst* to_insert)
1288 {
1289         MonoInst *prev;
1290         if (item->next) {
1291                 prev = item->next->data;
1292
1293                 while (prev->next != ins)
1294                         prev = prev->next;
1295                 to_insert->next = ins;
1296                 prev->next = to_insert;
1297         } else {
1298                 to_insert->next = ins;
1299         }
1300         /* 
1301          * needed otherwise in the next instruction we can add an ins to the 
1302          * end and that would get past this instruction.
1303          */
1304         item->data = to_insert; 
1305 }
1306
1307
1308 #if  0
1309 static int
1310 alloc_int_reg (MonoCompile *cfg, InstList *curinst, MonoInst *ins, int sym_reg, guint32 allow_mask)
1311 {
1312         int val = cfg->rs->iassign [sym_reg];
1313         if (val < 0) {
1314                 int spill = 0;
1315                 if (val < -1) {
1316                         /* the register gets spilled after this inst */
1317                         spill = -val -1;
1318                 }
1319                 val = mono_regstate_alloc_int (cfg->rs, allow_mask);
1320                 if (val < 0)
1321                         val = get_register_spilling (cfg, curinst, ins, allow_mask, sym_reg);
1322                 cfg->rs->iassign [sym_reg] = val;
1323                 /* add option to store before the instruction for src registers */
1324                 if (spill)
1325                         create_spilled_store (cfg, spill, val, sym_reg, ins);
1326         }
1327         cfg->rs->isymbolic [val] = sym_reg;
1328         return val;
1329 }
1330 #endif
1331
1332 /* flags used in reginfo->flags */
1333 enum {
1334         MONO_X86_FP_NEEDS_LOAD_SPILL    = 1 << 0,
1335         MONO_X86_FP_NEEDS_SPILL                 = 1 << 1,
1336         MONO_X86_FP_NEEDS_LOAD                  = 1 << 2,
1337         MONO_X86_REG_NOT_ECX                    = 1 << 3,
1338         MONO_X86_REG_EAX                                = 1 << 4,
1339         MONO_X86_REG_EDX                                = 1 << 5,
1340         MONO_X86_REG_ECX                                = 1 << 6
1341 };
1342
1343 static int
1344 mono_x86_alloc_int_reg (MonoCompile *cfg, InstList *tmp, MonoInst *ins, guint32 dest_mask, int sym_reg, int flags)
1345 {
1346         int val;
1347         int test_mask = dest_mask;
1348
1349         if (flags & MONO_X86_REG_EAX)
1350                 test_mask &= (1 << X86_EAX);
1351         else if (flags & MONO_X86_REG_EDX)
1352                 test_mask &= (1 << X86_EDX);
1353         else if (flags & MONO_X86_REG_ECX)
1354                 test_mask &= (1 << X86_ECX);
1355         else if (flags & MONO_X86_REG_NOT_ECX)
1356                 test_mask &= ~ (1 << X86_ECX);
1357
1358         val = mono_regstate_alloc_int (cfg->rs, test_mask);
1359         if (val >= 0 && test_mask != dest_mask)
1360                 DEBUG(g_print ("\tUsed flag to allocate reg %s for R%u\n", mono_arch_regname (val), sym_reg));
1361
1362         if (val < 0 && (flags & MONO_X86_REG_NOT_ECX)) {
1363                 DEBUG(g_print ("\tFailed to allocate flag suggested mask (%u) but exluding ECX\n", test_mask));
1364                 val = mono_regstate_alloc_int (cfg->rs, (dest_mask & (~1 << X86_ECX)));
1365         }
1366
1367         if (val < 0) {
1368                 val = mono_regstate_alloc_int (cfg->rs, dest_mask);
1369                 if (val < 0)
1370                         val = get_register_spilling (cfg, tmp, ins, dest_mask, sym_reg);
1371         }
1372
1373         return val;
1374 }
1375
1376
1377 /*#include "cprop.c"*/
1378
1379 /*
1380  * Local register allocation.
1381  * We first scan the list of instructions and we save the liveness info of
1382  * each register (when the register is first used, when it's value is set etc.).
1383  * We also reverse the list of instructions (in the InstList list) because assigning
1384  * registers backwards allows for more tricks to be used.
1385  */
1386 void
1387 mono_arch_local_regalloc (MonoCompile *cfg, MonoBasicBlock *bb)
1388 {
1389         MonoInst *ins;
1390         MonoRegState *rs = cfg->rs;
1391         int i, val, fpcount;
1392         RegTrack *reginfo, *reginfof;
1393         RegTrack *reginfo1, *reginfo2, *reginfod;
1394         InstList *tmp, *reversed = NULL;
1395         const char *spec;
1396         guint32 src1_mask, src2_mask, dest_mask;
1397         GList *fspill_list = NULL;
1398         int fspill = 0;
1399
1400         if (!bb->code)
1401                 return;
1402         rs->next_vireg = bb->max_ireg;
1403         rs->next_vfreg = bb->max_freg;
1404         mono_regstate_assign (rs);
1405         reginfo = g_malloc0 (sizeof (RegTrack) * rs->next_vireg);
1406         reginfof = g_malloc0 (sizeof (RegTrack) * rs->next_vfreg);
1407         rs->ifree_mask = X86_CALLEE_REGS;
1408
1409         ins = bb->code;
1410
1411         /*if (cfg->opt & MONO_OPT_COPYPROP)
1412                 local_copy_prop (cfg, ins);*/
1413
1414         i = 1;
1415         fpcount = 0;
1416         DEBUG (g_print ("LOCAL regalloc: basic block: %d\n", bb->block_num));
1417         /* forward pass on the instructions to collect register liveness info */
1418         while (ins) {
1419                 spec = ins_spec [ins->opcode];
1420                 
1421                 DEBUG (print_ins (i, ins));
1422
1423                 if (spec [MONO_INST_SRC1]) {
1424                         if (spec [MONO_INST_SRC1] == 'f') {
1425                                 GList *spill;
1426                                 reginfo1 = reginfof;
1427
1428                                 spill = g_list_first (fspill_list);
1429                                 if (spill && fpcount < MONO_MAX_FREGS) {
1430                                         reginfo1 [ins->sreg1].flags |= MONO_X86_FP_NEEDS_LOAD;
1431                                         fspill_list = g_list_remove (fspill_list, spill->data);
1432                                 } else
1433                                         fpcount--;
1434                         }
1435                         else
1436                                 reginfo1 = reginfo;
1437                         reginfo1 [ins->sreg1].prev_use = reginfo1 [ins->sreg1].last_use;
1438                         reginfo1 [ins->sreg1].last_use = i;
1439                         if (spec [MONO_INST_SRC1] == 'L') {
1440                                 /* The virtual register is allocated sequentially */
1441                                 reginfo1 [ins->sreg1 + 1].prev_use = reginfo1 [ins->sreg1 + 1].last_use;
1442                                 reginfo1 [ins->sreg1 + 1].last_use = i;
1443                                 if (reginfo1 [ins->sreg1 + 1].born_in == 0 || reginfo1 [ins->sreg1 + 1].born_in > i)
1444                                         reginfo1 [ins->sreg1 + 1].born_in = i;
1445
1446                                 reginfo1 [ins->sreg1].flags |= MONO_X86_REG_EAX;
1447                                 reginfo1 [ins->sreg1 + 1].flags |= MONO_X86_REG_EDX;
1448                         }
1449                 } else {
1450                         ins->sreg1 = -1;
1451                 }
1452                 if (spec [MONO_INST_SRC2]) {
1453                         if (spec [MONO_INST_SRC2] == 'f') {
1454                                 GList *spill;
1455                                 reginfo2 = reginfof;
1456                                 spill = g_list_first (fspill_list);
1457                                 if (spill) {
1458                                         reginfo2 [ins->sreg2].flags |= MONO_X86_FP_NEEDS_LOAD;
1459                                         fspill_list = g_list_remove (fspill_list, spill->data);
1460                                         if (fpcount >= MONO_MAX_FREGS) {
1461                                                 fspill++;
1462                                                 fspill_list = g_list_prepend (fspill_list, GINT_TO_POINTER(fspill));
1463                                                 reginfo2 [ins->sreg2].flags |= MONO_X86_FP_NEEDS_LOAD_SPILL;
1464                                         }
1465                                 } else
1466                                         fpcount--;
1467                         }
1468                         else
1469                                 reginfo2 = reginfo;
1470                         reginfo2 [ins->sreg2].prev_use = reginfo2 [ins->sreg2].last_use;
1471                         reginfo2 [ins->sreg2].last_use = i;
1472                         if (spec [MONO_INST_SRC2] == 'L') {
1473                                 /* The virtual register is allocated sequentially */
1474                                 reginfo2 [ins->sreg2 + 1].prev_use = reginfo2 [ins->sreg2 + 1].last_use;
1475                                 reginfo2 [ins->sreg2 + 1].last_use = i;
1476                                 if (reginfo2 [ins->sreg2 + 1].born_in == 0 || reginfo2 [ins->sreg2 + 1].born_in > i)
1477                                         reginfo2 [ins->sreg2 + 1].born_in = i;
1478                         }
1479                         if (spec [MONO_INST_CLOB] == 's') {
1480                                 reginfo2 [ins->sreg1].flags |= MONO_X86_REG_NOT_ECX;
1481                                 reginfo2 [ins->sreg2].flags |= MONO_X86_REG_ECX;
1482                         }
1483                 } else {
1484                         ins->sreg2 = -1;
1485                 }
1486                 if (spec [MONO_INST_DEST]) {
1487                         if (spec [MONO_INST_DEST] == 'f') {
1488                                 reginfod = reginfof;
1489                                 if (fpcount >= MONO_MAX_FREGS) {
1490                                         reginfod [ins->dreg].flags |= MONO_X86_FP_NEEDS_SPILL;
1491                                         fspill++;
1492                                         fspill_list = g_list_prepend (fspill_list, GINT_TO_POINTER(fspill));
1493                                         fpcount--;
1494                                 }
1495                                 fpcount++;
1496                         }
1497                         else
1498                                 reginfod = reginfo;
1499                         if (spec [MONO_INST_DEST] != 'b') /* it's not just a base register */
1500                                 reginfod [ins->dreg].killed_in = i;
1501                         reginfod [ins->dreg].prev_use = reginfod [ins->dreg].last_use;
1502                         reginfod [ins->dreg].last_use = i;
1503                         if (reginfod [ins->dreg].born_in == 0 || reginfod [ins->dreg].born_in > i)
1504                                 reginfod [ins->dreg].born_in = i;
1505                         if (spec [MONO_INST_DEST] == 'l' || spec [MONO_INST_DEST] == 'L') {
1506                                 /* The virtual register is allocated sequentially */
1507                                 reginfod [ins->dreg + 1].prev_use = reginfod [ins->dreg + 1].last_use;
1508                                 reginfod [ins->dreg + 1].last_use = i;
1509                                 if (reginfod [ins->dreg + 1].born_in == 0 || reginfod [ins->dreg + 1].born_in > i)
1510                                         reginfod [ins->dreg + 1].born_in = i;
1511
1512                                 reginfod [ins->dreg].flags |= MONO_X86_REG_EAX;
1513                                 reginfod [ins->dreg + 1].flags |= MONO_X86_REG_EDX;
1514                         }
1515                 } else {
1516                         ins->dreg = -1;
1517                 }
1518
1519                 reversed = inst_list_prepend (cfg->mempool, reversed, ins);
1520                 ++i;
1521                 ins = ins->next;
1522         }
1523
1524         // todo: check if we have anything left on fp stack, in verify mode?
1525         fspill = 0;
1526
1527         DEBUG (print_regtrack (reginfo, rs->next_vireg));
1528         DEBUG (print_regtrack (reginfof, rs->next_vfreg));
1529         tmp = reversed;
1530         while (tmp) {
1531                 int prev_dreg, prev_sreg1, prev_sreg2, clob_dreg;
1532                 dest_mask = src1_mask = src2_mask = X86_CALLEE_REGS;
1533                 --i;
1534                 ins = tmp->data;
1535                 spec = ins_spec [ins->opcode];
1536                 prev_dreg = -1;
1537                 clob_dreg = -1;
1538                 DEBUG (g_print ("processing:"));
1539                 DEBUG (print_ins (i, ins));
1540                 if (spec [MONO_INST_CLOB] == 's') {
1541                         if (rs->ifree_mask & (1 << X86_ECX)) {
1542                                 DEBUG (g_print ("\tshortcut assignment of R%d to ECX\n", ins->sreg2));
1543                                 rs->iassign [ins->sreg2] = X86_ECX;
1544                                 rs->isymbolic [X86_ECX] = ins->sreg2;
1545                                 ins->sreg2 = X86_ECX;
1546                                 rs->ifree_mask &= ~ (1 << X86_ECX);
1547                         } else {
1548                                 int need_ecx_spill = TRUE;
1549                                 /* 
1550                                  * we first check if src1/dreg is already assigned a register
1551                                  * and then we force a spill of the var assigned to ECX.
1552                                  */
1553                                 /* the destination register can't be ECX */
1554                                 dest_mask &= ~ (1 << X86_ECX);
1555                                 src1_mask &= ~ (1 << X86_ECX);
1556                                 val = rs->iassign [ins->dreg];
1557                                 /* 
1558                                  * the destination register is already assigned to ECX:
1559                                  * we need to allocate another register for it and then
1560                                  * copy from this to ECX.
1561                                  */
1562                                 if (val == X86_ECX && ins->dreg != ins->sreg2) {
1563                                         int new_dest;
1564                                         new_dest = mono_x86_alloc_int_reg (cfg, tmp, ins, dest_mask, ins->dreg, reginfo [ins->dreg].flags);
1565                                         g_assert (new_dest >= 0);
1566                                         DEBUG (g_print ("\tclob:s changing dreg R%d to %s from ECX\n", ins->dreg, mono_arch_regname (new_dest)));
1567
1568                                         rs->isymbolic [new_dest] = ins->dreg;
1569                                         rs->iassign [ins->dreg] = new_dest;
1570                                         clob_dreg = ins->dreg;
1571                                         ins->dreg = new_dest;
1572                                         create_copy_ins (cfg, X86_ECX, new_dest, ins);
1573                                         need_ecx_spill = FALSE;
1574                                         /*DEBUG (g_print ("\tforced spill of R%d\n", ins->dreg));
1575                                         val = get_register_force_spilling (cfg, tmp, ins, ins->dreg);
1576                                         rs->iassign [ins->dreg] = val;
1577                                         rs->isymbolic [val] = prev_dreg;
1578                                         ins->dreg = val;*/
1579                                 }
1580                                 val = rs->iassign [ins->sreg1];
1581                                 if (val == X86_ECX) {
1582                                         g_assert_not_reached ();
1583                                 } else if (val >= 0) {
1584                                         /* 
1585                                          * the first src reg was already assigned to a register,
1586                                          * we need to copy it to the dest register because the 
1587                                          * shift instruction clobbers the first operand.
1588                                          */
1589                                         MonoInst *copy = create_copy_ins (cfg, ins->dreg, val, NULL);
1590                                         DEBUG (g_print ("\tclob:s moved sreg1 from R%d to R%d\n", val, ins->dreg));
1591                                         insert_before_ins (ins, tmp, copy);
1592                                 }
1593                                 val = rs->iassign [ins->sreg2];
1594                                 if (val >= 0 && val != X86_ECX) {
1595                                         MonoInst *move = create_copy_ins (cfg, X86_ECX, val, NULL);
1596                                         DEBUG (g_print ("\tmoved arg from R%d (%d) to ECX\n", val, ins->sreg2));
1597                                         move->next = ins;
1598                                         g_assert_not_reached ();
1599                                         /* FIXME: where is move connected to the instruction list? */
1600                                         //tmp->prev->data->next = move;
1601                                 }
1602                                 if (need_ecx_spill && !(rs->ifree_mask & (1 << X86_ECX))) {
1603                                         DEBUG (g_print ("\tforced spill of R%d\n", rs->isymbolic [X86_ECX]));
1604                                         get_register_force_spilling (cfg, tmp, ins, rs->isymbolic [X86_ECX]);
1605                                         mono_regstate_free_int (rs, X86_ECX);
1606                                 }
1607                                 /* force-set sreg2 */
1608                                 rs->iassign [ins->sreg2] = X86_ECX;
1609                                 rs->isymbolic [X86_ECX] = ins->sreg2;
1610                                 ins->sreg2 = X86_ECX;
1611                                 rs->ifree_mask &= ~ (1 << X86_ECX);
1612                         }
1613                 } else if (spec [MONO_INST_CLOB] == 'd') { /* division */
1614                         int dest_reg = X86_EAX;
1615                         int clob_reg = X86_EDX;
1616                         if (spec [MONO_INST_DEST] == 'd') {
1617                                 dest_reg = X86_EDX; /* reminder */
1618                                 clob_reg = X86_EAX;
1619                         }
1620                         val = rs->iassign [ins->dreg];
1621                         if (0 && val >= 0 && val != dest_reg && !(rs->ifree_mask & (1 << dest_reg))) {
1622                                 DEBUG (g_print ("\tforced spill of R%d\n", rs->isymbolic [dest_reg]));
1623                                 get_register_force_spilling (cfg, tmp, ins, rs->isymbolic [dest_reg]);
1624                                 mono_regstate_free_int (rs, dest_reg);
1625                         }
1626                         if (val < 0) {
1627                                 if (val < -1) {
1628                                         /* the register gets spilled after this inst */
1629                                         int spill = -val -1;
1630                                         dest_mask = 1 << clob_reg;
1631                                         prev_dreg = ins->dreg;
1632                                         val = mono_regstate_alloc_int (rs, dest_mask);
1633                                         if (val < 0)
1634                                                 val = get_register_spilling (cfg, tmp, ins, dest_mask, ins->dreg);
1635                                         rs->iassign [ins->dreg] = val;
1636                                         if (spill)
1637                                                 create_spilled_store (cfg, spill, val, prev_dreg, ins);
1638                                         DEBUG (g_print ("\tassigned dreg %s to dest R%d\n", mono_arch_regname (val), ins->dreg));
1639                                         rs->isymbolic [val] = prev_dreg;
1640                                         ins->dreg = val;
1641                                         if (val != dest_reg) { /* force a copy */
1642                                                 create_copy_ins (cfg, val, dest_reg, ins);
1643                                         }
1644                                 } else {
1645                                         DEBUG (g_print ("\tshortcut assignment of R%d to %s\n", ins->dreg, mono_arch_regname (dest_reg)));
1646                                         prev_dreg = ins->dreg;
1647                                         rs->iassign [ins->dreg] = dest_reg;
1648                                         rs->isymbolic [dest_reg] = ins->dreg;
1649                                         ins->dreg = dest_reg;
1650                                         rs->ifree_mask &= ~ (1 << dest_reg);
1651                                 }
1652                         } else {
1653                                 //DEBUG (g_print ("dest reg in div assigned: %s\n", mono_arch_regname (val)));
1654                                 if (val != dest_reg) { /* force a copy */
1655                                         create_copy_ins (cfg, val, dest_reg, ins);
1656                                         if (!(rs->ifree_mask & (1 << dest_reg)) && rs->isymbolic [dest_reg] >= MONO_MAX_IREGS) {
1657                                                 DEBUG (g_print ("\tforced spill of R%d\n", rs->isymbolic [dest_reg]));
1658                                                 get_register_force_spilling (cfg, tmp, ins, rs->isymbolic [dest_reg]);
1659                                                 mono_regstate_free_int (rs, dest_reg);
1660                                         }
1661                                 }
1662                         }
1663                         if (!(rs->ifree_mask & (1 << clob_reg)) && (clob_reg != val) && (rs->isymbolic [clob_reg] >= 8)) {
1664                                 DEBUG (g_print ("\tforced spill of clobbered reg R%d\n", rs->isymbolic [clob_reg]));
1665                                 get_register_force_spilling (cfg, tmp, ins, rs->isymbolic [clob_reg]);
1666                                 mono_regstate_free_int (rs, clob_reg);
1667                         }
1668                         src1_mask = 1 << X86_EAX;
1669                         src2_mask = 1 << X86_ECX;
1670                 }
1671                 if (spec [MONO_INST_DEST] == 'l') {
1672                         int hreg;
1673                         val = rs->iassign [ins->dreg];
1674                         /* check special case when dreg have been moved from ecx (clob shift) */
1675                         if (spec [MONO_INST_CLOB] == 's' && clob_dreg != -1)
1676                                 hreg = clob_dreg + 1;
1677                         else
1678                                 hreg = ins->dreg + 1;
1679
1680                         /* base prev_dreg on fixed hreg, handle clob case */
1681                         val = hreg - 1;
1682
1683                         if (val != rs->isymbolic [X86_EAX] && !(rs->ifree_mask & (1 << X86_EAX))) {
1684                                 DEBUG (g_print ("\t(long-low) forced spill of R%d\n", rs->isymbolic [X86_EAX]));
1685                                 get_register_force_spilling (cfg, tmp, ins, rs->isymbolic [X86_EAX]);
1686                                 mono_regstate_free_int (rs, X86_EAX);
1687                         }
1688                         if (hreg != rs->isymbolic [X86_EDX] && !(rs->ifree_mask & (1 << X86_EDX))) {
1689                                 DEBUG (g_print ("\t(long-high) forced spill of R%d\n", rs->isymbolic [X86_EDX]));
1690                                 get_register_force_spilling (cfg, tmp, ins, rs->isymbolic [X86_EDX]);
1691                                 mono_regstate_free_int (rs, X86_EDX);
1692                         }
1693                 }
1694
1695                 /* Track dreg */
1696                 if (spec [MONO_INST_DEST] == 'f') {
1697                         if (reginfof [ins->dreg].flags & MONO_X86_FP_NEEDS_SPILL) {
1698                                 GList *spill_node;
1699                                 MonoInst *store;
1700                                 spill_node = g_list_first (fspill_list);
1701                                 g_assert (spill_node);
1702
1703                                 store = create_spilled_store_float (cfg, GPOINTER_TO_INT (spill_node->data), ins->dreg, ins);
1704                                 insert_before_ins (ins, tmp, store);
1705                                 fspill_list = g_list_remove (fspill_list, spill_node->data);
1706                                 fspill--;
1707                         }
1708                 } else if (spec [MONO_INST_DEST] == 'L') {
1709                         int hreg;
1710                         val = rs->iassign [ins->dreg];
1711                         /* check special case when dreg have been moved from ecx (clob shift) */
1712                         if (spec [MONO_INST_CLOB] == 's' && clob_dreg != -1)
1713                                 hreg = clob_dreg + 1;
1714                         else
1715                                 hreg = ins->dreg + 1;
1716
1717                         /* base prev_dreg on fixed hreg, handle clob case */
1718                         prev_dreg = hreg - 1;
1719
1720                         if (val < 0) {
1721                                 int spill = 0;
1722                                 if (val < -1) {
1723                                         /* the register gets spilled after this inst */
1724                                         spill = -val -1;
1725                                 }
1726                                 val = mono_x86_alloc_int_reg (cfg, tmp, ins, dest_mask, ins->dreg, reginfo [ins->dreg].flags);
1727                                 rs->iassign [ins->dreg] = val;
1728                                 if (spill)
1729                                         create_spilled_store (cfg, spill, val, prev_dreg, ins);
1730                         }
1731
1732                         DEBUG (g_print ("\tassigned dreg (long) %s to dest R%d\n", mono_arch_regname (val), hreg - 1));
1733  
1734                         rs->isymbolic [val] = hreg - 1;
1735                         ins->dreg = val;
1736                         
1737                         val = rs->iassign [hreg];
1738                         if (val < 0) {
1739                                 int spill = 0;
1740                                 if (val < -1) {
1741                                         /* the register gets spilled after this inst */
1742                                         spill = -val -1;
1743                                 }
1744                                 val = mono_x86_alloc_int_reg (cfg, tmp, ins, dest_mask, hreg, reginfo [hreg].flags);
1745                                 rs->iassign [hreg] = val;
1746                                 if (spill)
1747                                         create_spilled_store (cfg, spill, val, hreg, ins);
1748                         }
1749
1750                         DEBUG (g_print ("\tassigned hreg (long-high) %s to dest R%d\n", mono_arch_regname (val), hreg));
1751                         rs->isymbolic [val] = hreg;
1752                         /* save reg allocating into unused */
1753                         ins->unused = val;
1754
1755                         /* check if we can free our long reg */
1756                         if (reg_is_freeable (val) && hreg >= 0 && reginfo [hreg].born_in >= i) {
1757                                 DEBUG (g_print ("\tfreeable %s (R%d) (born in %d)\n", mono_arch_regname (val), hreg, reginfo [hreg].born_in));
1758                                 mono_regstate_free_int (rs, val);
1759                         }
1760                 }
1761                 else if (ins->dreg >= MONO_MAX_IREGS) {
1762                         int hreg;
1763                         val = rs->iassign [ins->dreg];
1764                         if (spec [MONO_INST_DEST] == 'l') {
1765                                 /* check special case when dreg have been moved from ecx (clob shift) */
1766                                 if (spec [MONO_INST_CLOB] == 's' && clob_dreg != -1)
1767                                         hreg = clob_dreg + 1;
1768                                 else
1769                                         hreg = ins->dreg + 1;
1770
1771                                 /* base prev_dreg on fixed hreg, handle clob case */
1772                                 prev_dreg = hreg - 1;
1773                         } else
1774                                 prev_dreg = ins->dreg;
1775
1776                         if (val < 0) {
1777                                 int spill = 0;
1778                                 if (val < -1) {
1779                                         /* the register gets spilled after this inst */
1780                                         spill = -val -1;
1781                                 }
1782                                 val = mono_x86_alloc_int_reg (cfg, tmp, ins, dest_mask, ins->dreg, reginfo [ins->dreg].flags);
1783                                 rs->iassign [ins->dreg] = val;
1784                                 if (spill)
1785                                         create_spilled_store (cfg, spill, val, prev_dreg, ins);
1786                         }
1787                         DEBUG (g_print ("\tassigned dreg %s to dest R%d\n", mono_arch_regname (val), ins->dreg));
1788                         rs->isymbolic [val] = prev_dreg;
1789                         ins->dreg = val;
1790                         /* handle cases where lreg needs to be eax:edx */
1791                         if (spec [MONO_INST_DEST] == 'l') {
1792                                 /* check special case when dreg have been moved from ecx (clob shift) */
1793                                 int hreg = prev_dreg + 1;
1794                                 val = rs->iassign [hreg];
1795                                 if (val < 0) {
1796                                         int spill = 0;
1797                                         if (val < -1) {
1798                                                 /* the register gets spilled after this inst */
1799                                                 spill = -val -1;
1800                                         }
1801                                         val = mono_x86_alloc_int_reg (cfg, tmp, ins, dest_mask, hreg, reginfo [hreg].flags);
1802                                         rs->iassign [hreg] = val;
1803                                         if (spill)
1804                                                 create_spilled_store (cfg, spill, val, hreg, ins);
1805                                 }
1806                                 DEBUG (g_print ("\tassigned hreg %s to dest R%d\n", mono_arch_regname (val), hreg));
1807                                 rs->isymbolic [val] = hreg;
1808                                 if (ins->dreg == X86_EAX) {
1809                                         if (val != X86_EDX)
1810                                                 create_copy_ins (cfg, val, X86_EDX, ins);
1811                                 } else if (ins->dreg == X86_EDX) {
1812                                         if (val == X86_EAX) {
1813                                                 /* swap */
1814                                                 g_assert_not_reached ();
1815                                         } else {
1816                                                 /* two forced copies */
1817                                                 create_copy_ins (cfg, val, X86_EDX, ins);
1818                                                 create_copy_ins (cfg, ins->dreg, X86_EAX, ins);
1819                                         }
1820                                 } else {
1821                                         if (val == X86_EDX) {
1822                                                 create_copy_ins (cfg, ins->dreg, X86_EAX, ins);
1823                                         } else {
1824                                                 /* two forced copies */
1825                                                 create_copy_ins (cfg, val, X86_EDX, ins);
1826                                                 create_copy_ins (cfg, ins->dreg, X86_EAX, ins);
1827                                         }
1828                                 }
1829                                 if (reg_is_freeable (val) && hreg >= 0 && reginfo [hreg].born_in >= i) {
1830                                         DEBUG (g_print ("\tfreeable %s (R%d)\n", mono_arch_regname (val), hreg));
1831                                         mono_regstate_free_int (rs, val);
1832                                 }
1833                         } else if (spec [MONO_INST_DEST] == 'a' && ins->dreg != X86_EAX && spec [MONO_INST_CLOB] != 'd') {
1834                                 /* this instruction only outputs to EAX, need to copy */
1835                                 create_copy_ins (cfg, ins->dreg, X86_EAX, ins);
1836                         } else if (spec [MONO_INST_DEST] == 'd' && ins->dreg != X86_EDX && spec [MONO_INST_CLOB] != 'd') {
1837                                 create_copy_ins (cfg, ins->dreg, X86_EDX, ins);
1838                         }
1839                 }
1840                 if (spec [MONO_INST_DEST] != 'f' && reg_is_freeable (ins->dreg) && prev_dreg >= 0 && reginfo [prev_dreg].born_in >= i) {
1841                         DEBUG (g_print ("\tfreeable %s (R%d) (born in %d)\n", mono_arch_regname (ins->dreg), prev_dreg, reginfo [prev_dreg].born_in));
1842                         mono_regstate_free_int (rs, ins->dreg);
1843                 }
1844                 /* put src1 in EAX if it needs to be */
1845                 if (spec [MONO_INST_SRC1] == 'a') {
1846                         if (!(rs->ifree_mask & (1 << X86_EAX))) {
1847                                 DEBUG (g_print ("\tforced spill of R%d\n", rs->isymbolic [X86_EAX]));
1848                                 get_register_force_spilling (cfg, tmp, ins, rs->isymbolic [X86_EAX]);
1849                                 mono_regstate_free_int (rs, X86_EAX);
1850                         }
1851                         /* force-set sreg1 */
1852                         rs->iassign [ins->sreg1] = X86_EAX;
1853                         rs->isymbolic [X86_EAX] = ins->sreg1;
1854                         ins->sreg1 = X86_EAX;
1855                         rs->ifree_mask &= ~ (1 << X86_EAX);
1856                 }
1857
1858                 /* Track sreg1 */
1859                 if (spec [MONO_INST_SRC1] == 'f') {
1860                         if (reginfof [ins->sreg1].flags & MONO_X86_FP_NEEDS_LOAD) {
1861                                 MonoInst *load;
1862                                 MonoInst *store = NULL;
1863
1864                                 if (reginfof [ins->sreg1].flags & MONO_X86_FP_NEEDS_LOAD_SPILL) {
1865                                         GList *spill_node;
1866                                         spill_node = g_list_first (fspill_list);
1867                                         g_assert (spill_node);
1868
1869                                         store = create_spilled_store_float (cfg, GPOINTER_TO_INT (spill_node->data), ins->sreg1, ins);          
1870                                         fspill_list = g_list_remove (fspill_list, spill_node->data);
1871                                 }
1872
1873                                 fspill++;
1874                                 fspill_list = g_list_prepend (fspill_list, GINT_TO_POINTER(fspill));
1875                                 load = create_spilled_load_float (cfg, fspill, ins->sreg1, ins);
1876                                 insert_before_ins (ins, tmp, load);
1877                                 if (store) 
1878                                         insert_before_ins (load, tmp, store);
1879                         }
1880                 } else if ((spec [MONO_INST_DEST] == 'L') && (spec [MONO_INST_SRC1] == 'L')) {
1881                         /* force source to be same as dest */
1882                         rs->iassign [ins->sreg1] = ins->dreg;
1883                         rs->iassign [ins->sreg1 + 1] = ins->unused;
1884                         rs->isymbolic [ins->dreg] = ins->sreg1;
1885                         rs->isymbolic [ins->unused] = ins->sreg1 + 1;
1886
1887                         DEBUG (g_print ("\tassigned sreg1 (long) %s to sreg1 R%d\n", mono_arch_regname (ins->dreg), ins->sreg1));
1888                         DEBUG (g_print ("\tassigned sreg1 (long-high) %s to sreg1 R%d\n", mono_arch_regname (ins->unused), ins->sreg1 + 1));
1889
1890                         ins->sreg1 = ins->dreg;
1891                         /* 
1892                          * No need for saving the reg, we know that src1=dest in this cases
1893                          * ins->inst_c0 = ins->unused;
1894                          */
1895
1896                         /* make sure that we remove them from free mask */
1897                         rs->ifree_mask &= ~ (1 << ins->dreg);
1898                         rs->ifree_mask &= ~ (1 << ins->unused);
1899                 }
1900                 else if (ins->sreg1 >= MONO_MAX_IREGS) {
1901                         val = rs->iassign [ins->sreg1];
1902                         prev_sreg1 = ins->sreg1;
1903                         if (val < 0) {
1904                                 int spill = 0;
1905                                 if (val < -1) {
1906                                         /* the register gets spilled after this inst */
1907                                         spill = -val -1;
1908                                 }
1909                                 if (0 && ins->opcode == OP_MOVE) {
1910                                         /* 
1911                                          * small optimization: the dest register is already allocated
1912                                          * but the src one is not: we can simply assign the same register
1913                                          * here and peephole will get rid of the instruction later.
1914                                          * This optimization may interfere with the clobbering handling:
1915                                          * it removes a mov operation that will be added again to handle clobbering.
1916                                          * There are also some other issues that should with make testjit.
1917                                          */
1918                                         mono_regstate_alloc_int (rs, 1 << ins->dreg);
1919                                         val = rs->iassign [ins->sreg1] = ins->dreg;
1920                                         //g_assert (val >= 0);
1921                                         DEBUG (g_print ("\tfast assigned sreg1 %s to R%d\n", mono_arch_regname (val), ins->sreg1));
1922                                 } else {
1923                                         //g_assert (val == -1); /* source cannot be spilled */
1924                                         val = mono_x86_alloc_int_reg (cfg, tmp, ins, src1_mask, ins->sreg1, reginfo [ins->sreg1].flags);
1925                                         rs->iassign [ins->sreg1] = val;
1926                                         DEBUG (g_print ("\tassigned sreg1 %s to R%d\n", mono_arch_regname (val), ins->sreg1));
1927                                 }
1928                                 if (spill) {
1929                                         MonoInst *store = create_spilled_store (cfg, spill, val, prev_sreg1, NULL);
1930                                         insert_before_ins (ins, tmp, store);
1931                                 }
1932                         }
1933                         rs->isymbolic [val] = prev_sreg1;
1934                         ins->sreg1 = val;
1935                 } else {
1936                         prev_sreg1 = -1;
1937                 }
1938                 /* handle clobbering of sreg1 */
1939                 if ((spec [MONO_INST_CLOB] == '1' || spec [MONO_INST_CLOB] == 's') && ins->dreg != ins->sreg1) {
1940                         MonoInst *copy = create_copy_ins (cfg, ins->dreg, ins->sreg1, NULL);
1941                         DEBUG (g_print ("\tneed to copy sreg1 %s to dreg %s\n", mono_arch_regname (ins->sreg1), mono_arch_regname (ins->dreg)));
1942                         if (ins->sreg2 == -1 || spec [MONO_INST_CLOB] == 's') {
1943                                 /* note: the copy is inserted before the current instruction! */
1944                                 insert_before_ins (ins, tmp, copy);
1945                                 /* we set sreg1 to dest as well */
1946                                 prev_sreg1 = ins->sreg1 = ins->dreg;
1947                         } else {
1948                                 /* inserted after the operation */
1949                                 copy->next = ins->next;
1950                                 ins->next = copy;
1951                         }
1952                 }
1953                 /* track sreg2 */
1954                 if (spec [MONO_INST_SRC2] == 'f') {
1955                         if (reginfof [ins->sreg2].flags & MONO_X86_FP_NEEDS_LOAD) {
1956                                 MonoInst *load;
1957                                 MonoInst *store = NULL;
1958
1959                                 if (reginfof [ins->sreg2].flags & MONO_X86_FP_NEEDS_LOAD_SPILL) {
1960                                         GList *spill_node;
1961
1962                                         spill_node = g_list_first (fspill_list);
1963                                         g_assert (spill_node);
1964                                         if (spec [MONO_INST_SRC1] == 'f' && (reginfof [ins->sreg1].flags & MONO_X86_FP_NEEDS_LOAD_SPILL))
1965                                                 spill_node = g_list_next (spill_node);
1966         
1967                                         store = create_spilled_store_float (cfg, GPOINTER_TO_INT (spill_node->data), ins->sreg2, ins);
1968                                         fspill_list = g_list_remove (fspill_list, spill_node->data);
1969                                 } 
1970                                 
1971                                 fspill++;
1972                                 fspill_list = g_list_prepend (fspill_list, GINT_TO_POINTER(fspill));
1973                                 load = create_spilled_load_float (cfg, fspill, ins->sreg2, ins);
1974                                 insert_before_ins (ins, tmp, load);
1975                                 if (store) 
1976                                         insert_before_ins (load, tmp, store);
1977                         }
1978                 } 
1979                 else if (ins->sreg2 >= MONO_MAX_IREGS) {
1980                         val = rs->iassign [ins->sreg2];
1981                         prev_sreg2 = ins->sreg2;
1982                         if (val < 0) {
1983                                 int spill = 0;
1984                                 if (val < -1) {
1985                                         /* the register gets spilled after this inst */
1986                                         spill = -val -1;
1987                                 }
1988                                 val = mono_x86_alloc_int_reg (cfg, tmp, ins, src2_mask, ins->sreg2, reginfo [ins->sreg2].flags);
1989                                 rs->iassign [ins->sreg2] = val;
1990                                 DEBUG (g_print ("\tassigned sreg2 %s to R%d\n", mono_arch_regname (val), ins->sreg2));
1991                                 if (spill)
1992                                         create_spilled_store (cfg, spill, val, prev_sreg2, ins);
1993                         }
1994                         rs->isymbolic [val] = prev_sreg2;
1995                         ins->sreg2 = val;
1996                         if (spec [MONO_INST_CLOB] == 's' && ins->sreg2 != X86_ECX) {
1997                                 DEBUG (g_print ("\tassigned sreg2 %s to R%d, but ECX is needed (R%d)\n", mono_arch_regname (val), ins->sreg2, rs->iassign [X86_ECX]));
1998                         }
1999                 } else {
2000                         prev_sreg2 = -1;
2001                 }
2002
2003                 if (spec [MONO_INST_CLOB] == 'c') {
2004                         int j, s;
2005                         guint32 clob_mask = X86_CALLEE_REGS;
2006                         for (j = 0; j < MONO_MAX_IREGS; ++j) {
2007                                 s = 1 << j;
2008                                 if ((clob_mask & s) && !(rs->ifree_mask & s) && j != ins->sreg1) {
2009                                         //g_warning ("register %s busy at call site\n", mono_arch_regname (j));
2010                                 }
2011                         }
2012                 }
2013                 /*if (reg_is_freeable (ins->sreg1) && prev_sreg1 >= 0 && reginfo [prev_sreg1].born_in >= i) {
2014                         DEBUG (g_print ("freeable %s\n", mono_arch_regname (ins->sreg1)));
2015                         mono_regstate_free_int (rs, ins->sreg1);
2016                 }
2017                 if (reg_is_freeable (ins->sreg2) && prev_sreg2 >= 0 && reginfo [prev_sreg2].born_in >= i) {
2018                         DEBUG (g_print ("freeable %s\n", mono_arch_regname (ins->sreg2)));
2019                         mono_regstate_free_int (rs, ins->sreg2);
2020                 }*/
2021         
2022                 //DEBUG (print_ins (i, ins));
2023                 /* this may result from a insert_before call */
2024                 if (!tmp->next)
2025                         bb->code = tmp->data;
2026                 tmp = tmp->next;
2027         }
2028
2029         g_free (reginfo);
2030         g_free (reginfof);
2031         g_list_free (fspill_list);
2032 }
2033
2034 static unsigned char*
2035 emit_float_to_int (MonoCompile *cfg, guchar *code, int dreg, int size, gboolean is_signed)
2036 {
2037         x86_alu_reg_imm (code, X86_SUB, X86_ESP, 4);
2038         x86_fnstcw_membase(code, X86_ESP, 0);
2039         x86_mov_reg_membase (code, dreg, X86_ESP, 0, 2);
2040         x86_alu_reg_imm (code, X86_OR, dreg, 0xc00);
2041         x86_mov_membase_reg (code, X86_ESP, 2, dreg, 2);
2042         x86_fldcw_membase (code, X86_ESP, 2);
2043         if (size == 8) {
2044                 x86_alu_reg_imm (code, X86_SUB, X86_ESP, 8);
2045                 x86_fist_pop_membase (code, X86_ESP, 0, TRUE);
2046                 x86_pop_reg (code, dreg);
2047                 /* FIXME: need the high register 
2048                  * x86_pop_reg (code, dreg_high);
2049                  */
2050         } else {
2051                 x86_push_reg (code, X86_EAX); // SP = SP - 4
2052                 x86_fist_pop_membase (code, X86_ESP, 0, FALSE);
2053                 x86_pop_reg (code, dreg);
2054         }
2055         x86_fldcw_membase (code, X86_ESP, 0);
2056         x86_alu_reg_imm (code, X86_ADD, X86_ESP, 4);
2057
2058         if (size == 1)
2059                 x86_widen_reg (code, dreg, dreg, is_signed, FALSE);
2060         else if (size == 2)
2061                 x86_widen_reg (code, dreg, dreg, is_signed, TRUE);
2062         return code;
2063 }
2064
2065 static unsigned char*
2066 mono_emit_stack_alloc (guchar *code, MonoInst* tree)
2067 {
2068         int sreg = tree->sreg1;
2069 #ifdef PLATFORM_WIN32
2070         guint8* br[5];
2071
2072         /*
2073          * Under Windows:
2074          * If requested stack size is larger than one page,
2075          * perform stack-touch operation
2076          */
2077         /*
2078          * Generate stack probe code.
2079          * Under Windows, it is necessary to allocate one page at a time,
2080          * "touching" stack after each successful sub-allocation. This is
2081          * because of the way stack growth is implemented - there is a
2082          * guard page before the lowest stack page that is currently commited.
2083          * Stack normally grows sequentially so OS traps access to the
2084          * guard page and commits more pages when needed.
2085          */
2086         x86_test_reg_imm (code, sreg, ~0xFFF);
2087         br[0] = code; x86_branch8 (code, X86_CC_Z, 0, FALSE);
2088
2089         br[2] = code; /* loop */
2090         x86_alu_reg_imm (code, X86_SUB, X86_ESP, 0x1000);
2091         x86_test_membase_reg (code, X86_ESP, 0, X86_ESP);
2092         x86_alu_reg_imm (code, X86_SUB, sreg, 0x1000);
2093         x86_alu_reg_imm (code, X86_CMP, sreg, 0x1000);
2094         br[3] = code; x86_branch8 (code, X86_CC_AE, 0, FALSE);
2095         x86_patch (br[3], br[2]);
2096         x86_test_reg_reg (code, sreg, sreg);
2097         br[4] = code; x86_branch8 (code, X86_CC_Z, 0, FALSE);
2098         x86_alu_reg_reg (code, X86_SUB, X86_ESP, sreg);
2099
2100         br[1] = code; x86_jump8 (code, 0);
2101
2102         x86_patch (br[0], code);
2103         x86_alu_reg_reg (code, X86_SUB, X86_ESP, sreg);
2104         x86_patch (br[1], code);
2105         x86_patch (br[4], code);
2106 #else /* PLATFORM_WIN32 */
2107         x86_alu_reg_reg (code, X86_SUB, X86_ESP, tree->sreg1);
2108 #endif
2109         if (tree->flags & MONO_INST_INIT) {
2110                 int offset = 0;
2111                 if (tree->dreg != X86_EAX && sreg != X86_EAX) {
2112                         x86_push_reg (code, X86_EAX);
2113                         offset += 4;
2114                 }
2115                 if (tree->dreg != X86_ECX && sreg != X86_ECX) {
2116                         x86_push_reg (code, X86_ECX);
2117                         offset += 4;
2118                 }
2119                 if (tree->dreg != X86_EDI && sreg != X86_EDI) {
2120                         x86_push_reg (code, X86_EDI);
2121                         offset += 4;
2122                 }
2123                 
2124                 x86_shift_reg_imm (code, X86_SHR, sreg, 2);
2125                 if (sreg != X86_ECX)
2126                         x86_mov_reg_reg (code, X86_ECX, sreg, 4);
2127                 x86_alu_reg_reg (code, X86_XOR, X86_EAX, X86_EAX);
2128                                 
2129                 x86_lea_membase (code, X86_EDI, X86_ESP, offset);
2130                 x86_cld (code);
2131                 x86_prefix (code, X86_REP_PREFIX);
2132                 x86_stosl (code);
2133                 
2134                 if (tree->dreg != X86_EDI && sreg != X86_EDI)
2135                         x86_pop_reg (code, X86_EDI);
2136                 if (tree->dreg != X86_ECX && sreg != X86_ECX)
2137                         x86_pop_reg (code, X86_ECX);
2138                 if (tree->dreg != X86_EAX && sreg != X86_EAX)
2139                         x86_pop_reg (code, X86_EAX);
2140         }
2141         return code;
2142 }
2143
2144 #define REAL_PRINT_REG(text,reg) \
2145 mono_assert (reg >= 0); \
2146 x86_push_reg (code, X86_EAX); \
2147 x86_push_reg (code, X86_EDX); \
2148 x86_push_reg (code, X86_ECX); \
2149 x86_push_reg (code, reg); \
2150 x86_push_imm (code, reg); \
2151 x86_push_imm (code, text " %d %p\n"); \
2152 x86_mov_reg_imm (code, X86_EAX, printf); \
2153 x86_call_reg (code, X86_EAX); \
2154 x86_alu_reg_imm (code, X86_ADD, X86_ESP, 3*4); \
2155 x86_pop_reg (code, X86_ECX); \
2156 x86_pop_reg (code, X86_EDX); \
2157 x86_pop_reg (code, X86_EAX);
2158
2159 /* benchmark and set based on cpu */
2160 #define LOOP_ALIGNMENT 8
2161 #define bb_is_loop_start(bb) ((bb)->loop_body_start && (bb)->nesting)
2162
2163 void
2164 mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb)
2165 {
2166         MonoInst *ins;
2167         MonoCallInst *call;
2168         guint offset;
2169         guint8 *code = cfg->native_code + cfg->code_len;
2170         MonoInst *last_ins = NULL;
2171         guint last_offset = 0;
2172         int max_len, cpos;
2173
2174         if (cfg->opt & MONO_OPT_PEEPHOLE)
2175                 peephole_pass (cfg, bb);
2176
2177         if (cfg->opt & MONO_OPT_LOOP) {
2178                 int pad, align = LOOP_ALIGNMENT;
2179                 /* set alignment depending on cpu */
2180                 if (bb_is_loop_start (bb) && (pad = (cfg->code_len & (align - 1)))) {
2181                         pad = align - pad;
2182                         /*g_print ("adding %d pad at %x to loop in %s\n", pad, cfg->code_len, cfg->method->name);*/
2183                         x86_padding (code, pad);
2184                         cfg->code_len += pad;
2185                         bb->native_offset = cfg->code_len;
2186                 }
2187         }
2188
2189         if (cfg->verbose_level > 2)
2190                 g_print ("Basic block %d starting at offset 0x%x\n", bb->block_num, bb->native_offset);
2191
2192         cpos = bb->max_offset;
2193
2194         if (cfg->prof_options & MONO_PROFILE_COVERAGE) {
2195                 MonoProfileCoverageInfo *cov = cfg->coverage_info;
2196                 g_assert (!mono_compile_aot);
2197                 cpos += 6;
2198
2199                 cov->data [bb->dfn].cil_code = bb->cil_code;
2200                 /* this is not thread save, but good enough */
2201                 x86_inc_mem (code, &cov->data [bb->dfn].count); 
2202         }
2203
2204         offset = code - cfg->native_code;
2205
2206         ins = bb->code;
2207         while (ins) {
2208                 offset = code - cfg->native_code;
2209
2210                 max_len = ((guint8 *)ins_spec [ins->opcode])[MONO_INST_LEN];
2211
2212                 if (offset > (cfg->code_size - max_len - 16)) {
2213                         cfg->code_size *= 2;
2214                         cfg->native_code = g_realloc (cfg->native_code, cfg->code_size);
2215                         code = cfg->native_code + offset;
2216                         mono_jit_stats.code_reallocs++;
2217                 }
2218
2219                 mono_debug_record_line_number (cfg, ins, offset);
2220
2221                 switch (ins->opcode) {
2222                 case OP_BIGMUL:
2223                         x86_mul_reg (code, ins->sreg2, TRUE);
2224                         break;
2225                 case OP_BIGMUL_UN:
2226                         x86_mul_reg (code, ins->sreg2, FALSE);
2227                         break;
2228                 case OP_X86_SETEQ_MEMBASE:
2229                 case OP_X86_SETNE_MEMBASE:
2230                         x86_set_membase (code, ins->opcode == OP_X86_SETEQ_MEMBASE ? X86_CC_EQ : X86_CC_NE,
2231                                          ins->inst_basereg, ins->inst_offset, TRUE);
2232                         break;
2233                 case OP_STOREI1_MEMBASE_IMM:
2234                         x86_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 1);
2235                         break;
2236                 case OP_STOREI2_MEMBASE_IMM:
2237                         x86_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 2);
2238                         break;
2239                 case OP_STORE_MEMBASE_IMM:
2240                 case OP_STOREI4_MEMBASE_IMM:
2241                         x86_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 4);
2242                         break;
2243                 case OP_STOREI1_MEMBASE_REG:
2244                         x86_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 1);
2245                         break;
2246                 case OP_STOREI2_MEMBASE_REG:
2247                         x86_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 2);
2248                         break;
2249                 case OP_STORE_MEMBASE_REG:
2250                 case OP_STOREI4_MEMBASE_REG:
2251                         x86_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 4);
2252                         break;
2253                 case CEE_LDIND_I:
2254                 case CEE_LDIND_I4:
2255                 case CEE_LDIND_U4:
2256                         x86_mov_reg_mem (code, ins->dreg, ins->inst_p0, 4);
2257                         break;
2258                 case OP_LOADU4_MEM:
2259                         x86_mov_reg_imm (code, ins->dreg, ins->inst_p0);
2260                         x86_mov_reg_membase (code, ins->dreg, ins->dreg, 0, 4);
2261                         break;
2262                 case OP_LOAD_MEMBASE:
2263                 case OP_LOADI4_MEMBASE:
2264                 case OP_LOADU4_MEMBASE:
2265                         x86_mov_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, 4);
2266                         break;
2267                 case OP_LOADU1_MEMBASE:
2268                         x86_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, FALSE, FALSE);
2269                         break;
2270                 case OP_LOADI1_MEMBASE:
2271                         x86_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, TRUE, FALSE);
2272                         break;
2273                 case OP_LOADU2_MEMBASE:
2274                         x86_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, FALSE, TRUE);
2275                         break;
2276                 case OP_LOADI2_MEMBASE:
2277                         x86_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, TRUE, TRUE);
2278                         break;
2279                 case CEE_CONV_I1:
2280                         x86_widen_reg (code, ins->dreg, ins->sreg1, TRUE, FALSE);
2281                         break;
2282                 case CEE_CONV_I2:
2283                         x86_widen_reg (code, ins->dreg, ins->sreg1, TRUE, TRUE);
2284                         break;
2285                 case CEE_CONV_U1:
2286                         x86_widen_reg (code, ins->dreg, ins->sreg1, FALSE, FALSE);
2287                         break;
2288                 case CEE_CONV_U2:
2289                         x86_widen_reg (code, ins->dreg, ins->sreg1, FALSE, TRUE);
2290                         break;
2291                 case OP_COMPARE:
2292                         x86_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2);
2293                         break;
2294                 case OP_COMPARE_IMM:
2295                         x86_alu_reg_imm (code, X86_CMP, ins->sreg1, ins->inst_imm);
2296                         break;
2297                 case OP_X86_COMPARE_MEMBASE_REG:
2298                         x86_alu_membase_reg (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->sreg2);
2299                         break;
2300                 case OP_X86_COMPARE_MEMBASE_IMM:
2301                         x86_alu_membase_imm (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->inst_imm);
2302                         break;
2303                 case OP_X86_COMPARE_MEMBASE8_IMM:
2304                         x86_alu_membase8_imm (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->inst_imm);
2305                         break;
2306                 case OP_X86_COMPARE_REG_MEMBASE:
2307                         x86_alu_reg_membase (code, X86_CMP, ins->sreg1, ins->sreg2, ins->inst_offset);
2308                         break;
2309                 case OP_X86_TEST_NULL:
2310                         x86_test_reg_reg (code, ins->sreg1, ins->sreg1);
2311                         break;
2312                 case OP_X86_ADD_MEMBASE_IMM:
2313                         x86_alu_membase_imm (code, X86_ADD, ins->inst_basereg, ins->inst_offset, ins->inst_imm);
2314                         break;
2315                 case OP_X86_ADD_MEMBASE:
2316                         x86_alu_reg_membase (code, X86_ADD, ins->sreg1, ins->sreg2, ins->inst_offset);
2317                         break;
2318                 case OP_X86_SUB_MEMBASE_IMM:
2319                         x86_alu_membase_imm (code, X86_SUB, ins->inst_basereg, ins->inst_offset, ins->inst_imm);
2320                         break;
2321                 case OP_X86_SUB_MEMBASE:
2322                         x86_alu_reg_membase (code, X86_SUB, ins->sreg1, ins->sreg2, ins->inst_offset);
2323                         break;
2324                 case OP_X86_INC_MEMBASE:
2325                         x86_inc_membase (code, ins->inst_basereg, ins->inst_offset);
2326                         break;
2327                 case OP_X86_INC_REG:
2328                         x86_inc_reg (code, ins->dreg);
2329                         break;
2330                 case OP_X86_DEC_MEMBASE:
2331                         x86_dec_membase (code, ins->inst_basereg, ins->inst_offset);
2332                         break;
2333                 case OP_X86_DEC_REG:
2334                         x86_dec_reg (code, ins->dreg);
2335                         break;
2336                 case OP_X86_MUL_MEMBASE:
2337                         x86_imul_reg_membase (code, ins->sreg1, ins->sreg2, ins->inst_offset);
2338                         break;
2339                 case CEE_BREAK:
2340                         x86_breakpoint (code);
2341                         break;
2342                 case OP_ADDCC:
2343                 case CEE_ADD:
2344                         x86_alu_reg_reg (code, X86_ADD, ins->sreg1, ins->sreg2);
2345                         break;
2346                 case OP_ADC:
2347                         x86_alu_reg_reg (code, X86_ADC, ins->sreg1, ins->sreg2);
2348                         break;
2349                 case OP_ADDCC_IMM:
2350                 case OP_ADD_IMM:
2351                         x86_alu_reg_imm (code, X86_ADD, ins->dreg, ins->inst_imm);
2352                         break;
2353                 case OP_ADC_IMM:
2354                         x86_alu_reg_imm (code, X86_ADC, ins->dreg, ins->inst_imm);
2355                         break;
2356                 case OP_SUBCC:
2357                 case CEE_SUB:
2358                         x86_alu_reg_reg (code, X86_SUB, ins->sreg1, ins->sreg2);
2359                         break;
2360                 case OP_SBB:
2361                         x86_alu_reg_reg (code, X86_SBB, ins->sreg1, ins->sreg2);
2362                         break;
2363                 case OP_SUBCC_IMM:
2364                 case OP_SUB_IMM:
2365                         x86_alu_reg_imm (code, X86_SUB, ins->dreg, ins->inst_imm);
2366                         break;
2367                 case OP_SBB_IMM:
2368                         x86_alu_reg_imm (code, X86_SBB, ins->dreg, ins->inst_imm);
2369                         break;
2370                 case CEE_AND:
2371                         x86_alu_reg_reg (code, X86_AND, ins->sreg1, ins->sreg2);
2372                         break;
2373                 case OP_AND_IMM:
2374                         x86_alu_reg_imm (code, X86_AND, ins->sreg1, ins->inst_imm);
2375                         break;
2376                 case CEE_DIV:
2377                         x86_cdq (code);
2378                         x86_div_reg (code, ins->sreg2, TRUE);
2379                         break;
2380                 case CEE_DIV_UN:
2381                         x86_alu_reg_reg (code, X86_XOR, X86_EDX, X86_EDX);
2382                         x86_div_reg (code, ins->sreg2, FALSE);
2383                         break;
2384                 case OP_DIV_IMM:
2385                         x86_mov_reg_imm (code, ins->sreg2, ins->inst_imm);
2386                         x86_cdq (code);
2387                         x86_div_reg (code, ins->sreg2, TRUE);
2388                         break;
2389                 case CEE_REM:
2390                         x86_cdq (code);
2391                         x86_div_reg (code, ins->sreg2, TRUE);
2392                         break;
2393                 case CEE_REM_UN:
2394                         x86_alu_reg_reg (code, X86_XOR, X86_EDX, X86_EDX);
2395                         x86_div_reg (code, ins->sreg2, FALSE);
2396                         break;
2397                 case OP_REM_IMM:
2398                         x86_mov_reg_imm (code, ins->sreg2, ins->inst_imm);
2399                         x86_cdq (code);
2400                         x86_div_reg (code, ins->sreg2, TRUE);
2401                         break;
2402                 case CEE_OR:
2403                         x86_alu_reg_reg (code, X86_OR, ins->sreg1, ins->sreg2);
2404                         break;
2405                 case OP_OR_IMM:
2406                         x86_alu_reg_imm (code, X86_OR, ins->sreg1, ins->inst_imm);
2407                         break;
2408                 case CEE_XOR:
2409                         x86_alu_reg_reg (code, X86_XOR, ins->sreg1, ins->sreg2);
2410                         break;
2411                 case OP_XOR_IMM:
2412                         x86_alu_reg_imm (code, X86_XOR, ins->sreg1, ins->inst_imm);
2413                         break;
2414                 case CEE_SHL:
2415                         g_assert (ins->sreg2 == X86_ECX);
2416                         x86_shift_reg (code, X86_SHL, ins->dreg);
2417                         break;
2418                 case CEE_SHR:
2419                         g_assert (ins->sreg2 == X86_ECX);
2420                         x86_shift_reg (code, X86_SAR, ins->dreg);
2421                         break;
2422                 case OP_SHR_IMM:
2423                         x86_shift_reg_imm (code, X86_SAR, ins->dreg, ins->inst_imm);
2424                         break;
2425                 case OP_SHR_UN_IMM:
2426                         x86_shift_reg_imm (code, X86_SHR, ins->dreg, ins->inst_imm);
2427                         break;
2428                 case CEE_SHR_UN:
2429                         g_assert (ins->sreg2 == X86_ECX);
2430                         x86_shift_reg (code, X86_SHR, ins->dreg);
2431                         break;
2432                 case OP_SHL_IMM:
2433                         x86_shift_reg_imm (code, X86_SHL, ins->dreg, ins->inst_imm);
2434                         break;
2435                 case OP_LSHL: {
2436                         guint8 *jump_to_end;
2437
2438                         /* handle shifts below 32 bits */
2439                         x86_shld_reg (code, ins->unused, ins->sreg1);
2440                         x86_shift_reg (code, X86_SHL, ins->sreg1);
2441
2442                         x86_test_reg_imm (code, X86_ECX, 32);
2443                         jump_to_end = code; x86_branch8 (code, X86_CC_EQ, 0, TRUE);
2444
2445                         /* handle shift over 32 bit */
2446                         x86_mov_reg_reg (code, ins->unused, ins->sreg1, 4);
2447                         x86_clear_reg (code, ins->sreg1);
2448                         
2449                         x86_patch (jump_to_end, code);
2450                         }
2451                         break;
2452                 case OP_LSHR: {
2453                         guint8 *jump_to_end;
2454
2455                         /* handle shifts below 32 bits */
2456                         x86_shrd_reg (code, ins->sreg1, ins->unused);
2457                         x86_shift_reg (code, X86_SAR, ins->unused);
2458
2459                         x86_test_reg_imm (code, X86_ECX, 32);
2460                         jump_to_end = code; x86_branch8 (code, X86_CC_EQ, 0, FALSE);
2461
2462                         /* handle shifts over 31 bits */
2463                         x86_mov_reg_reg (code, ins->sreg1, ins->unused, 4);
2464                         x86_shift_reg_imm (code, X86_SAR, ins->unused, 31);
2465                         
2466                         x86_patch (jump_to_end, code);
2467                         }
2468                         break;
2469                 case OP_LSHR_UN: {
2470                         guint8 *jump_to_end;
2471
2472                         /* handle shifts below 32 bits */
2473                         x86_shrd_reg (code, ins->sreg1, ins->unused);
2474                         x86_shift_reg (code, X86_SHR, ins->unused);
2475
2476                         x86_test_reg_imm (code, X86_ECX, 32);
2477                         jump_to_end = code; x86_branch8 (code, X86_CC_EQ, 0, FALSE);
2478
2479                         /* handle shifts over 31 bits */
2480                         x86_mov_reg_reg (code, ins->sreg1, ins->unused, 4);
2481                         x86_shift_reg_imm (code, X86_SHR, ins->unused, 31);
2482                         
2483                         x86_patch (jump_to_end, code);
2484                         }
2485                         break;
2486                 case OP_LSHL_IMM:
2487                         if (ins->inst_imm >= 32) {
2488                                 x86_mov_reg_reg (code, ins->unused, ins->sreg1, 4);
2489                                 x86_clear_reg (code, ins->sreg1);
2490                                 x86_shift_reg_imm (code, X86_SHL, ins->unused, ins->inst_imm - 32);
2491                         } else {
2492                                 x86_shld_reg_imm (code, ins->unused, ins->sreg1, ins->inst_imm);
2493                                 x86_shift_reg_imm (code, X86_SHL, ins->sreg1, ins->inst_imm);
2494                         }
2495                         break;
2496                 case OP_LSHR_IMM:
2497                         if (ins->inst_imm >= 32) {
2498                                 x86_mov_reg_reg (code, ins->sreg1, ins->unused,  4);
2499                                 x86_shift_reg_imm (code, X86_SAR, ins->unused, 0x1f);
2500                                 x86_shift_reg_imm (code, X86_SAR, ins->sreg1, ins->inst_imm - 32);
2501                         } else {
2502                                 x86_shrd_reg_imm (code, ins->sreg1, ins->unused, ins->inst_imm);
2503                                 x86_shift_reg_imm (code, X86_SAR, ins->unused, ins->inst_imm);
2504                         }
2505                         break;
2506                 case OP_LSHR_UN_IMM:
2507                         if (ins->inst_imm >= 32) {
2508                                 x86_mov_reg_reg (code, ins->sreg1, ins->unused, 4);
2509                                 x86_clear_reg (code, ins->unused);
2510                                 x86_shift_reg_imm (code, X86_SHR, ins->sreg1, ins->inst_imm - 32);
2511                         } else {
2512                                 x86_shrd_reg_imm (code, ins->sreg1, ins->unused, ins->inst_imm);
2513                                 x86_shift_reg_imm (code, X86_SHR, ins->unused, ins->inst_imm);
2514                         }
2515                         break;
2516                 case CEE_NOT:
2517                         x86_not_reg (code, ins->sreg1);
2518                         break;
2519                 case CEE_NEG:
2520                         x86_neg_reg (code, ins->sreg1);
2521                         break;
2522                 case OP_SEXT_I1:
2523                         x86_widen_reg (code, ins->dreg, ins->sreg1, TRUE, FALSE);
2524                         break;
2525                 case OP_SEXT_I2:
2526                         x86_widen_reg (code, ins->dreg, ins->sreg1, TRUE, TRUE);
2527                         break;
2528                 case CEE_MUL:
2529                         x86_imul_reg_reg (code, ins->sreg1, ins->sreg2);
2530                         break;
2531                 case OP_MUL_IMM:
2532                         x86_imul_reg_reg_imm (code, ins->dreg, ins->sreg1, ins->inst_imm);
2533                         break;
2534                 case CEE_MUL_OVF:
2535                         x86_imul_reg_reg (code, ins->sreg1, ins->sreg2);
2536                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_O, FALSE, "OverflowException");
2537                         break;
2538                 case CEE_MUL_OVF_UN: {
2539                         /* the mul operation and the exception check should most likely be split */
2540                         int non_eax_reg, saved_eax = FALSE, saved_edx = FALSE;
2541                         /*g_assert (ins->sreg2 == X86_EAX);
2542                         g_assert (ins->dreg == X86_EAX);*/
2543                         if (ins->sreg2 == X86_EAX) {
2544                                 non_eax_reg = ins->sreg1;
2545                         } else if (ins->sreg1 == X86_EAX) {
2546                                 non_eax_reg = ins->sreg2;
2547                         } else {
2548                                 /* no need to save since we're going to store to it anyway */
2549                                 if (ins->dreg != X86_EAX) {
2550                                         saved_eax = TRUE;
2551                                         x86_push_reg (code, X86_EAX);
2552                                 }
2553                                 x86_mov_reg_reg (code, X86_EAX, ins->sreg1, 4);
2554                                 non_eax_reg = ins->sreg2;
2555                         }
2556                         if (ins->dreg == X86_EDX) {
2557                                 if (!saved_eax) {
2558                                         saved_eax = TRUE;
2559                                         x86_push_reg (code, X86_EAX);
2560                                 }
2561                         } else if (ins->dreg != X86_EAX) {
2562                                 saved_edx = TRUE;
2563                                 x86_push_reg (code, X86_EDX);
2564                         }
2565                         x86_mul_reg (code, non_eax_reg, FALSE);
2566                         /* save before the check since pop and mov don't change the flags */
2567                         if (ins->dreg != X86_EAX)
2568                                 x86_mov_reg_reg (code, ins->dreg, X86_EAX, 4);
2569                         if (saved_edx)
2570                                 x86_pop_reg (code, X86_EDX);
2571                         if (saved_eax)
2572                                 x86_pop_reg (code, X86_EAX);
2573                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_O, FALSE, "OverflowException");
2574                         break;
2575                 }
2576                 case OP_ICONST:
2577                         x86_mov_reg_imm (code, ins->dreg, ins->inst_c0);
2578                         break;
2579                 case OP_AOTCONST:
2580                         mono_add_patch_info (cfg, offset, (MonoJumpInfoType)ins->inst_i1, ins->inst_p0);
2581                         x86_mov_reg_imm (code, ins->dreg, 0);
2582                         break;
2583                 case CEE_CONV_I4:
2584                 case OP_MOVE:
2585                         x86_mov_reg_reg (code, ins->dreg, ins->sreg1, 4);
2586                         break;
2587                 case CEE_CONV_U4:
2588                         g_assert_not_reached ();
2589                 case CEE_JMP: {
2590                         /*
2591                          * Note: this 'frame destruction' logic is useful for tail calls, too.
2592                          * Keep in sync with the code in emit_epilog.
2593                          */
2594                         int pos = 0;
2595
2596                         /* FIXME: no tracing support... */
2597                         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
2598                                 code = mono_arch_instrument_epilog (cfg, mono_profiler_method_leave, code, FALSE);
2599                         /* reset offset to make max_len work */
2600                         offset = code - cfg->native_code;
2601
2602                         g_assert (!cfg->method->save_lmf);
2603
2604                         if (cfg->used_int_regs & (1 << X86_EBX))
2605                                 pos -= 4;
2606                         if (cfg->used_int_regs & (1 << X86_EDI))
2607                                 pos -= 4;
2608                         if (cfg->used_int_regs & (1 << X86_ESI))
2609                                 pos -= 4;
2610                         if (pos)
2611                                 x86_lea_membase (code, X86_ESP, X86_EBP, pos);
2612         
2613                         if (cfg->used_int_regs & (1 << X86_ESI))
2614                                 x86_pop_reg (code, X86_ESI);
2615                         if (cfg->used_int_regs & (1 << X86_EDI))
2616                                 x86_pop_reg (code, X86_EDI);
2617                         if (cfg->used_int_regs & (1 << X86_EBX))
2618                                 x86_pop_reg (code, X86_EBX);
2619         
2620                         /* restore ESP/EBP */
2621                         x86_leave (code);
2622                         offset = code - cfg->native_code;
2623                         mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_METHOD_JUMP, ins->inst_p0);
2624                         x86_jump32 (code, 0);
2625                         break;
2626                 }
2627                 case OP_CHECK_THIS:
2628                         /* ensure ins->sreg1 is not NULL
2629                          * note that cmp DWORD PTR [eax], eax is one byte shorter than
2630                          * cmp DWORD PTR [eax], 0
2631                          */
2632                         x86_alu_membase_reg (code, X86_CMP, ins->sreg1, 0, ins->sreg1);
2633                         break;
2634                 case OP_ARGLIST: {
2635                         int hreg = ins->sreg1 == X86_EAX? X86_ECX: X86_EAX;
2636                         x86_push_reg (code, hreg);
2637                         x86_lea_membase (code, hreg, X86_EBP, cfg->sig_cookie);
2638                         x86_mov_membase_reg (code, ins->sreg1, 0, hreg, 4);
2639                         x86_pop_reg (code, hreg);
2640                         break;
2641                 }
2642                 case OP_FCALL:
2643                 case OP_LCALL:
2644                 case OP_VCALL:
2645                 case OP_VOIDCALL:
2646                 case CEE_CALL:
2647                         call = (MonoCallInst*)ins;
2648                         if (ins->flags & MONO_INST_HAS_METHOD)
2649                                 mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_METHOD, call->method);
2650                         else {
2651                                 mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_ABS, call->fptr);
2652                         }
2653                         x86_call_code (code, 0);
2654                         if (call->stack_usage && !CALLCONV_IS_STDCALL (call->signature->call_convention))
2655                                 x86_alu_reg_imm (code, X86_ADD, X86_ESP, call->stack_usage);
2656                         break;
2657                 case OP_FCALL_REG:
2658                 case OP_LCALL_REG:
2659                 case OP_VCALL_REG:
2660                 case OP_VOIDCALL_REG:
2661                 case OP_CALL_REG:
2662                         call = (MonoCallInst*)ins;
2663                         x86_call_reg (code, ins->sreg1);
2664                         if (call->stack_usage && !CALLCONV_IS_STDCALL (call->signature->call_convention))
2665                                 x86_alu_reg_imm (code, X86_ADD, X86_ESP, call->stack_usage);
2666                         break;
2667                 case OP_FCALL_MEMBASE:
2668                 case OP_LCALL_MEMBASE:
2669                 case OP_VCALL_MEMBASE:
2670                 case OP_VOIDCALL_MEMBASE:
2671                 case OP_CALL_MEMBASE:
2672                         call = (MonoCallInst*)ins;
2673                         x86_call_membase (code, ins->sreg1, ins->inst_offset);
2674                         if (call->stack_usage && !CALLCONV_IS_STDCALL (call->signature->call_convention))
2675                                 x86_alu_reg_imm (code, X86_ADD, X86_ESP, call->stack_usage);
2676                         break;
2677                 case OP_OUTARG:
2678                 case OP_X86_PUSH:
2679                         x86_push_reg (code, ins->sreg1);
2680                         break;
2681                 case OP_X86_PUSH_IMM:
2682                         x86_push_imm (code, ins->inst_imm);
2683                         break;
2684                 case OP_X86_PUSH_MEMBASE:
2685                         x86_push_membase (code, ins->inst_basereg, ins->inst_offset);
2686                         break;
2687                 case OP_X86_PUSH_OBJ: 
2688                         x86_alu_reg_imm (code, X86_SUB, X86_ESP, ins->inst_imm);
2689                         x86_push_reg (code, X86_EDI);
2690                         x86_push_reg (code, X86_ESI);
2691                         x86_push_reg (code, X86_ECX);
2692                         if (ins->inst_offset)
2693                                 x86_lea_membase (code, X86_ESI, ins->inst_basereg, ins->inst_offset);
2694                         else
2695                                 x86_mov_reg_reg (code, X86_ESI, ins->inst_basereg, 4);
2696                         x86_lea_membase (code, X86_EDI, X86_ESP, 12);
2697                         x86_mov_reg_imm (code, X86_ECX, (ins->inst_imm >> 2));
2698                         x86_cld (code);
2699                         x86_prefix (code, X86_REP_PREFIX);
2700                         x86_movsd (code);
2701                         x86_pop_reg (code, X86_ECX);
2702                         x86_pop_reg (code, X86_ESI);
2703                         x86_pop_reg (code, X86_EDI);
2704                         break;
2705                 case OP_X86_LEA:
2706                         x86_lea_memindex (code, ins->dreg, ins->sreg1, ins->inst_imm, ins->sreg2, ins->unused);
2707                         break;
2708                 case OP_X86_LEA_MEMBASE:
2709                         x86_lea_membase (code, ins->dreg, ins->sreg1, ins->inst_imm);
2710                         break;
2711                 case OP_X86_XCHG:
2712                         x86_xchg_reg_reg (code, ins->sreg1, ins->sreg2, 4);
2713                         break;
2714                 case OP_LOCALLOC:
2715                         /* keep alignment */
2716                         x86_alu_reg_imm (code, X86_ADD, ins->sreg1, MONO_ARCH_FRAME_ALIGNMENT - 1);
2717                         x86_alu_reg_imm (code, X86_AND, ins->sreg1, ~(MONO_ARCH_FRAME_ALIGNMENT - 1));
2718                         code = mono_emit_stack_alloc (code, ins);
2719                         x86_mov_reg_reg (code, ins->dreg, X86_ESP, 4);
2720                         break;
2721                 case CEE_RET:
2722                         x86_ret (code);
2723                         break;
2724                 case CEE_THROW: {
2725                         x86_push_reg (code, ins->sreg1);
2726                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_INTERNAL_METHOD, 
2727                                              (gpointer)"mono_arch_throw_exception");
2728                         x86_call_code (code, 0);
2729                         break;
2730                 }
2731                 case OP_RETHROW: {
2732                         x86_push_reg (code, ins->sreg1);
2733                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_INTERNAL_METHOD, 
2734                                              (gpointer)"mono_arch_rethrow_exception");
2735                         x86_call_code (code, 0);
2736                         break;
2737                 }
2738                 case OP_CALL_HANDLER: 
2739                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_BB, ins->inst_target_bb);
2740                         x86_call_imm (code, 0);
2741                         break;
2742                 case OP_LABEL:
2743                         ins->inst_c0 = code - cfg->native_code;
2744                         break;
2745                 case CEE_BR:
2746                         //g_print ("target: %p, next: %p, curr: %p, last: %p\n", ins->inst_target_bb, bb->next_bb, ins, bb->last_ins);
2747                         //if ((ins->inst_target_bb == bb->next_bb) && ins == bb->last_ins)
2748                         //break;
2749                         if (ins->flags & MONO_INST_BRLABEL) {
2750                                 if (ins->inst_i0->inst_c0) {
2751                                         x86_jump_code (code, cfg->native_code + ins->inst_i0->inst_c0);
2752                                 } else {
2753                                         mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_LABEL, ins->inst_i0);
2754                                         if ((cfg->opt & MONO_OPT_BRANCH) &&
2755                                             x86_is_imm8 (ins->inst_i0->inst_c1 - cpos))
2756                                                 x86_jump8 (code, 0);
2757                                         else 
2758                                                 x86_jump32 (code, 0);
2759                                 }
2760                         } else {
2761                                 if (ins->inst_target_bb->native_offset) {
2762                                         x86_jump_code (code, cfg->native_code + ins->inst_target_bb->native_offset); 
2763                                 } else {
2764                                         mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_BB, ins->inst_target_bb);
2765                                         if ((cfg->opt & MONO_OPT_BRANCH) &&
2766                                             x86_is_imm8 (ins->inst_target_bb->max_offset - cpos))
2767                                                 x86_jump8 (code, 0);
2768                                         else 
2769                                                 x86_jump32 (code, 0);
2770                                 } 
2771                         }
2772                         break;
2773                 case OP_BR_REG:
2774                         x86_jump_reg (code, ins->sreg1);
2775                         break;
2776                 case OP_CEQ:
2777                         x86_set_reg (code, X86_CC_EQ, ins->dreg, TRUE);
2778                         x86_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
2779                         break;
2780                 case OP_CLT:
2781                         x86_set_reg (code, X86_CC_LT, ins->dreg, TRUE);
2782                         x86_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
2783                         break;
2784                 case OP_CLT_UN:
2785                         x86_set_reg (code, X86_CC_LT, ins->dreg, FALSE);
2786                         x86_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
2787                         break;
2788                 case OP_CGT:
2789                         x86_set_reg (code, X86_CC_GT, ins->dreg, TRUE);
2790                         x86_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
2791                         break;
2792                 case OP_CGT_UN:
2793                         x86_set_reg (code, X86_CC_GT, ins->dreg, FALSE);
2794                         x86_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
2795                         break;
2796                 case OP_CNE:
2797                         x86_set_reg (code, X86_CC_NE, ins->dreg, TRUE);
2798                         x86_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
2799                         break;
2800                 case OP_COND_EXC_EQ:
2801                 case OP_COND_EXC_NE_UN:
2802                 case OP_COND_EXC_LT:
2803                 case OP_COND_EXC_LT_UN:
2804                 case OP_COND_EXC_GT:
2805                 case OP_COND_EXC_GT_UN:
2806                 case OP_COND_EXC_GE:
2807                 case OP_COND_EXC_GE_UN:
2808                 case OP_COND_EXC_LE:
2809                 case OP_COND_EXC_LE_UN:
2810                 case OP_COND_EXC_OV:
2811                 case OP_COND_EXC_NO:
2812                 case OP_COND_EXC_C:
2813                 case OP_COND_EXC_NC:
2814                         EMIT_COND_SYSTEM_EXCEPTION (branch_cc_table [ins->opcode - OP_COND_EXC_EQ], 
2815                                                     (ins->opcode < OP_COND_EXC_NE_UN), ins->inst_p1);
2816                         break;
2817                 case CEE_BEQ:
2818                 case CEE_BNE_UN:
2819                 case CEE_BLT:
2820                 case CEE_BLT_UN:
2821                 case CEE_BGT:
2822                 case CEE_BGT_UN:
2823                 case CEE_BGE:
2824                 case CEE_BGE_UN:
2825                 case CEE_BLE:
2826                 case CEE_BLE_UN:
2827                         EMIT_COND_BRANCH (ins, branch_cc_table [ins->opcode - CEE_BEQ], (ins->opcode < CEE_BNE_UN));
2828                         break;
2829
2830                 /* floating point opcodes */
2831                 case OP_R8CONST: {
2832                         double d = *(double *)ins->inst_p0;
2833
2834                         if ((d == 0.0) && (mono_signbit (d) == 0)) {
2835                                 x86_fldz (code);
2836                         } else if (d == 1.0) {
2837                                 x86_fld1 (code);
2838                         } else {
2839                                 mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_R8, ins->inst_p0);
2840                                 x86_fld (code, NULL, TRUE);
2841                         }
2842                         break;
2843                 }
2844                 case OP_R4CONST: {
2845                         float f = *(float *)ins->inst_p0;
2846
2847                         if ((f == 0.0) && (mono_signbit (f) == 0)) {
2848                                 x86_fldz (code);
2849                         } else if (f == 1.0) {
2850                                 x86_fld1 (code);
2851                         } else {
2852                                 mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_R4, ins->inst_p0);
2853                                 x86_fld (code, NULL, FALSE);
2854                         }
2855                         break;
2856                 }
2857                 case OP_STORER8_MEMBASE_REG:
2858                         x86_fst_membase (code, ins->inst_destbasereg, ins->inst_offset, TRUE, TRUE);
2859                         break;
2860                 case OP_LOADR8_SPILL_MEMBASE:
2861                         x86_fld_membase (code, ins->inst_basereg, ins->inst_offset, TRUE);
2862                         x86_fxch (code, 1);
2863                         break;
2864                 case OP_LOADR8_MEMBASE:
2865                         x86_fld_membase (code, ins->inst_basereg, ins->inst_offset, TRUE);
2866                         break;
2867                 case OP_STORER4_MEMBASE_REG:
2868                         x86_fst_membase (code, ins->inst_destbasereg, ins->inst_offset, FALSE, TRUE);
2869                         break;
2870                 case OP_LOADR4_MEMBASE:
2871                         x86_fld_membase (code, ins->inst_basereg, ins->inst_offset, FALSE);
2872                         break;
2873                 case CEE_CONV_R4: /* FIXME: change precision */
2874                 case CEE_CONV_R8:
2875                         x86_push_reg (code, ins->sreg1);
2876                         x86_fild_membase (code, X86_ESP, 0, FALSE);
2877                         x86_alu_reg_imm (code, X86_ADD, X86_ESP, 4);
2878                         break;
2879                 case OP_X86_FP_LOAD_I8:
2880                         x86_fild_membase (code, ins->inst_basereg, ins->inst_offset, TRUE);
2881                         break;
2882                 case OP_X86_FP_LOAD_I4:
2883                         x86_fild_membase (code, ins->inst_basereg, ins->inst_offset, FALSE);
2884                         break;
2885                 case OP_FCONV_TO_I1:
2886                         code = emit_float_to_int (cfg, code, ins->dreg, 1, TRUE);
2887                         break;
2888                 case OP_FCONV_TO_U1:
2889                         code = emit_float_to_int (cfg, code, ins->dreg, 1, FALSE);
2890                         break;
2891                 case OP_FCONV_TO_I2:
2892                         code = emit_float_to_int (cfg, code, ins->dreg, 2, TRUE);
2893                         break;
2894                 case OP_FCONV_TO_U2:
2895                         code = emit_float_to_int (cfg, code, ins->dreg, 2, FALSE);
2896                         break;
2897                 case OP_FCONV_TO_I4:
2898                 case OP_FCONV_TO_I:
2899                         code = emit_float_to_int (cfg, code, ins->dreg, 4, TRUE);
2900                         break;
2901                 case OP_FCONV_TO_I8:
2902                         x86_alu_reg_imm (code, X86_SUB, X86_ESP, 4);
2903                         x86_fnstcw_membase(code, X86_ESP, 0);
2904                         x86_mov_reg_membase (code, ins->dreg, X86_ESP, 0, 2);
2905                         x86_alu_reg_imm (code, X86_OR, ins->dreg, 0xc00);
2906                         x86_mov_membase_reg (code, X86_ESP, 2, ins->dreg, 2);
2907                         x86_fldcw_membase (code, X86_ESP, 2);
2908                         x86_alu_reg_imm (code, X86_SUB, X86_ESP, 8);
2909                         x86_fist_pop_membase (code, X86_ESP, 0, TRUE);
2910                         x86_pop_reg (code, ins->dreg);
2911                         x86_pop_reg (code, ins->unused);
2912                         x86_fldcw_membase (code, X86_ESP, 0);
2913                         x86_alu_reg_imm (code, X86_ADD, X86_ESP, 4);
2914                         break;
2915                 case OP_LCONV_TO_R_UN: { 
2916                         static guint8 mn[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f, 0x40 };
2917                         guint8 *br;
2918
2919                         /* load 64bit integer to FP stack */
2920                         x86_push_imm (code, 0);
2921                         x86_push_reg (code, ins->sreg2);
2922                         x86_push_reg (code, ins->sreg1);
2923                         x86_fild_membase (code, X86_ESP, 0, TRUE);
2924                         /* store as 80bit FP value */
2925                         x86_fst80_membase (code, X86_ESP, 0);
2926                         
2927                         /* test if lreg is negative */
2928                         x86_test_reg_reg (code, ins->sreg2, ins->sreg2);
2929                         br = code; x86_branch8 (code, X86_CC_GEZ, 0, TRUE);
2930         
2931                         /* add correction constant mn */
2932                         x86_fld80_mem (code, mn);
2933                         x86_fld80_membase (code, X86_ESP, 0);
2934                         x86_fp_op_reg (code, X86_FADD, 1, TRUE);
2935                         x86_fst80_membase (code, X86_ESP, 0);
2936
2937                         x86_patch (br, code);
2938
2939                         x86_fld80_membase (code, X86_ESP, 0);
2940                         x86_alu_reg_imm (code, X86_ADD, X86_ESP, 12);
2941
2942                         break;
2943                 }
2944                 case OP_LCONV_TO_OVF_I: {
2945                         guint8 *br [3], *label [1];
2946
2947                         /* 
2948                          * Valid ints: 0xffffffff:8000000 to 00000000:0x7f000000
2949                          */
2950                         x86_test_reg_reg (code, ins->sreg1, ins->sreg1);
2951
2952                         /* If the low word top bit is set, see if we are negative */
2953                         br [0] = code; x86_branch8 (code, X86_CC_LT, 0, TRUE);
2954                         /* We are not negative (no top bit set, check for our top word to be zero */
2955                         x86_test_reg_reg (code, ins->sreg2, ins->sreg2);
2956                         br [1] = code; x86_branch8 (code, X86_CC_EQ, 0, TRUE);
2957                         label [0] = code;
2958
2959                         /* throw exception */
2960                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_EXC, "OverflowException");
2961                         x86_jump32 (code, 0);
2962         
2963                         x86_patch (br [0], code);
2964                         /* our top bit is set, check that top word is 0xfffffff */
2965                         x86_alu_reg_imm (code, X86_CMP, ins->sreg2, 0xffffffff);
2966                 
2967                         x86_patch (br [1], code);
2968                         /* nope, emit exception */
2969                         br [2] = code; x86_branch8 (code, X86_CC_NE, 0, TRUE);
2970                         x86_patch (br [2], label [0]);
2971
2972                         if (ins->dreg != ins->sreg1)
2973                                 x86_mov_reg_reg (code, ins->dreg, ins->sreg1, 4);
2974                         break;
2975                 }
2976                 case OP_FADD:
2977                         x86_fp_op_reg (code, X86_FADD, 1, TRUE);
2978                         break;
2979                 case OP_FSUB:
2980                         x86_fp_op_reg (code, X86_FSUB, 1, TRUE);
2981                         break;          
2982                 case OP_FMUL:
2983                         x86_fp_op_reg (code, X86_FMUL, 1, TRUE);
2984                         break;          
2985                 case OP_FDIV:
2986                         x86_fp_op_reg (code, X86_FDIV, 1, TRUE);
2987                         break;          
2988                 case OP_FNEG:
2989                         x86_fchs (code);
2990                         break;          
2991                 case OP_SIN:
2992                         x86_fsin (code);
2993                         x86_fldz (code);
2994                         x86_fp_op_reg (code, X86_FADD, 1, TRUE);
2995                         break;          
2996                 case OP_COS:
2997                         x86_fcos (code);
2998                         x86_fldz (code);
2999                         x86_fp_op_reg (code, X86_FADD, 1, TRUE);
3000                         break;          
3001                 case OP_ABS:
3002                         x86_fabs (code);
3003                         break;          
3004                 case OP_TAN: {
3005                         /* 
3006                          * it really doesn't make sense to inline all this code,
3007                          * it's here just to show that things may not be as simple 
3008                          * as they appear.
3009                          */
3010                         guchar *check_pos, *end_tan, *pop_jump;
3011                         x86_push_reg (code, X86_EAX);
3012                         x86_fptan (code);
3013                         x86_fnstsw (code);
3014                         x86_test_reg_imm (code, X86_EAX, X86_FP_C2);
3015                         check_pos = code;
3016                         x86_branch8 (code, X86_CC_NE, 0, FALSE);
3017                         x86_fstp (code, 0); /* pop the 1.0 */
3018                         end_tan = code;
3019                         x86_jump8 (code, 0);
3020                         x86_fldpi (code);
3021                         x86_fp_op (code, X86_FADD, 0);
3022                         x86_fxch (code, 1);
3023                         x86_fprem1 (code);
3024                         x86_fstsw (code);
3025                         x86_test_reg_imm (code, X86_EAX, X86_FP_C2);
3026                         pop_jump = code;
3027                         x86_branch8 (code, X86_CC_NE, 0, FALSE);
3028                         x86_fstp (code, 1);
3029                         x86_fptan (code);
3030                         x86_patch (pop_jump, code);
3031                         x86_fstp (code, 0); /* pop the 1.0 */
3032                         x86_patch (check_pos, code);
3033                         x86_patch (end_tan, code);
3034                         x86_fldz (code);
3035                         x86_fp_op_reg (code, X86_FADD, 1, TRUE);
3036                         x86_pop_reg (code, X86_EAX);
3037                         break;
3038                 }
3039                 case OP_ATAN:
3040                         x86_fld1 (code);
3041                         x86_fpatan (code);
3042                         x86_fldz (code);
3043                         x86_fp_op_reg (code, X86_FADD, 1, TRUE);
3044                         break;          
3045                 case OP_SQRT:
3046                         x86_fsqrt (code);
3047                         break;          
3048                 case OP_X86_FPOP:
3049                         x86_fstp (code, 0);
3050                         break;          
3051                 case OP_FREM: {
3052                         guint8 *l1, *l2;
3053
3054                         x86_push_reg (code, X86_EAX);
3055                         /* we need to exchange ST(0) with ST(1) */
3056                         x86_fxch (code, 1);
3057
3058                         /* this requires a loop, because fprem somtimes 
3059                          * returns a partial remainder */
3060                         l1 = code;
3061                         /* looks like MS is using fprem instead of the IEEE compatible fprem1 */
3062                         /* x86_fprem1 (code); */
3063                         x86_fprem (code);
3064                         x86_fnstsw (code);
3065                         x86_alu_reg_imm (code, X86_AND, X86_EAX, X86_FP_C2);
3066                         l2 = code + 2;
3067                         x86_branch8 (code, X86_CC_NE, l1 - l2, FALSE);
3068
3069                         /* pop result */
3070                         x86_fstp (code, 1);
3071
3072                         x86_pop_reg (code, X86_EAX);
3073                         break;
3074                 }
3075                 case OP_FCOMPARE:
3076                         if (cfg->opt & MONO_OPT_FCMOV) {
3077                                 x86_fcomip (code, 1);
3078                                 x86_fstp (code, 0);
3079                                 break;
3080                         }
3081                         /* this overwrites EAX */
3082                         EMIT_FPCOMPARE(code);
3083                         x86_alu_reg_imm (code, X86_AND, X86_EAX, X86_FP_CC_MASK);
3084                         break;
3085                 case OP_FCEQ:
3086                         if (cfg->opt & MONO_OPT_FCMOV) {
3087                                 /* zeroing the register at the start results in 
3088                                  * shorter and faster code (we can also remove the widening op)
3089                                  */
3090                                 guchar *unordered_check;
3091                                 x86_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
3092                                 x86_fcomip (code, 1);
3093                                 x86_fstp (code, 0);
3094                                 unordered_check = code;
3095                                 x86_branch8 (code, X86_CC_P, 0, FALSE);
3096                                 x86_set_reg (code, X86_CC_EQ, ins->dreg, FALSE);
3097                                 x86_patch (unordered_check, code);
3098                                 break;
3099                         }
3100                         if (ins->dreg != X86_EAX) 
3101                                 x86_push_reg (code, X86_EAX);
3102
3103                         EMIT_FPCOMPARE(code);
3104                         x86_alu_reg_imm (code, X86_AND, X86_EAX, X86_FP_CC_MASK);
3105                         x86_alu_reg_imm (code, X86_CMP, X86_EAX, 0x4000);
3106                         x86_set_reg (code, X86_CC_EQ, ins->dreg, TRUE);
3107                         x86_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
3108
3109                         if (ins->dreg != X86_EAX) 
3110                                 x86_pop_reg (code, X86_EAX);
3111                         break;
3112                 case OP_FCLT:
3113                 case OP_FCLT_UN:
3114                         if (cfg->opt & MONO_OPT_FCMOV) {
3115                                 /* zeroing the register at the start results in 
3116                                  * shorter and faster code (we can also remove the widening op)
3117                                  */
3118                                 x86_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
3119                                 x86_fcomip (code, 1);
3120                                 x86_fstp (code, 0);
3121                                 if (ins->opcode == OP_FCLT_UN) {
3122                                         guchar *unordered_check = code;
3123                                         guchar *jump_to_end;
3124                                         x86_branch8 (code, X86_CC_P, 0, FALSE);
3125                                         x86_set_reg (code, X86_CC_GT, ins->dreg, FALSE);
3126                                         jump_to_end = code;
3127                                         x86_jump8 (code, 0);
3128                                         x86_patch (unordered_check, code);
3129                                         x86_inc_reg (code, ins->dreg);
3130                                         x86_patch (jump_to_end, code);
3131                                 } else {
3132                                         x86_set_reg (code, X86_CC_GT, ins->dreg, FALSE);
3133                                 }
3134                                 break;
3135                         }
3136                         if (ins->dreg != X86_EAX) 
3137                                 x86_push_reg (code, X86_EAX);
3138
3139                         EMIT_FPCOMPARE(code);
3140                         x86_alu_reg_imm (code, X86_AND, X86_EAX, X86_FP_CC_MASK);
3141                         if (ins->opcode == OP_FCLT_UN) {
3142                                 guchar *is_not_zero_check, *end_jump;
3143                                 is_not_zero_check = code;
3144                                 x86_branch8 (code, X86_CC_NZ, 0, TRUE);
3145                                 end_jump = code;
3146                                 x86_jump8 (code, 0);
3147                                 x86_patch (is_not_zero_check, code);
3148                                 x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_CC_MASK);
3149
3150                                 x86_patch (end_jump, code);
3151                         }
3152                         x86_set_reg (code, X86_CC_EQ, ins->dreg, TRUE);
3153                         x86_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
3154
3155                         if (ins->dreg != X86_EAX) 
3156                                 x86_pop_reg (code, X86_EAX);
3157                         break;
3158                 case OP_FCGT:
3159                 case OP_FCGT_UN:
3160                         if (cfg->opt & MONO_OPT_FCMOV) {
3161                                 /* zeroing the register at the start results in 
3162                                  * shorter and faster code (we can also remove the widening op)
3163                                  */
3164                                 guchar *unordered_check;
3165                                 x86_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
3166                                 x86_fcomip (code, 1);
3167                                 x86_fstp (code, 0);
3168                                 if (ins->opcode == OP_FCGT) {
3169                                         unordered_check = code;
3170                                         x86_branch8 (code, X86_CC_P, 0, FALSE);
3171                                         x86_set_reg (code, X86_CC_LT, ins->dreg, FALSE);
3172                                         x86_patch (unordered_check, code);
3173                                 } else {
3174                                         x86_set_reg (code, X86_CC_LT, ins->dreg, FALSE);
3175                                 }
3176                                 break;
3177                         }
3178                         if (ins->dreg != X86_EAX) 
3179                                 x86_push_reg (code, X86_EAX);
3180
3181                         EMIT_FPCOMPARE(code);
3182                         x86_alu_reg_imm (code, X86_AND, X86_EAX, X86_FP_CC_MASK);
3183                         x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_C0);
3184                         if (ins->opcode == OP_FCGT_UN) {
3185                                 guchar *is_not_zero_check, *end_jump;
3186                                 is_not_zero_check = code;
3187                                 x86_branch8 (code, X86_CC_NZ, 0, TRUE);
3188                                 end_jump = code;
3189                                 x86_jump8 (code, 0);
3190                                 x86_patch (is_not_zero_check, code);
3191                                 x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_CC_MASK);
3192
3193                                 x86_patch (end_jump, code);
3194                         }
3195                         x86_set_reg (code, X86_CC_EQ, ins->dreg, TRUE);
3196                         x86_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
3197
3198                         if (ins->dreg != X86_EAX) 
3199                                 x86_pop_reg (code, X86_EAX);
3200                         break;
3201                 case OP_FBEQ:
3202                         if (cfg->opt & MONO_OPT_FCMOV) {
3203                                 guchar *jump = code;
3204                                 x86_branch8 (code, X86_CC_P, 0, TRUE);
3205                                 EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
3206                                 x86_patch (jump, code);
3207                                 break;
3208                         }
3209                         x86_alu_reg_imm (code, X86_CMP, X86_EAX, 0x4000);
3210                         EMIT_COND_BRANCH (ins, X86_CC_EQ, TRUE);
3211                         break;
3212                 case OP_FBNE_UN:
3213                         /* Branch if C013 != 100 */
3214                         if (cfg->opt & MONO_OPT_FCMOV) {
3215                                 /* branch if !ZF or (PF|CF) */
3216                                 EMIT_COND_BRANCH (ins, X86_CC_NE, FALSE);
3217                                 EMIT_COND_BRANCH (ins, X86_CC_P, FALSE);
3218                                 EMIT_COND_BRANCH (ins, X86_CC_B, FALSE);
3219                                 break;
3220                         }
3221                         x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_C3);
3222                         EMIT_COND_BRANCH (ins, X86_CC_NE, FALSE);
3223                         break;
3224                 case OP_FBLT:
3225                         if (cfg->opt & MONO_OPT_FCMOV) {
3226                                 EMIT_COND_BRANCH (ins, X86_CC_GT, FALSE);
3227                                 break;
3228                         }
3229                         EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
3230                         break;
3231                 case OP_FBLT_UN:
3232                         if (cfg->opt & MONO_OPT_FCMOV) {
3233                                 EMIT_COND_BRANCH (ins, X86_CC_P, FALSE);
3234                                 EMIT_COND_BRANCH (ins, X86_CC_GT, FALSE);
3235                                 break;
3236                         }
3237                         if (ins->opcode == OP_FBLT_UN) {
3238                                 guchar *is_not_zero_check, *end_jump;
3239                                 is_not_zero_check = code;
3240                                 x86_branch8 (code, X86_CC_NZ, 0, TRUE);
3241                                 end_jump = code;
3242                                 x86_jump8 (code, 0);
3243                                 x86_patch (is_not_zero_check, code);
3244                                 x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_CC_MASK);
3245
3246                                 x86_patch (end_jump, code);
3247                         }
3248                         EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
3249                         break;
3250                 case OP_FBGT:
3251                 case OP_FBGT_UN:
3252                         if (cfg->opt & MONO_OPT_FCMOV) {
3253                                 EMIT_COND_BRANCH (ins, X86_CC_LT, FALSE);
3254                                 break;
3255                         }
3256                         x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_C0);
3257                         if (ins->opcode == OP_FBGT_UN) {
3258                                 guchar *is_not_zero_check, *end_jump;
3259                                 is_not_zero_check = code;
3260                                 x86_branch8 (code, X86_CC_NZ, 0, TRUE);
3261                                 end_jump = code;
3262                                 x86_jump8 (code, 0);
3263                                 x86_patch (is_not_zero_check, code);
3264                                 x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_CC_MASK);
3265
3266                                 x86_patch (end_jump, code);
3267                         }
3268                         EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
3269                         break;
3270                 case OP_FBGE:
3271                         /* Branch if C013 == 100 or 001 */
3272                         if (cfg->opt & MONO_OPT_FCMOV) {
3273                                 guchar *br1;
3274
3275                                 /* skip branch if C1=1 */
3276                                 br1 = code;
3277                                 x86_branch8 (code, X86_CC_P, 0, FALSE);
3278                                 /* branch if (C0 | C3) = 1 */
3279                                 EMIT_COND_BRANCH (ins, X86_CC_BE, FALSE);
3280                                 x86_patch (br1, code);
3281                                 break;
3282                         }
3283                         x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_C0);
3284                         EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
3285                         x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_C3);
3286                         EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
3287                         break;
3288                 case OP_FBGE_UN:
3289                         /* Branch if C013 == 000 */
3290                         if (cfg->opt & MONO_OPT_FCMOV) {
3291                                 EMIT_COND_BRANCH (ins, X86_CC_LE, FALSE);
3292                                 break;
3293                         }
3294                         EMIT_COND_BRANCH (ins, X86_CC_NE, FALSE);
3295                         break;
3296                 case OP_FBLE:
3297                         /* Branch if C013=000 or 100 */
3298                         if (cfg->opt & MONO_OPT_FCMOV) {
3299                                 guchar *br1;
3300
3301                                 /* skip branch if C1=1 */
3302                                 br1 = code;
3303                                 x86_branch8 (code, X86_CC_P, 0, FALSE);
3304                                 /* branch if C0=0 */
3305                                 EMIT_COND_BRANCH (ins, X86_CC_NB, FALSE);
3306                                 x86_patch (br1, code);
3307                                 break;
3308                         }
3309                         x86_alu_reg_imm (code, X86_AND, X86_EAX, (X86_FP_C0|X86_FP_C1));
3310                         x86_alu_reg_imm (code, X86_CMP, X86_EAX, 0);
3311                         EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
3312                         break;
3313                 case OP_FBLE_UN:
3314                         /* Branch if C013 != 001 */
3315                         if (cfg->opt & MONO_OPT_FCMOV) {
3316                                 EMIT_COND_BRANCH (ins, X86_CC_P, FALSE);
3317                                 EMIT_COND_BRANCH (ins, X86_CC_GE, FALSE);
3318                                 break;
3319                         }
3320                         x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_C0);
3321                         EMIT_COND_BRANCH (ins, X86_CC_NE, FALSE);
3322                         break;
3323                 case CEE_CKFINITE: {
3324                         x86_push_reg (code, X86_EAX);
3325                         x86_fxam (code);
3326                         x86_fnstsw (code);
3327                         x86_alu_reg_imm (code, X86_AND, X86_EAX, 0x4100);
3328                         x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_C0);
3329                         x86_pop_reg (code, X86_EAX);
3330                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_EQ, FALSE, "ArithmeticException");
3331                         break;
3332                 }
3333                 
3334                 case OP_X86_TLS_GET: {
3335                         x86_prefix (code, X86_GS_PREFIX);
3336                         x86_mov_reg_mem (code, ins->dreg, ins->inst_offset, 4);                 
3337                         break;
3338                 }
3339                 default:
3340                         g_warning ("unknown opcode %s in %s()\n", mono_inst_name (ins->opcode), __FUNCTION__);
3341                         g_assert_not_reached ();
3342                 }
3343
3344                 if ((code - cfg->native_code - offset) > max_len) {
3345                         g_warning ("wrong maximal instruction length of instruction %s (expected %d, got %d)",
3346                                    mono_inst_name (ins->opcode), max_len, code - cfg->native_code - offset);
3347                         g_assert_not_reached ();
3348                 }
3349                
3350                 cpos += max_len;
3351
3352                 last_ins = ins;
3353                 last_offset = offset;
3354                 
3355                 ins = ins->next;
3356         }
3357
3358         cfg->code_len = code - cfg->native_code;
3359 }
3360
3361 void
3362 mono_arch_register_lowlevel_calls (void)
3363 {
3364 }
3365
3366 void
3367 mono_arch_patch_code (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *ji, gboolean run_cctors)
3368 {
3369         MonoJumpInfo *patch_info;
3370
3371         for (patch_info = ji; patch_info; patch_info = patch_info->next) {
3372                 unsigned char *ip = patch_info->ip.i + code;
3373                 const unsigned char *target;
3374
3375                 target = mono_resolve_patch_target (method, domain, code, patch_info, run_cctors);
3376
3377                 switch (patch_info->type) {
3378                 case MONO_PATCH_INFO_IP:
3379                         *((gconstpointer *)(ip)) = target;
3380                         continue;
3381                 case MONO_PATCH_INFO_METHOD_REL:
3382                         *((gconstpointer *)(ip)) = target;
3383                         continue;
3384                 case MONO_PATCH_INFO_SWITCH: {
3385                         *((gconstpointer *)(ip + 2)) = target;
3386                         /* we put into the table the absolute address, no need for x86_patch in this case */
3387                         continue;
3388                 }
3389                 case MONO_PATCH_INFO_IID:
3390                         *((guint32 *)(ip + 1)) = (guint32)target;
3391                         continue;                       
3392                 case MONO_PATCH_INFO_CLASS_INIT: {
3393                         guint8 *code = ip;
3394                         /* Might already been changed to a nop */
3395                         x86_call_code (code, 0);
3396                         break;
3397                 }
3398                 case MONO_PATCH_INFO_R4:
3399                 case MONO_PATCH_INFO_R8:
3400                         *((gconstpointer *)(ip + 2)) = target;
3401                         continue;
3402                 case MONO_PATCH_INFO_METHODCONST:
3403                 case MONO_PATCH_INFO_CLASS:
3404                 case MONO_PATCH_INFO_IMAGE:
3405                 case MONO_PATCH_INFO_FIELD:
3406                 case MONO_PATCH_INFO_VTABLE:
3407                 case MONO_PATCH_INFO_SFLDA:
3408                 case MONO_PATCH_INFO_EXC_NAME:
3409                 case MONO_PATCH_INFO_LDSTR:
3410                 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3411                 case MONO_PATCH_INFO_LDTOKEN:
3412                         *((gconstpointer *)(ip + 1)) = target;
3413                         continue;
3414                 default:
3415                         break;
3416                 }
3417                 x86_patch (ip, target);
3418         }
3419 }
3420
3421 int
3422 mono_arch_max_epilog_size (MonoCompile *cfg)
3423 {
3424         int exc_count = 0, max_epilog_size = 16;
3425         MonoJumpInfo *patch_info;
3426         
3427         if (cfg->method->save_lmf)
3428                 max_epilog_size += 128;
3429         
3430         if (mono_jit_trace_calls != NULL)
3431                 max_epilog_size += 50;
3432
3433         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
3434                 max_epilog_size += 50;
3435
3436         /* count the number of exception infos */
3437      
3438         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3439                 if (patch_info->type == MONO_PATCH_INFO_EXC)
3440                         exc_count++;
3441         }
3442
3443         /* 
3444          * make sure we have enough space for exceptions
3445          * 16 is the size of two push_imm instructions and a call
3446          */
3447         max_epilog_size += exc_count*16;
3448
3449         return max_epilog_size;
3450 }
3451
3452 guint8 *
3453 mono_arch_emit_prolog (MonoCompile *cfg)
3454 {
3455         MonoMethod *method = cfg->method;
3456         MonoBasicBlock *bb;
3457         MonoMethodSignature *sig;
3458         MonoInst *inst;
3459         int alloc_size, pos, max_offset, i;
3460         guint8 *code;
3461
3462         cfg->code_size =  MAX (mono_method_get_header (method)->code_size * 4, 256);
3463         code = cfg->native_code = g_malloc (cfg->code_size);
3464
3465         x86_push_reg (code, X86_EBP);
3466         x86_mov_reg_reg (code, X86_EBP, X86_ESP, 4);
3467
3468         alloc_size = - cfg->stack_offset;
3469         pos = 0;
3470
3471         if (method->save_lmf) {
3472                 pos += sizeof (MonoLMF);
3473
3474                 /* save the current IP */
3475                 mono_add_patch_info (cfg, code + 1 - cfg->native_code, MONO_PATCH_INFO_IP, NULL);
3476                 x86_push_imm_template (code);
3477
3478                 /* save all caller saved regs */
3479                 x86_push_reg (code, X86_EBP);
3480                 x86_push_reg (code, X86_ESI);
3481                 x86_push_reg (code, X86_EDI);
3482                 x86_push_reg (code, X86_EBX);
3483
3484                 /* save method info */
3485                 x86_push_imm (code, method);
3486
3487                 /* get the address of lmf for the current thread */
3488                 /* 
3489                  * This is performance critical so we try to use some tricks to make
3490                  * it fast.
3491                  */
3492                 if (lmf_tls_offset != -1) {
3493                         /* Load lmf quicky using the GS register */
3494                         x86_prefix (code, X86_GS_PREFIX);
3495                         x86_mov_reg_mem (code, X86_EAX, lmf_tls_offset, 4);
3496                 }
3497                 else {
3498                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_INTERNAL_METHOD, 
3499                                                                  (gpointer)"mono_get_lmf_addr");
3500                         x86_call_code (code, 0);
3501                 }
3502
3503                 /* push lmf */
3504                 x86_push_reg (code, X86_EAX); 
3505                 /* push *lfm (previous_lmf) */
3506                 x86_push_membase (code, X86_EAX, 0);
3507                 /* *(lmf) = ESP */
3508                 x86_mov_membase_reg (code, X86_EAX, 0, X86_ESP, 4);
3509         } else {
3510
3511                 if (cfg->used_int_regs & (1 << X86_EBX)) {
3512                         x86_push_reg (code, X86_EBX);
3513                         pos += 4;
3514                 }
3515
3516                 if (cfg->used_int_regs & (1 << X86_EDI)) {
3517                         x86_push_reg (code, X86_EDI);
3518                         pos += 4;
3519                 }
3520
3521                 if (cfg->used_int_regs & (1 << X86_ESI)) {
3522                         x86_push_reg (code, X86_ESI);
3523                         pos += 4;
3524                 }
3525         }
3526
3527         alloc_size -= pos;
3528
3529         if (alloc_size) {
3530                 /* See mono_emit_stack_alloc */
3531 #ifdef PLATFORM_WIN32
3532                 guint32 remaining_size = alloc_size;
3533                 while (remaining_size >= 0x1000) {
3534                         x86_alu_reg_imm (code, X86_SUB, X86_ESP, 0x1000);
3535                         x86_test_membase_reg (code, X86_ESP, 0, X86_ESP);
3536                         remaining_size -= 0x1000;
3537                 }
3538                 if (remaining_size)
3539                         x86_alu_reg_imm (code, X86_SUB, X86_ESP, remaining_size);
3540 #else
3541                 x86_alu_reg_imm (code, X86_SUB, X86_ESP, alloc_size);
3542 #endif
3543         }
3544
3545         /* compute max_offset in order to use short forward jumps */
3546         max_offset = 0;
3547         if (cfg->opt & MONO_OPT_BRANCH) {
3548                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3549                         MonoInst *ins = bb->code;
3550                         bb->max_offset = max_offset;
3551
3552                         if (cfg->prof_options & MONO_PROFILE_COVERAGE)
3553                                 max_offset += 6;
3554                         /* max alignment for loops */
3555                         if ((cfg->opt & MONO_OPT_LOOP) && bb_is_loop_start (bb))
3556                                 max_offset += LOOP_ALIGNMENT;
3557
3558                         while (ins) {
3559                                 if (ins->opcode == OP_LABEL)
3560                                         ins->inst_c1 = max_offset;
3561                                 
3562                                 max_offset += ((guint8 *)ins_spec [ins->opcode])[MONO_INST_LEN];
3563                                 ins = ins->next;
3564                         }
3565                 }
3566         }
3567
3568         if (mono_jit_trace_calls != NULL && mono_trace_eval (method))
3569                 code = mono_arch_instrument_prolog (cfg, mono_trace_enter_method, code, TRUE);
3570
3571         /* load arguments allocated to register from the stack */
3572         sig = method->signature;
3573         pos = 0;
3574
3575         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
3576                 inst = cfg->varinfo [pos];
3577                 if (inst->opcode == OP_REGVAR) {
3578                         x86_mov_reg_membase (code, inst->dreg, X86_EBP, inst->inst_offset, 4);
3579                         if (cfg->verbose_level > 2)
3580                                 g_print ("Argument %d assigned to register %s\n", pos, mono_arch_regname (inst->dreg));
3581                 }
3582                 pos++;
3583         }
3584
3585         cfg->code_len = code - cfg->native_code;
3586
3587         return code;
3588 }
3589
3590 void
3591 mono_arch_emit_epilog (MonoCompile *cfg)
3592 {
3593         MonoJumpInfo *patch_info;
3594         MonoMethod *method = cfg->method;
3595         MonoMethodSignature *sig = method->signature;
3596         int pos;
3597         guint32 stack_to_pop;
3598         guint8 *code;
3599
3600         code = cfg->native_code + cfg->code_len;
3601
3602         if (mono_jit_trace_calls != NULL && mono_trace_eval (method))
3603                 code = mono_arch_instrument_epilog (cfg, mono_trace_leave_method, code, TRUE);
3604
3605         /* the code restoring the registers must be kept in sync with CEE_JMP */
3606         pos = 0;
3607         
3608         if (method->save_lmf) {
3609                 gint32 prev_lmf_reg;
3610
3611                 /* Find a spare register */
3612                 switch (sig->ret->type) {
3613                 case MONO_TYPE_I8:
3614                 case MONO_TYPE_U8:
3615                         prev_lmf_reg = X86_EDI;
3616                         cfg->used_int_regs |= (1 << X86_EDI);
3617                         break;
3618                 default:
3619                         prev_lmf_reg = X86_EDX;
3620                         break;
3621                 }
3622
3623                 /* reg = previous_lmf */
3624                 x86_mov_reg_membase (code, prev_lmf_reg, X86_EBP, -32, 4);
3625
3626                 /* ecx = lmf */
3627                 x86_mov_reg_membase (code, X86_ECX, X86_EBP, -28, 4);
3628
3629                 /* *(lmf) = previous_lmf */
3630                 x86_mov_membase_reg (code, X86_ECX, 0, prev_lmf_reg, 4);
3631
3632                 /* restore caller saved regs */
3633                 if (cfg->used_int_regs & (1 << X86_EBX)) {
3634                         x86_mov_reg_membase (code, X86_EBX, X86_EBP, -20, 4);
3635                 }
3636
3637                 if (cfg->used_int_regs & (1 << X86_EDI)) {
3638                         x86_mov_reg_membase (code, X86_EDI, X86_EBP, -16, 4);
3639                 }
3640                 if (cfg->used_int_regs & (1 << X86_ESI)) {
3641                         x86_mov_reg_membase (code, X86_ESI, X86_EBP, -12, 4);
3642                 }
3643
3644                 /* EBP is restored by LEAVE */
3645         } else {
3646                 if (cfg->used_int_regs & (1 << X86_EBX)) {
3647                         pos -= 4;
3648                 }
3649                 if (cfg->used_int_regs & (1 << X86_EDI)) {
3650                         pos -= 4;
3651                 }
3652                 if (cfg->used_int_regs & (1 << X86_ESI)) {
3653                         pos -= 4;
3654                 }
3655
3656                 if (pos)
3657                         x86_lea_membase (code, X86_ESP, X86_EBP, pos);
3658
3659                 if (cfg->used_int_regs & (1 << X86_ESI)) {
3660                         x86_pop_reg (code, X86_ESI);
3661                 }
3662                 if (cfg->used_int_regs & (1 << X86_EDI)) {
3663                         x86_pop_reg (code, X86_EDI);
3664                 }
3665                 if (cfg->used_int_regs & (1 << X86_EBX)) {
3666                         x86_pop_reg (code, X86_EBX);
3667                 }
3668         }
3669
3670         x86_leave (code);
3671
3672         if (CALLCONV_IS_STDCALL (sig->call_convention)) {
3673                 MonoJitArgumentInfo *arg_info = alloca (sizeof (MonoJitArgumentInfo) * (sig->param_count + 1));
3674
3675                 stack_to_pop = mono_arch_get_argument_info (sig, sig->param_count, arg_info);
3676         } else if (MONO_TYPE_ISSTRUCT (cfg->method->signature->ret))
3677                 stack_to_pop = 4;
3678         else
3679                 stack_to_pop = 0;
3680
3681         if (stack_to_pop)
3682                 x86_ret_imm (code, stack_to_pop);
3683         else
3684                 x86_ret (code);
3685
3686         /* add code to raise exceptions */
3687         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3688                 switch (patch_info->type) {
3689                 case MONO_PATCH_INFO_EXC:
3690                         x86_patch (patch_info->ip.i + cfg->native_code, code);
3691                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_EXC_NAME, patch_info->data.target);
3692                         x86_push_imm (code, patch_info->data.target);
3693                         mono_add_patch_info (cfg, code + 1 - cfg->native_code, MONO_PATCH_INFO_METHOD_REL, (gpointer)patch_info->ip.i);
3694                         x86_push_imm (code, patch_info->ip.i + cfg->native_code);
3695                         patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
3696                         patch_info->data.name = "mono_arch_throw_exception_by_name";
3697                         patch_info->ip.i = code - cfg->native_code;
3698                         x86_jump_code (code, 0);
3699                         break;
3700                 default:
3701                         /* do nothing */
3702                         break;
3703                 }
3704         }
3705
3706         cfg->code_len = code - cfg->native_code;
3707
3708         g_assert (cfg->code_len < cfg->code_size);
3709
3710 }
3711
3712 void
3713 mono_arch_flush_icache (guint8 *code, gint size)
3714 {
3715         /* not needed */
3716 }
3717
3718 void
3719 mono_arch_flush_register_windows (void)
3720 {
3721 }
3722
3723 /*
3724  * Support for fast access to the thread-local lmf structure using the GS
3725  * segment register on NPTL + kernel 2.6.x.
3726  */
3727
3728 static gboolean tls_offset_inited = FALSE;
3729
3730 /* code should be simply return <tls var>; */
3731 static int read_tls_offset_from_method (void* method)
3732 {
3733         guint8* code = (guint8*) method;
3734         /* 
3735          * Determine the offset of the variable inside the TLS structures
3736          * by disassembling the function.
3737          */
3738
3739         /* gcc-3.3.2
3740          *
3741          * push ebp
3742          * mov ebp, esp
3743          * mov eax, gs:0
3744          * mov eax, DWORD PTR [eax+<offset>]
3745          */
3746         if (
3747                 (code [0] == 0x55) && (code [1] == 0x89) && (code [2] == 0xe5) &&
3748                 (code [3] == 0x65) && (code [4] == 0xa1) && (code [5] == 0x00) &&
3749                 (code [6] == 0x00) && (code [7] == 0x00) && (code [8] == 0x00) &&
3750                 (code [9] == 0x8b) && (code [10] == 0x80)) {
3751                 return *(int*)&(code [11]);
3752         }
3753         
3754         /* gcc-3.4
3755          *
3756          * push ebp
3757          * mov ebp, esp
3758          * mov eax, gs:<offset>
3759          */
3760         if (
3761                 (code [0] == 0x55) && (code [1] == 0x89) && (code [2] == 0xe5) &&
3762                 (code [3] == 0x65) && (code [4] == 0xa1)) {
3763                 return *(int*)&(code [5]);
3764         }
3765         
3766         /* 3.2.2 with -march=athlon
3767          *
3768          * push ebp
3769          * mov eax, gs:<offset>
3770          * mov ebp, esp
3771          */
3772         if (
3773                 (code [0] == 0x55) && (code [1] == 0x65) && (code [2] == 0xa1)) {
3774                 return *(int*)&(code [3]);
3775         }
3776         
3777         return -1;
3778 }
3779 void
3780 mono_arch_setup_jit_tls_data (MonoJitTlsData *tls)
3781 {
3782 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
3783         pthread_t self = pthread_self();
3784         pthread_attr_t attr;
3785         void *staddr = NULL;
3786         size_t stsize = 0;
3787         struct sigaltstack sa;
3788 #endif
3789
3790         if (!tls_offset_inited) {
3791                 tls_offset_inited = TRUE;
3792                 if (getenv ("MONO_NPTL")) {
3793                         lmf_tls_offset = read_tls_offset_from_method (mono_get_lmf_addr);
3794                         appdomain_tls_offset = read_tls_offset_from_method (mono_domain_get);
3795                         thread_tls_offset = read_tls_offset_from_method (mono_thread_current);
3796                 }
3797         }               
3798
3799 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
3800
3801         /* Determine stack boundaries */
3802         if (!mono_running_on_valgrind ()) {
3803 #ifdef HAVE_PTHREAD_GETATTR_NP
3804                 pthread_getattr_np( self, &attr );
3805 #else
3806 #ifdef HAVE_PTHREAD_ATTR_GET_NP
3807                 pthread_attr_get_np( self, &attr );
3808 #elif defined(sun)
3809                 pthread_attr_init( &attr );
3810                 pthread_attr_getstacksize( &attr, &stsize );
3811 #else
3812 #error "Not implemented"
3813 #endif
3814 #endif
3815 #ifndef sun
3816                 pthread_attr_getstack( &attr, &staddr, &stsize );
3817 #endif
3818         }
3819
3820         /* 
3821          * staddr seems to be wrong for the main thread, so we keep the value in
3822          * tls->end_of_stack
3823          */
3824         tls->stack_size = stsize;
3825
3826         /* Setup an alternate signal stack */
3827         tls->signal_stack = g_malloc (SIGNAL_STACK_SIZE);
3828         tls->signal_stack_size = SIGNAL_STACK_SIZE;
3829
3830         sa.ss_sp = tls->signal_stack;
3831         sa.ss_size = SIGNAL_STACK_SIZE;
3832         sa.ss_flags = SS_ONSTACK;
3833         sigaltstack (&sa, NULL);
3834 #endif
3835 }
3836
3837 void
3838 mono_arch_free_jit_tls_data (MonoJitTlsData *tls)
3839 {
3840 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
3841         struct sigaltstack sa;
3842
3843         sa.ss_sp = tls->signal_stack;
3844         sa.ss_size = SIGNAL_STACK_SIZE;
3845         sa.ss_flags = SS_DISABLE;
3846         sigaltstack  (&sa, NULL);
3847
3848         if (tls->signal_stack)
3849                 g_free (tls->signal_stack);
3850 #endif
3851 }
3852
3853 void
3854 mono_arch_emit_this_vret_args (MonoCompile *cfg, MonoCallInst *inst, int this_reg, int this_type, int vt_reg)
3855 {
3856
3857         /* add the this argument */
3858         if (this_reg != -1) {
3859                 MonoInst *this;
3860                 MONO_INST_NEW (cfg, this, OP_OUTARG);
3861                 this->type = this_type;
3862                 this->sreg1 = this_reg;
3863                 mono_bblock_add_inst (cfg->cbb, this);
3864         }
3865
3866         if (vt_reg != -1) {
3867                 MonoInst *vtarg;
3868                 MONO_INST_NEW (cfg, vtarg, OP_OUTARG);
3869                 vtarg->type = STACK_MP;
3870                 vtarg->sreg1 = vt_reg;
3871                 mono_bblock_add_inst (cfg->cbb, vtarg);
3872         }
3873 }
3874
3875
3876 gint
3877 mono_arch_get_opcode_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
3878 {
3879         if (cmethod->klass == mono_defaults.math_class) {
3880                 if (strcmp (cmethod->name, "Sin") == 0)
3881                         return OP_SIN;
3882                 else if (strcmp (cmethod->name, "Cos") == 0)
3883                         return OP_COS;
3884                 else if (strcmp (cmethod->name, "Tan") == 0)
3885                         return OP_TAN;
3886                 else if (strcmp (cmethod->name, "Atan") == 0)
3887                         return OP_ATAN;
3888                 else if (strcmp (cmethod->name, "Sqrt") == 0)
3889                         return OP_SQRT;
3890                 else if (strcmp (cmethod->name, "Abs") == 0 && fsig->params [0]->type == MONO_TYPE_R8)
3891                         return OP_ABS;
3892 #if 0
3893                 /* OP_FREM is not IEEE compatible */
3894                 else if (strcmp (cmethod->name, "IEEERemainder") == 0)
3895                         return OP_FREM;
3896 #endif
3897                 else
3898                         return -1;
3899         } else {
3900                 return -1;
3901         }
3902         return -1;
3903 }
3904
3905
3906 gboolean
3907 mono_arch_print_tree (MonoInst *tree, int arity)
3908 {
3909         return 0;
3910 }
3911
3912 MonoInst* mono_arch_get_domain_intrinsic (MonoCompile* cfg)
3913 {
3914         MonoInst* ins;
3915         
3916         if (appdomain_tls_offset == -1)
3917                 return NULL;
3918         
3919         MONO_INST_NEW (cfg, ins, OP_X86_TLS_GET);
3920         ins->inst_offset = appdomain_tls_offset;
3921         return ins;
3922 }
3923
3924 MonoInst* mono_arch_get_thread_intrinsic (MonoCompile* cfg)
3925 {
3926         MonoInst* ins;
3927         
3928         if (thread_tls_offset == -1)
3929                 return NULL;
3930         
3931         MONO_INST_NEW (cfg, ins, OP_X86_TLS_GET);
3932         ins->inst_offset = thread_tls_offset;
3933         return ins;
3934 }