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