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