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