fixed most compiler warnings, code cleanup
[mono.git] / mono / jit / emit-x86.c
1 /*
2  * emit-x86.c: Support functions for emitting x86 code
3  *
4  * Authors:
5  *   Dietmar Maurer (dietmar@ximian.com)
6  *   Miguel de Icaza (miguel@ximian.com)
7  *
8  * (C) 2001 Ximian, Inc.
9  */
10
11 #include <config.h>
12 #include <glib.h>
13
14 #include <mono/metadata/assembly.h>
15 #include <mono/metadata/loader.h>
16 #include <mono/metadata/cil-coff.h>
17 #include <mono/metadata/tabledefs.h>
18 #include <mono/metadata/class.h>
19 #include <mono/metadata/mono-endian.h>
20 #include <mono/arch/x86/x86-codegen.h>
21
22 #include "jit.h"
23 #include "codegen.h"
24 #include "debug.h"
25
26 static void
27 enter_method (MonoMethod *method, gpointer ebp)
28 {
29         int i, j;
30         MonoClass *class;
31         MonoObject *o;
32
33         printf ("ENTER: %s.%s::%s\n(", method->klass->name_space,
34                 method->klass->name, method->name);
35
36         
37         if (((int)ebp & 3) != 0) {
38                 g_error ("unaligned stack detected (%p)", ebp);
39         }
40
41         ebp += 8;
42
43         if (ISSTRUCT (method->signature->ret)) {
44                 int size, align;
45                 
46                 g_assert (!method->signature->ret->byref);
47
48                 size = mono_type_stack_size (method->signature->ret, &align);
49
50                 printf ("VALUERET:%p, ", *((gpointer *)ebp));
51                 ebp += sizeof (gpointer);
52         }
53
54         if (method->signature->hasthis) {
55                 if (method->klass->valuetype) {
56                         printf ("value:%p, ", *((gpointer *)ebp));
57                 } else {
58                         o = *((MonoObject **)ebp);
59
60                         g_assert (o);
61
62                         class = o->klass;
63
64                         if (class == mono_defaults.string_class) {
65                                 printf ("this:[STRING:%p:%s], ", o, mono_string_to_utf8 ((MonoString *)o));
66                         } else {
67                                 printf ("this:%p[%s.%s], ", o, class->name_space, class->name);
68                         }
69                 }
70                 ebp += sizeof (gpointer);
71         }
72
73         for (i = 0; i < method->signature->param_count; ++i) {
74                 MonoType *type = method->signature->params [i];
75                 int size, align;
76                 size = mono_type_stack_size (type, &align);
77
78                 if (type->byref) {
79                         printf ("[BYREF:%p], ", *((gpointer *)ebp)); 
80                 } else switch (type->type) {
81                         
82                 case MONO_TYPE_BOOLEAN:
83                 case MONO_TYPE_CHAR:
84                 case MONO_TYPE_I1:
85                 case MONO_TYPE_U1:
86                 case MONO_TYPE_I2:
87                 case MONO_TYPE_U2:
88                 case MONO_TYPE_I4:
89                 case MONO_TYPE_U4:
90                 case MONO_TYPE_I:
91                 case MONO_TYPE_U:
92                         printf ("%d, ", *((int *)(ebp)));
93                         break;
94                 case MONO_TYPE_STRING: {
95                         MonoString *s = *((MonoString **)ebp);
96                         if (s) {
97                                 g_assert (((MonoObject *)s)->klass == mono_defaults.string_class);
98                                 printf ("[STRING:%p:%s], ", s, mono_string_to_utf8 (s));
99                         } else 
100                                 printf ("[STRING:null], ");
101                         break;
102                 }
103                 case MONO_TYPE_CLASS:
104                 case MONO_TYPE_OBJECT: {
105                         o = *((MonoObject **)ebp);
106                         if (o) {
107                                 class = o->klass;
108                     
109                                 if (class == mono_defaults.string_class) {
110                                         printf ("[STRING:%p:%s], ", o, mono_string_to_utf8 ((MonoString *)o));
111                                 } else if (class == mono_defaults.int32_class) {
112                                         printf ("[INT32:%p:%d], ", o, *(gint32 *)((gpointer)o + sizeof (MonoObject)));
113                                 } else
114                                         printf ("[%s.%s:%p], ", class->name_space, class->name, o);
115                         } else {
116                                 printf ("%p, ", *((gpointer *)(ebp)));                          
117                         }
118                         break;
119                 }
120                 case MONO_TYPE_PTR:
121                 case MONO_TYPE_FNPTR:
122                 case MONO_TYPE_ARRAY:
123                 case MONO_TYPE_SZARRAY:
124                         printf ("%p, ", *((gpointer *)(ebp)));
125                         break;
126                 case MONO_TYPE_I8:
127                         printf ("%lld, ", *((gint64 *)(ebp)));
128                         break;
129                 case MONO_TYPE_R4:
130                         printf ("%f, ", *((float *)(ebp)));
131                         break;
132                 case MONO_TYPE_R8:
133                         printf ("%f, ", *((double *)(ebp)));
134                         break;
135                 case MONO_TYPE_VALUETYPE: 
136                         printf ("[");
137                         for (j = 0; j < size; j++)
138                                 printf ("%02x,", *((guint8*)ebp +j));
139                         printf ("], ");
140                         break;
141                 default:
142                         printf ("XX, ");
143                 }
144
145                 g_assert (align == 4);
146                 ebp += size + 3;
147                 ebp = (gpointer)((unsigned)ebp & ~(3));
148         }
149
150         printf (")\n");
151 }
152
153 static void
154 leave_method (MonoMethod *method, int edx, int eax, double test)
155 {
156         gint64 l;
157
158         printf ("LEAVE: %s.%s::%s ", method->klass->name_space,
159                 method->klass->name, method->name);
160
161         switch (method->signature->ret->type) {
162         case MONO_TYPE_VOID:
163                 break;
164         case MONO_TYPE_BOOLEAN:
165                 if (eax)
166                         printf ("TRUE:%d", eax);
167                 else 
168                         printf ("FALSE");
169                         
170                 break;
171         case MONO_TYPE_CHAR:
172         case MONO_TYPE_I1:
173         case MONO_TYPE_U1:
174         case MONO_TYPE_I2:
175         case MONO_TYPE_U2:
176         case MONO_TYPE_I4:
177         case MONO_TYPE_U4:
178         case MONO_TYPE_I:
179         case MONO_TYPE_U:
180                 printf ("EAX=%d", eax);
181                 break;
182         case MONO_TYPE_STRING: {
183                 MonoString *s = (MonoString *)eax;
184
185                 if (s) {
186                         g_assert (((MonoObject *)s)->klass == mono_defaults.string_class);
187                         printf ("[STRING:%p:%s]", s, mono_string_to_utf8 (s));
188                 } else 
189                         printf ("[STRING:null], ");
190                 break;
191         }
192         case MONO_TYPE_OBJECT: {
193                 MonoObject *o = (MonoObject *)eax;
194
195                 if (o) {
196                         if (o->klass == mono_defaults.boolean_class) {
197                                 printf ("[BOOLEAN:%p:%d]", o, *((guint8 *)o + sizeof (MonoObject)));            
198                         } else if  (o->klass == mono_defaults.int32_class) {
199                                 printf ("[INT32:%p:%d]", o, *((gint32 *)((gpointer)o + sizeof (MonoObject))));  
200                         } else
201                                 printf ("[%s.%s:%p]", o->klass->name_space, o->klass->name, o);
202                 } else
203                         printf ("[OBJECT:%p]", o);
204                
205                 break;
206         }
207         case MONO_TYPE_CLASS:
208         case MONO_TYPE_PTR:
209         case MONO_TYPE_FNPTR:
210         case MONO_TYPE_ARRAY:
211         case MONO_TYPE_SZARRAY:
212                 printf ("EAX=%p", (gpointer)eax);
213                 break;
214         case MONO_TYPE_I8:
215                 *((gint32 *)&l) = eax;
216                 *((gint32 *)&l + 1) = edx;
217                 printf ("EAX/EDX=%lld", l);
218                 break;
219         case MONO_TYPE_R8:
220                 printf ("FP=%f\n", test);
221                 break;
222         default:
223                 printf ("(unknown return type)");
224         }
225
226         printf ("\n");
227 }
228
229 /**
230  * arch_emit_prologue:
231  * @cfg: pointer to status information
232  *
233  * Emits the function prolog.
234  */
235 static void
236 arch_emit_prologue (MonoFlowGraph *cfg)
237 {
238         x86_push_reg (cfg->code, X86_EBP);
239         x86_mov_reg_reg (cfg->code, X86_EBP, X86_ESP, 4);
240
241         if (cfg->locals_size)
242                 x86_alu_reg_imm (cfg->code, X86_SUB, X86_ESP, cfg->locals_size);
243
244         if (mono_regset_reg_used (cfg->rs, X86_EBX)) 
245                 x86_push_reg (cfg->code, X86_EBX);
246
247         if (mono_regset_reg_used (cfg->rs, X86_EDI)) 
248                 x86_push_reg (cfg->code, X86_EDI);
249
250         if (mono_regset_reg_used (cfg->rs, X86_ESI))
251                 x86_push_reg (cfg->code, X86_ESI);
252
253         if (mono_jit_trace_calls) {
254                 x86_push_reg (cfg->code, X86_EBP);
255                 x86_push_imm (cfg->code, cfg->method);
256                 x86_mov_reg_imm (cfg->code, X86_EAX, enter_method);
257                 x86_call_reg (cfg->code, X86_EAX);
258                 x86_alu_reg_imm (cfg->code, X86_ADD, X86_ESP, 8);
259         }
260 }
261
262 /**
263  * arch_emit_epilogue:
264  * @cfg: pointer to status information
265  *
266  * Emits the function epilog.
267  */
268 static void
269 arch_emit_epilogue (MonoFlowGraph *cfg)
270 {
271         if (mono_jit_trace_calls) {
272                 x86_fld_reg (cfg->code, 0);
273                 x86_alu_reg_imm (cfg->code, X86_SUB, X86_ESP, 8);
274                 x86_fst_membase (cfg->code, X86_ESP, 0, TRUE, TRUE);
275                 x86_push_reg (cfg->code, X86_EAX);
276                 x86_push_reg (cfg->code, X86_EDX);
277                 x86_push_imm (cfg->code, cfg->method);
278                 x86_mov_reg_imm (cfg->code, X86_EAX, leave_method);
279                 x86_call_reg (cfg->code, X86_EAX);
280                 x86_alu_reg_imm (cfg->code, X86_ADD, X86_ESP, 4);
281                 x86_pop_reg (cfg->code, X86_EDX);
282                 x86_pop_reg (cfg->code, X86_EAX);
283                 x86_alu_reg_imm (cfg->code, X86_ADD, X86_ESP, 8);
284         }
285
286         if (mono_regset_reg_used (cfg->rs, X86_ESI))
287                 x86_pop_reg (cfg->code, X86_ESI);
288
289         if (mono_regset_reg_used (cfg->rs, X86_EDI))
290                 x86_pop_reg (cfg->code, X86_EDI);
291
292         if (mono_regset_reg_used (cfg->rs, X86_EBX))
293                 x86_pop_reg (cfg->code, X86_EBX);
294
295         x86_leave (cfg->code);
296         x86_ret (cfg->code);
297 }
298
299 /*
300  * get_unbox_trampoline:
301  * @m: method pointer
302  *
303  * when value type methods are called through the vtable we need to unbox the
304  * this argument. This method returns a pointer to a trampoline which does
305  * unboxing before calling the method
306  */
307 static gpointer
308 get_unbox_trampoline (MonoMethod *m)
309 {
310         gpointer p = arch_compile_method (m);
311         guint8 *code, *start;
312         int this_pos = 4;
313
314         if (!m->signature->ret->byref && m->signature->ret->type == MONO_TYPE_VALUETYPE)
315                 this_pos = 8;
316             
317         start = code = g_malloc (16);
318
319         x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
320         x86_jump_code (code, p);
321         g_assert ((code - start) < 16);
322
323         return start;
324 }
325
326 /**
327  * x86_magic_trampoline:
328  * @eax: saved x86 register 
329  * @ecx: saved x86 register 
330  * @edx: saved x86 register 
331  * @esi: saved x86 register 
332  * @edi: saved x86 register 
333  * @ebx: saved x86 register
334  * @code: pointer into caller code
335  * @method: the method to translate
336  *
337  * This method is called by the trampoline functions for virtual
338  * methods. It inspects the caller code to find the address of the
339  * vtable slot, then calls the JIT compiler and writes the address
340  * of the compiled method back to the vtable. All virtual methods 
341  * are called with: x86_call_membase (inst, basereg, disp). We always
342  * use 32 bit displacement to ensure that the length of the call 
343  * instruction is 6 bytes. We need to get the value of the basereg 
344  * and the constant displacement.
345  */
346 static gpointer
347 x86_magic_trampoline (int eax, int ecx, int edx, int esi, int edi, 
348                       int ebx, guint8 *code, MonoMethod *m)
349 {
350         guint8 ab, reg;
351         gint32 disp;
352         gpointer o;
353
354         /* go to the start of the call instruction */
355         code -= 6;
356         g_assert (*code == 0xff);
357
358         code++;
359         ab = *code;
360         g_assert ((ab >> 6) == 2);
361         
362         /* extract the register number containing the address */
363         reg = ab & 0x07;
364         code++;
365
366         /* extract the displacement */
367         disp = *((gint32*)code);
368
369         switch (reg) {
370         case X86_EAX:
371                 o = (gpointer)eax;
372                 break;
373         case X86_EDX:
374                 o = (gpointer)edx;
375                 break;
376         case X86_ECX:
377                 o = (gpointer)ecx;
378                 break;
379         case X86_ESI:
380                 o = (gpointer)esi;
381                 break;
382         case X86_EDI:
383                 o = (gpointer)edi;
384                 break;
385         case X86_EBX:
386                 o = (gpointer)ebx;
387                 break;
388         default:
389                 g_assert_not_reached ();
390         }
391
392         o += disp;
393
394         if (m->klass->valuetype) {
395                 return *((gpointer *)o) = get_unbox_trampoline (m);
396         } else
397                 return *((gpointer *)o) = arch_compile_method (m);
398 }
399
400 /**
401  * arch_create_jit_trampoline:
402  * @method: pointer to the method info
403  *
404  * Creates a trampoline function for virtual methods. If the created
405  * code is called it first starts JIT compilation of method,
406  * and then calls the newly created method. I also replaces the
407  * corresponding vtable entry (see x86_magic_trampoline).
408  * 
409  * Returns: a pointer to the newly created code 
410  */
411 gpointer
412 arch_create_jit_trampoline (MonoMethod *method)
413 {
414         guint8 *code, *buf;
415         static guint8 *vc = NULL;
416
417         if (method->addr)
418                 return method->addr;
419
420         if (!vc) {
421                 vc = buf = g_malloc (24);
422
423                 /* push the return address onto the stack */
424                 x86_push_membase (buf, X86_ESP, 4);
425
426                 /* save all register values */
427                 x86_push_reg (buf, X86_EBX);
428                 x86_push_reg (buf, X86_EDI);
429                 x86_push_reg (buf, X86_ESI);
430                 x86_push_reg (buf, X86_EDX);
431                 x86_push_reg (buf, X86_ECX);
432                 x86_push_reg (buf, X86_EAX);
433
434                 x86_call_code (buf, x86_magic_trampoline);
435                 x86_alu_reg_imm (buf, X86_ADD, X86_ESP, 8*4);
436
437                 /* call the compiled method */
438                 x86_jump_reg (buf, X86_EAX);
439
440                 g_assert ((buf - vc) <= 24);
441         }
442
443         code = buf = g_malloc (16);
444         x86_push_imm (buf, method);
445         x86_jump_code (buf, vc);
446         g_assert ((buf - code) <= 16);
447
448         return code;
449 }
450
451 /**
452  * arch_create_simple_jit_trampoline:
453  * @method: pointer to the method info
454  *
455  * Creates a trampoline function for method. If the created
456  * code is called it first starts JIT compilation of method,
457  * and then calls the newly created method. I also replaces the
458  * address in method->addr with the result of the JIT 
459  * compilation step (in arch_compile_method).
460  * 
461  * Returns: a pointer to the newly created code 
462  */
463 gpointer
464 arch_create_simple_jit_trampoline (MonoMethod *method)
465 {
466         guint8 *code, *buf;
467
468         if (method->addr)
469                 return method->addr;
470
471         /* we never free the allocated code buffer */
472         code = buf = g_malloc (16);
473         x86_push_imm (buf, method);
474         x86_call_code (buf, arch_compile_method);
475         x86_alu_reg_imm (buf, X86_ADD, X86_ESP, 4);
476         /* jump to the compiled method */
477         x86_jump_reg (buf, X86_EAX);
478         g_assert ((buf - code) < 16);
479
480         return code;
481 }
482
483 static void
484 mono_label_cfg (MonoFlowGraph *cfg)
485 {
486         int i, j;
487         
488         for (i = 0; i < cfg->block_count; i++) {
489                 GPtrArray *forest = cfg->bblocks [i].forest;
490                 const int top = forest->len;
491
492                 for (j = 0; j < top; j++) {
493                         MBTree *t1 = (MBTree *) g_ptr_array_index (forest, j);
494                         MBState *mbstate;
495
496                         mbstate =  mono_burg_label (t1, cfg);
497                         if (!mbstate) {
498                                 cfg->invalid = 1;
499                                 if (mono_debug_handle)
500                                         return;
501                                 g_warning ("tree does not match");
502                                 mono_print_ctree (t1); printf ("\n\n");
503
504                                 mono_print_forest (forest);
505                                 g_assert_not_reached ();
506                         }
507                 }
508         }
509 }
510
511 static void
512 tree_preallocate_regs (MBTree *tree, int goal, MonoRegSet *rs) 
513 {
514         switch (tree->op) {
515         case MB_TERM_CALL_I4:
516         case MB_TERM_CALL_I8:
517         case MB_TERM_CALL_R8:
518 //      case MB_TERM_CALL_VOID :
519                 tree->reg1 = mono_regset_alloc_reg (rs, X86_EAX, tree->exclude_mask);
520                 tree->reg2 = mono_regset_alloc_reg (rs, X86_EDX, tree->exclude_mask);
521                 tree->reg3 = mono_regset_alloc_reg (rs, X86_ECX, tree->exclude_mask);
522                 return;
523         default: break;
524         }
525
526         switch (goal) {
527         case MB_NTERM_reg:
528         case MB_NTERM_lreg: {
529                 switch (tree->op) {
530                 case MB_TERM_SHL:
531                 case MB_TERM_SHR:
532                 case MB_TERM_SHR_UN:
533                         tree->exclude_mask |= (1 << X86_ECX);
534                         tree->left->exclude_mask |= (1 << X86_ECX);
535                         break;
536                 case MB_TERM_MUL:
537                 case MB_TERM_MUL_OVF:
538                 case MB_TERM_MUL_OVF_UN:
539                 case MB_TERM_DIV:
540                 case MB_TERM_DIV_UN:
541                 case MB_TERM_REM:
542                 case MB_TERM_REM_UN:
543                         tree->reg1 = mono_regset_alloc_reg (rs, X86_EAX, tree->exclude_mask);
544                         tree->reg2 = mono_regset_alloc_reg (rs, X86_EDX, tree->exclude_mask);
545                         if (goal == MB_NTERM_reg) {
546                                 tree->left->exclude_mask |= (1 << X86_EDX);
547                                 tree->right->exclude_mask |= (1 << X86_EDX) | (1 << X86_EAX);
548                         }
549                         break;
550                 default:
551                         break;
552                 }
553                 break;
554         }
555         default:
556                 break;
557         }
558 }
559
560 static void
561 tree_allocate_regs (MBTree *tree, int goal, MonoRegSet *rs) 
562 {
563         MBTree *kids[10];
564         int ern = mono_burg_rule (tree->state, goal);
565         guint16 *nts = mono_burg_nts [ern];
566         int i;
567         
568         mono_burg_kids (tree, ern, kids);
569
570         //printf ("RALLOC START %d %p %d\n",  tree->op, rs->free_mask, goal);
571
572         if (nts [0] && kids [0] == tree) {
573                 /* chain rule */
574                 tree_allocate_regs (kids [0], nts [0], rs);
575                 return;
576         }
577
578         for (i = 0; nts [i]; i++)
579                 tree_preallocate_regs (kids [i], nts [i], rs);
580
581         for (i = 0; nts [i]; i++)
582                 tree_allocate_regs (kids [i], nts [i], rs);
583
584         for (i = 0; nts [i]; i++) {
585                 mono_regset_free_reg (rs, kids [i]->reg1);
586                 mono_regset_free_reg (rs, kids [i]->reg2);
587                 mono_regset_free_reg (rs, kids [i]->reg3);
588         }
589
590         switch (goal) {
591         case MB_NTERM_reg:
592                 if (tree->reg1 < 0) { 
593                         tree->reg1 = mono_regset_alloc_reg (rs, -1, tree->exclude_mask);
594                         g_assert (tree->reg1 != -1);
595                 }
596                 break;
597
598         case MB_NTERM_lreg:
599                 if (tree->reg1 < 0) { 
600                         tree->reg1 = mono_regset_alloc_reg (rs, -1, tree->exclude_mask);
601                         g_assert (tree->reg1 != -1);
602                 }
603                 if (tree->reg2 < 0) { 
604                         tree->reg2 = mono_regset_alloc_reg (rs, -1, tree->exclude_mask);
605                         g_assert (tree->reg2 != -1);
606                 }
607                 break;
608
609         case MB_NTERM_freg:
610                 /* fixme: allocate floating point registers */
611                 break;
612       
613         case MB_NTERM_addr:
614                 if (tree->op == MB_TERM_ADD) {
615                         tree->reg1 = mono_regset_alloc_reg (rs, tree->left->reg1, tree->exclude_mask);
616                         tree->reg2 = mono_regset_alloc_reg (rs, tree->right->reg1, tree->exclude_mask);
617                 }
618                 break;
619                 
620         case MB_NTERM_base:
621                 if (tree->op == MB_TERM_ADD) {
622                         tree->reg1 = mono_regset_alloc_reg (rs, tree->left->reg1, tree->exclude_mask);
623                 }
624                 break;
625                
626         case MB_NTERM_index:
627                 if (tree->op == MB_TERM_SHL ||
628                     tree->op == MB_TERM_MUL) {
629                         tree->reg1 = mono_regset_alloc_reg (rs, tree->left->reg1, tree->exclude_mask);
630                 }
631                 break;
632                
633         default:
634                 /* do nothing */
635         }
636
637         //printf ("RALLOC END %d %p\n",  tree->op, rs->free_mask);
638         tree->emit = mono_burg_func [ern];
639 }
640
641 static void
642 arch_allocate_regs (MonoFlowGraph *cfg)
643 {
644         int i, j;
645         
646         for (i = 0; i < cfg->block_count; i++) {
647                 GPtrArray *forest = cfg->bblocks [i].forest;
648                 const int top = forest->len;
649
650                 for (j = 0; j < top; j++) {
651                         MBTree *t1 = (MBTree *) g_ptr_array_index (forest, j);
652                         //printf ("AREGSTART %d:%d %p\n", i, j, cfg->rs->free_mask);
653                         tree_allocate_regs (t1, 1, cfg->rs);
654                         //printf ("AREGENDT %d:%d %p\n", i, j, cfg->rs->free_mask);
655                         g_assert (cfg->rs->free_mask == 0xffffffff);
656                 }
657         }
658 }
659
660 static void
661 tree_emit (int goal, MonoFlowGraph *cfg, MBTree *tree) 
662 {
663         MBTree *kids[10];
664         int i, ern = mono_burg_rule (tree->state, goal);
665         guint16 *nts = mono_burg_nts [ern];
666         MBEmitFunc emit;
667         int offset;
668
669         mono_burg_kids (tree, ern, kids);
670
671         for (i = 0; nts [i]; i++) 
672                 tree_emit (nts [i], cfg, kids [i]);
673
674         tree->addr = offset = cfg->code - cfg->start;
675
676         // we assume an instruction uses a maximum of 128 bytes
677         if ((cfg->code_size - offset) <= 128) {
678                 int add = MIN ((cfg->code_size * 2), 1024);
679
680                 cfg->code_size += add;
681                 cfg->start = g_realloc (cfg->start, cfg->code_size);
682                 g_assert (cfg->start);
683                 cfg->code = cfg->start + offset;
684         }
685
686         if ((emit = mono_burg_func [ern]))
687                 emit (tree, cfg);
688
689         g_assert ((cfg->code - cfg->start) < cfg->code_size);
690 }
691
692 static void
693 mono_emit_cfg (MonoFlowGraph *cfg)
694 {
695         int i, j;
696
697         for (i = 0; i < cfg->block_count; i++) {
698                 MonoBBlock *bb = &cfg->bblocks [i];
699                 GPtrArray *forest = bb->forest;
700                 const int top = forest->len;
701
702                 bb->addr = cfg->code - cfg->start;
703           
704                 for (j = 0; j < top; j++) {
705                         MBTree *t1 = (MBTree *) g_ptr_array_index (forest, j);
706                         
707                         tree_emit (1, cfg, t1);
708                 }
709         }
710                 
711         cfg->epilog = cfg->code - cfg->start;
712 }
713
714 static void
715 mono_compute_branches (MonoFlowGraph *cfg)
716 {
717         guint8 *end;
718         int i, j;
719
720         end = cfg->code;
721
722         for (j = 0; j < cfg->block_count; j++) {
723                 MonoBBlock *bb = &cfg->bblocks [j];
724                 GPtrArray *forest = bb->forest;
725                 const int top = forest->len;
726         
727                 for (i = 0; i < top; i++) {
728                         MBTree *t1 = (MBTree *) g_ptr_array_index (forest, i);
729
730                         if (t1->is_jump) {
731
732                                 if (t1->op == MB_TERM_SWITCH) {
733                                         MonoBBlock **jt = (MonoBBlock **)t1->data.p;
734                                         guint32 *rt = (guint32 *)t1->data.p;
735
736                                         int m = *((guint32 *)t1->data.p) + 1;
737                                         int j;
738                                         
739                                         for (j = 1; j <= m; j++)
740                                                 rt [j] = (int)(jt [j]->addr + cfg->start);
741                                 }
742
743                                 /* emit the jump instruction again to update addresses */
744                                 cfg->code = cfg->start + t1->addr;
745                                 ((MBEmitFunc)t1->emit) (t1, cfg);
746
747                         }
748                 }
749         }
750
751         cfg->code = end;
752 }
753
754 static int
755 match_debug_method (MonoMethod* method)
756 {
757         GList *tmp = mono_debug_methods;
758
759         for (; tmp; tmp = tmp->next) {
760                 if (strcmp (method->name, tmp->data) == 0) {
761                         return 1;
762                 }
763         }
764         return 0;
765 }
766
767 /**
768  * arch_compile_method:
769  * @method: pointer to the method info
770  *
771  * JIT compilation of a single method. This method also writes the result 
772  * back to method->addr, an thus overwrites the trampoline function.
773  *
774  * Returns: a pointer to the newly created code.
775  */
776 gpointer
777 arch_compile_method (MonoMethod *method)
778 {
779         MonoFlowGraph *cfg;
780         MonoMemPool *mp = mono_mempool_new ();
781
782         g_assert (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL));
783         g_assert (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL));
784
785         if (mono_jit_trace_calls || mono_jit_dump_asm || mono_jit_dump_forest) {
786                 printf ("Start JIT compilation of %s.%s:%s\n", method->klass->name_space,
787                         method->klass->name, method->name);
788         }
789
790         if (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) {
791                 MonoClassField *field;
792                 const char *name = method->name;
793                 static guint target_offset = 0;
794                 static guint method_offset = 0;
795                 guint8 *code;
796                 gboolean delegate = FALSE;
797
798                 if (method->klass->parent && 
799                     method->klass->parent->parent == mono_defaults.delegate_class)
800                         delegate = TRUE;
801                                 
802                 if (!target_offset) {
803                         mono_class_init (mono_defaults.delegate_class);
804
805                         field = mono_class_get_field_from_name (mono_defaults.delegate_class, "m_target");
806                         target_offset = field->offset;
807                         field = mono_class_get_field_from_name (mono_defaults.delegate_class, "method_ptr");
808                         method_offset = field->offset;
809                 }
810                 
811                 if (delegate && *name == '.' && (strcmp (name, ".ctor") == 0)) {
812                         method->addr = code = g_malloc (32);
813                         x86_push_reg (code, X86_EBP);
814                         x86_mov_reg_reg (code, X86_EBP, X86_ESP, 4);
815                         
816                         /* load the this pointer */
817                         x86_mov_reg_membase (code, X86_EAX, X86_EBP, 8, 4); 
818                         /* load m_target arg */
819                         x86_mov_reg_membase (code, X86_EDX, X86_EBP, 12, 4);
820                         /* store mtarget */
821                         x86_mov_membase_reg (code, X86_EAX, target_offset, X86_EDX, 4); 
822                         /* load method_ptr arg */
823                         x86_mov_reg_membase (code, X86_EDX, X86_EBP, 16, 4);
824                         /* store method_ptr */
825                         x86_mov_membase_reg (code, X86_EAX, method_offset, X86_EDX, 4); 
826
827                         x86_leave (code);
828                         x86_ret (code);
829
830                         g_assert ((code - (guint8*)method->addr) < 32);
831
832                 } else if (delegate && *name == 'I' && (strcmp (name, "Invoke") == 0)) {
833                         MonoMethodSignature *csig = method->signature;
834                         int i, target, this_pos = 4;
835                         guint8 *source;
836
837                         method->addr = g_malloc (64);
838
839                         if (csig->ret->type == MONO_TYPE_VALUETYPE) {
840                                 g_assert (!csig->ret->byref);
841                                 this_pos = 8;
842                         }
843
844                         for (i = 0; i < 2; i ++) {
845                                 code = method->addr;
846                                 /* load the this pointer */
847                                 x86_mov_reg_membase (code, X86_EAX, X86_ESP, this_pos, 4);
848                                 /* load mtarget */
849                                 x86_mov_reg_membase (code, X86_EDX, X86_EAX, target_offset, 4); 
850                                 /* check if zero (static method call without this pointer) */
851                                 x86_alu_reg_imm (code, X86_CMP, X86_EDX, 0);
852                                 x86_branch32 (code, X86_CC_EQ, target, TRUE); 
853                                 source = code;
854
855                                 /* virtual delegate methods: we have to replace the this pointer 
856                                  * withe the actual target */
857                                 x86_mov_membase_reg (code, X86_ESP, this_pos, X86_EDX, 4); 
858                                 /* jump to method_ptr() */
859                                 x86_jump_membase (code, X86_EAX, method_offset);
860
861                                 /* static delegate methods: we have to remove the this pointer 
862                                  * from the activation frame */
863                                 target = code - source;
864                                 if (this_pos == 8) {
865                                         x86_mov_reg_membase (code, X86_EDX, X86_ESP, 4, 4);
866                                         x86_mov_membase_reg (code, X86_ESP, 8, X86_EDX, 4);
867                                 }
868                                 x86_mov_reg_membase (code, X86_EDX, X86_ESP, 0, 4);
869                                 x86_mov_membase_reg (code, X86_ESP, 4, X86_EDX, 4);
870                                 x86_alu_reg_imm (code, X86_ADD, X86_ESP, 4);
871
872                                 /* jump to method_ptr() */
873                                 x86_jump_membase (code, X86_EAX, method_offset);
874                         }
875
876                         g_assert ((code - (guint8*)method->addr) < 64);
877
878                 } else {
879                         if (mono_debug_handle)
880                                 return NULL;
881                         g_error ("Don't know how to exec runtime method %s.%s::%s", 
882                                  method->klass->name_space, method->klass->name, method->name);
883                 }
884         
885         } else {
886                 MonoMethodHeader *header = ((MonoMethodNormal *)method)->header;
887                 MonoJitInfo *ji = g_new0 (MonoJitInfo, 1);
888                 
889                 cfg = mono_cfg_new (method, mp);
890
891                 mono_analyze_flow (cfg);
892                 if (cfg->invalid)
893                         return NULL;
894
895                 mono_analyze_stack (cfg);
896                 if (cfg->invalid)
897                         return NULL;
898         
899                 cfg->rs = mono_regset_new (X86_NREG);
900                 mono_regset_reserve_reg (cfg->rs, X86_ESP);
901                 mono_regset_reserve_reg (cfg->rs, X86_EBP);
902
903                 cfg->code_size = 256;
904                 cfg->start = cfg->code = g_malloc (cfg->code_size);
905
906                 if (match_debug_method (method))
907                         x86_breakpoint (cfg->code);
908
909                 if (mono_jit_dump_forest) {
910                         int i;
911                         printf ("FOREST %s.%s:%s\n", method->klass->name_space,
912                                 method->klass->name, method->name);
913                         for (i = 0; i < cfg->block_count; i++) {
914                                 printf ("BLOCK %d:\n", i);
915                                 mono_print_forest (cfg->bblocks [i].forest);
916                         }
917                 }
918         
919                 mono_label_cfg (cfg);
920                 if (cfg->invalid)
921                         return NULL;
922
923                 arch_allocate_regs (cfg);
924
925                 /* align to 8 byte boundary */
926                 cfg->locals_size += 7;
927                 cfg->locals_size &= ~7;
928
929                 arch_emit_prologue (cfg);
930                 mono_emit_cfg (cfg);
931                 arch_emit_epilogue (cfg);               
932
933                 method->addr = cfg->start;
934
935                 mono_compute_branches (cfg);
936                 
937                 if (mono_jit_dump_asm) {
938                         char *id = g_strdup_printf ("%s.%s_%s", method->klass->name_space,
939                                                     method->klass->name, method->name);
940                         mono_disassemble_code (cfg->start, cfg->code - cfg->start, id);
941                         g_free (id);
942                 }
943                 if (mono_debug_handle)
944                         mono_debug_add_method (mono_debug_handle, cfg);
945
946                 ji->code_size = cfg->code - cfg->start;
947                 ji->used_regs = cfg->rs->used_mask;
948                 ji->method = method;
949                 ji->code_start = method->addr;
950                 mono_jit_info_table_add (mono_jit_info_table, ji);
951
952                 if (header->num_clauses) {
953                         int i, start_block, end_block;
954
955                         ji->num_clauses = header->num_clauses;
956                         ji->clauses = g_new0 (MonoJitExceptionInfo, header->num_clauses);
957
958                         for (i = 0; i < header->num_clauses; i++) {
959                                 MonoExceptionClause *ec = &header->clauses [i];
960                                 MonoJitExceptionInfo *ei = &ji->clauses [i];
961                         
962                                 ei->flags = ec->flags;
963                                 ei->token_or_filter = ec->token_or_filter;
964
965                                 g_assert (cfg->bcinfo [ec->try_offset].is_block_start);
966                                 start_block = cfg->bcinfo [ec->try_offset].block_id;
967                                 end_block = cfg->bcinfo [ec->try_offset + ec->try_len].block_id;
968                                 g_assert (cfg->bcinfo [ec->try_offset + ec->try_len].is_block_start);
969                                 
970                                 ei->try_start = cfg->start + cfg->bblocks [start_block].addr;
971                                 ei->try_end = cfg->start + cfg->bblocks [end_block].addr;
972                                 
973                                 g_assert (cfg->bcinfo [ec->handler_offset].is_block_start);
974                                 start_block = cfg->bcinfo [ec->handler_offset].block_id;
975                                 ei->handler_start = cfg->start + cfg->bblocks [start_block].addr;       
976                                 
977                                 //printf ("TEST %x %x %x\n", ei->try_start, ei->try_end, ei->handler_start);
978                         }
979                 }
980                 
981                 mono_regset_free (cfg->rs);
982
983                 mono_cfg_free (cfg);
984
985                 mono_mempool_destroy (mp);
986
987         }
988
989         if (mono_jit_trace_calls || mono_jit_dump_asm || mono_jit_dump_forest) {
990                 printf ("END JIT compilation of %s.%s:%s %p %p\n", method->klass->name_space,
991                         method->klass->name, method->name, method, method->addr);
992         }
993
994
995         return method->addr;
996 }
997
998 /*
999  * arch_get_restore_context:
1000  *
1001  * Returns a pointer to a method which restores a previously saved sigcontext.
1002  */
1003 static gpointer
1004 arch_get_restore_context ()
1005 {
1006         static guint8 *start = NULL;
1007         guint8 *code;
1008
1009         if (start)
1010                 return start;
1011
1012         /* restore_contect (struct sigcontext *ctx) */
1013         /* we do not restore X86_EAX, X86_EDX */
1014
1015         start = code = malloc (1024);
1016         
1017         /* load ctx */
1018         x86_mov_reg_membase (code, X86_EAX, X86_ESP, 4, 4);
1019
1020         /* get return address, stored in EDX */
1021         x86_mov_reg_membase (code, X86_EDX, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, eip), 4);
1022
1023         /* restore EBX */
1024         x86_mov_reg_membase (code, X86_EBX, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, ebx), 4);
1025         /* restore EDI */
1026         x86_mov_reg_membase (code, X86_EDI, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, edi), 4);
1027         /* restore ESI */
1028         x86_mov_reg_membase (code, X86_ESI, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, esi), 4);
1029         /* restore ESP */
1030         x86_mov_reg_membase (code, X86_ESP, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, esp), 4);
1031         /* restore EBP */
1032         x86_mov_reg_membase (code, X86_EBP, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, ebp), 4);
1033         /* restore ECX. the exception object is passed here to the catch handler */
1034         x86_mov_reg_membase (code, X86_ECX, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, ecx), 4);
1035
1036         /* jump to the saved IP */
1037         x86_jump_reg (code, X86_EDX);
1038
1039         return start;
1040 }
1041
1042 /*
1043  * arch_get_call_finally:
1044  *
1045  * Returns a pointer to a method which calls a finally handler.
1046  */
1047 static gpointer
1048 arch_get_call_finally ()
1049 {
1050         static guint8 *start = NULL;
1051         guint8 *code;
1052
1053         if (start)
1054                 return start;
1055
1056         /* call_finally (struct sigcontext *ctx, unsigned long eip) */
1057         start = code = malloc (1024);
1058
1059         x86_push_reg (code, X86_EBP);
1060         x86_mov_reg_reg (code, X86_EBP, X86_ESP, 4);
1061         x86_push_reg (code, X86_EBX);
1062         x86_push_reg (code, X86_EDI);
1063         x86_push_reg (code, X86_ESI);
1064
1065         /* load ctx */
1066         x86_mov_reg_membase (code, X86_EAX, X86_EBP, 8, 4);
1067         /* load eip */
1068         x86_mov_reg_membase (code, X86_ECX, X86_EBP, 12, 4);
1069         /* save EBP */
1070         x86_push_reg (code, X86_EBP);
1071         /* set new EBP */
1072         x86_mov_reg_membase (code, X86_EBP, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, ebp), 4);
1073         /* call the handler */
1074         x86_call_reg (code, X86_ECX);
1075         /* restore EBP */
1076         x86_pop_reg (code, X86_EBP);
1077         /* restore saved regs */
1078         x86_pop_reg (code, X86_ESI);
1079         x86_pop_reg (code, X86_EDI);
1080         x86_pop_reg (code, X86_EBX);
1081         x86_leave (code);
1082         x86_ret (code);
1083
1084         return start;
1085 }
1086
1087 /**
1088  * arch_handle_exception:
1089  * @ctx: saved processor state
1090  * @obj:
1091  */
1092 void
1093 arch_handle_exception (struct sigcontext *ctx, gpointer obj)
1094 {
1095         MonoJitInfo *ji;
1096         gpointer ip = (gpointer)ctx->eip;
1097         static void (*restore_context) (struct sigcontext *);
1098         static void (*call_finally) (struct sigcontext *, unsigned long);
1099        
1100         g_assert (ctx != NULL);
1101         g_assert (obj != NULL);
1102
1103         ji = mono_jit_info_table_find (mono_jit_info_table, ip);
1104
1105         if (!restore_context)
1106                 restore_context = arch_get_restore_context ();
1107         
1108         if (!call_finally)
1109                 call_finally = arch_get_call_finally ();
1110
1111         if (ji) { /* we are inside managed code */
1112                 MonoMethod *m = ji->method;
1113                 unsigned next_bp;
1114                 int offset = 2;
1115
1116                 if (ji->num_clauses) {
1117                         int i;
1118
1119                         g_assert (ji->clauses);
1120                         
1121                         for (i = 0; i < ji->num_clauses; i++) {
1122                                 MonoJitExceptionInfo *ei = &ji->clauses [i];
1123
1124                                 if (ei->try_start <= ip && ip <= (ei->try_end)) { 
1125                                         /* catch block */
1126                                         if (ei->flags == 0 && mono_object_isinst (obj, 
1127                                                 mono_class_get (m->klass->image, ei->token_or_filter))) {
1128                                         
1129                                                 ctx->eip = (unsigned long)ei->handler_start;
1130                                                 ctx->ecx = (unsigned long)obj;
1131                                                 restore_context (ctx);
1132                                                 g_assert_not_reached ();
1133                                         }
1134                                 }
1135                         }
1136
1137                         /* no handler found - we need to call all finally handlers */
1138                         for (i = 0; i < ji->num_clauses; i++) {
1139                                 MonoJitExceptionInfo *ei = &ji->clauses [i];
1140
1141                                 if (ei->try_start <= ip && ip < (ei->try_end) &&
1142                                     (ei->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
1143                                         call_finally (ctx, (unsigned long)ei->handler_start);
1144                                 }
1145                         }
1146                 }
1147
1148                 if (mono_object_isinst (obj, mono_defaults.exception_class)) {
1149                         char  *strace = mono_string_to_utf8 (((MonoException*)obj)->stack_trace);
1150                         char  *tmp;
1151
1152                         if (!strcmp (strace, "TODO: implement stack traces"))
1153                                 strace = g_strdup ("");
1154
1155                         tmp = g_strdup_printf ("%sin %s.%s:%s ()\n", strace, m->klass->name_space,  
1156                                                m->klass->name, m->name);
1157
1158                         g_free (strace);
1159
1160                         ((MonoException*)obj)->stack_trace = mono_string_new (tmp);
1161                         g_free (tmp);
1162                 }
1163
1164                 /* continue unwinding */
1165
1166                 /* restore caller saved registers */
1167                 if (ji->used_regs & X86_ESI_MASK) {
1168                         ctx->esi = *((int *)ctx->ebp + offset);
1169                         offset++;
1170                 }
1171                 if (ji->used_regs & X86_EDI_MASK) {
1172                         ctx->edi = *((int *)ctx->ebp + offset);
1173                         offset++;
1174                 }
1175                 if (ji->used_regs & X86_EBX_MASK) {
1176                         ctx->ebx = *((int *)ctx->ebp + offset);
1177                 }
1178
1179                 ctx->esp = ctx->ebp;
1180                 ctx->eip = *((int *)ctx->ebp + 1);
1181                 ctx->ebp = *((int *)ctx->ebp);
1182                 
1183                 if (next_bp < (unsigned)mono_end_of_stack)
1184                         arch_handle_exception (ctx, obj);
1185                 else
1186                         mono_jit_abort (obj);
1187
1188         } else {
1189                 gpointer *lmf_addr = TlsGetValue (lmf_thread_id);
1190                 MonoLMF *lmf;
1191                 MonoMethod *m;
1192
1193                 g_assert (lmf_addr);
1194                 lmf = *((MonoLMF **)lmf_addr);
1195
1196                 if (!lmf)
1197                         mono_jit_abort (obj);
1198
1199                 m = lmf->method;
1200
1201                 *lmf_addr = lmf->previous_lmf;
1202
1203                 ctx->esi = lmf->esi;
1204                 ctx->edi = lmf->edi;
1205                 ctx->ebx = lmf->ebx;
1206                 ctx->ebp = lmf->ebp;
1207                 ctx->eip = lmf->eip;
1208                 ctx->esp = (unsigned long)lmf;
1209
1210                 if (mono_object_isinst (obj, mono_defaults.exception_class)) {
1211                         char  *strace = mono_string_to_utf8 (((MonoException*)obj)->stack_trace);
1212                         char  *tmp;
1213
1214                         if (!strcmp (strace, "TODO: implement stack traces"))
1215                                 strace = g_strdup ("");
1216
1217                         tmp = g_strdup_printf ("%sin (unmanaged) %s.%s:%s ()\n", strace, m->klass->name_space,  
1218                                                m->klass->name, m->name);
1219
1220                         g_free (strace);
1221
1222                         ((MonoException*)obj)->stack_trace = mono_string_new (tmp);
1223                         g_free (tmp);
1224                 }
1225
1226                 if (ctx->eip < (unsigned)mono_end_of_stack)
1227                         arch_handle_exception (ctx, obj);
1228                 else
1229                         mono_jit_abort (obj);
1230         }
1231
1232         g_assert_not_reached ();
1233 }
1234
1235 static void
1236 throw_exception (unsigned long eax, unsigned long ecx, unsigned long edx, unsigned long ebx,
1237                  unsigned long esi, unsigned long edi, unsigned long ebp, MonoObject *exc,
1238                  unsigned long eip,  unsigned long esp)
1239 {
1240         struct sigcontext ctx;
1241         
1242         ctx.esp = esp;
1243         ctx.eip = eip;
1244         ctx.ebp = ebp;
1245         ctx.edi = edi;
1246         ctx.esi = esi;
1247         ctx.ebx = ebx;
1248         ctx.edx = edx;
1249         ctx.ecx = ecx;
1250         ctx.eax = eax;
1251         
1252         arch_handle_exception (&ctx, exc);
1253
1254         g_assert_not_reached ();
1255 }
1256
1257 gpointer 
1258 arch_get_throw_exception (void)
1259 {
1260         static guint8 *start = NULL;
1261         guint8 *code;
1262
1263         if (start)
1264                 return start;
1265
1266         code = start = g_malloc (1024);
1267
1268         x86_push_reg (code, X86_ESP);
1269         x86_push_membase (code, X86_ESP, 4); /* IP */
1270         x86_push_membase (code, X86_ESP, 12); /* exception */
1271         x86_push_reg (code, X86_EBP);
1272         x86_push_reg (code, X86_EDI);
1273         x86_push_reg (code, X86_ESI);
1274         x86_push_reg (code, X86_EBX);
1275         x86_push_reg (code, X86_EDX);
1276         x86_push_reg (code, X86_ECX);
1277         x86_push_reg (code, X86_EAX);
1278         x86_call_code (code, throw_exception);
1279         /* we should never reach this breakpoint */
1280         x86_breakpoint (code);
1281
1282         return start;
1283 }
1284
1285
1286
1287