Sat Feb 16 16:27:42 CET 2002 Paolo Molaro <lupus@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         
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->vtable->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)->vtable->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->vtable->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)->vtable->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->vtable->klass == mono_defaults.boolean_class) {
197                                 printf ("[BOOLEAN:%p:%d]", o, *((guint8 *)o + sizeof (MonoObject)));            
198                         } else if  (o->vtable->klass == mono_defaults.int32_class) {
199                                 printf ("[INT32:%p:%d]", o, *((gint32 *)((gpointer)o + sizeof (MonoObject))));  
200                         } else
201                                 printf ("[%s.%s:%p]", o->vtable->klass->name_space, o->vtable->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, const guint8 *code, MonoMethod *m)
349 {
350         guint8 reg;
351         gint32 disp;
352         gpointer o;
353
354         /* go to the start of the call instruction
355          *
356          * address_byte = (m << 6) | (o << 3) | reg
357          * call opcode: 0xff address_byte displacement
358          * 0xff m=1,o=2 imm8
359          * 0xff m=2,o=2 imm32
360          */
361         code -= 6;
362         if ((code [3] == 0xff) && ((code [4] & 0x18) == 0x10) && ((code [4] >> 6) == 1)) {
363                 reg = code [4] & 0x07;
364                 disp = (signed char)code [5];
365         } else {
366                 if ((code [0] == 0xff) && ((code [1] & 0x18) == 0x10) && ((code [1] >> 6) == 2)) {
367                         reg = code [1] & 0x07;
368                         disp = *((gint32*)(code + 2));
369                 } else {
370                         g_assert_not_reached ();
371                 }
372         }
373
374         switch (reg) {
375         case X86_EAX:
376                 o = (gpointer)eax;
377                 break;
378         case X86_EDX:
379                 o = (gpointer)edx;
380                 break;
381         case X86_ECX:
382                 o = (gpointer)ecx;
383                 break;
384         case X86_ESI:
385                 o = (gpointer)esi;
386                 break;
387         case X86_EDI:
388                 o = (gpointer)edi;
389                 break;
390         case X86_EBX:
391                 o = (gpointer)ebx;
392                 break;
393         default:
394                 g_assert_not_reached ();
395         }
396
397         o += disp;
398
399         if (m->klass->valuetype) {
400                 return *((gpointer *)o) = get_unbox_trampoline (m);
401         } else
402                 return *((gpointer *)o) = arch_compile_method (m);
403 }
404
405 /**
406  * arch_create_jit_trampoline:
407  * @method: pointer to the method info
408  *
409  * Creates a trampoline function for virtual methods. If the created
410  * code is called it first starts JIT compilation of method,
411  * and then calls the newly created method. I also replaces the
412  * corresponding vtable entry (see x86_magic_trampoline).
413  * 
414  * Returns: a pointer to the newly created code 
415  */
416 gpointer
417 arch_create_jit_trampoline (MonoMethod *method)
418 {
419         guint8 *code, *buf;
420         static guint8 *vc = NULL;
421
422         if (method->addr)
423                 return method->addr;
424
425         if (!vc) {
426                 vc = buf = g_malloc (24);
427
428                 /* push the return address onto the stack */
429                 x86_push_membase (buf, X86_ESP, 4);
430
431                 /* save all register values */
432                 x86_push_reg (buf, X86_EBX);
433                 x86_push_reg (buf, X86_EDI);
434                 x86_push_reg (buf, X86_ESI);
435                 x86_push_reg (buf, X86_EDX);
436                 x86_push_reg (buf, X86_ECX);
437                 x86_push_reg (buf, X86_EAX);
438
439                 x86_call_code (buf, x86_magic_trampoline);
440                 x86_alu_reg_imm (buf, X86_ADD, X86_ESP, 8*4);
441
442                 /* call the compiled method */
443                 x86_jump_reg (buf, X86_EAX);
444
445                 g_assert ((buf - vc) <= 24);
446         }
447
448         code = buf = g_malloc (16);
449         x86_push_imm (buf, method);
450         x86_jump_code (buf, vc);
451         g_assert ((buf - code) <= 16);
452
453         return code;
454 }
455
456 /**
457  * arch_create_simple_jit_trampoline:
458  * @method: pointer to the method info
459  *
460  * Creates a trampoline function for method. If the created
461  * code is called it first starts JIT compilation of method,
462  * and then calls the newly created method. I also replaces the
463  * address in method->addr with the result of the JIT 
464  * compilation step (in arch_compile_method).
465  * 
466  * Returns: a pointer to the newly created code 
467  */
468 gpointer
469 arch_create_simple_jit_trampoline (MonoMethod *method)
470 {
471         guint8 *code, *buf;
472
473         if (method->addr)
474                 return method->addr;
475
476         /* we never free the allocated code buffer */
477         code = buf = g_malloc (16);
478         x86_push_imm (buf, method);
479         x86_call_code (buf, arch_compile_method);
480         x86_alu_reg_imm (buf, X86_ADD, X86_ESP, 4);
481         /* jump to the compiled method */
482         x86_jump_reg (buf, X86_EAX);
483         g_assert ((buf - code) < 16);
484
485         return code;
486 }
487
488 static void
489 mono_label_cfg (MonoFlowGraph *cfg)
490 {
491         int i, j;
492         
493         for (i = 0; i < cfg->block_count; i++) {
494                 GPtrArray *forest = cfg->bblocks [i].forest;
495                 int top;
496
497                 if (!cfg->bblocks [i].reached) /* unreachable code */
498                         continue;
499                 
500                 top = forest->len;
501
502                 for (j = 0; j < top; j++) {
503                         MBTree *t1 = (MBTree *) g_ptr_array_index (forest, j);
504                         MBState *mbstate;
505
506                         mbstate =  mono_burg_label (t1, cfg);
507                         if (!mbstate) {
508                                 cfg->invalid = 1;
509                                 if (mono_debug_handle)
510                                         return;
511                                 g_warning ("tree does not match");
512                                 mono_print_ctree (t1); printf ("\n\n");
513
514                                 mono_print_forest (forest);
515                                 g_assert_not_reached ();
516                         }
517                 }
518         }
519 }
520
521 static void
522 tree_preallocate_regs (MBTree *tree, int goal, MonoRegSet *rs) 
523 {
524         switch (tree->op) {
525         case MB_TERM_CALL_I4:
526         case MB_TERM_CALL_I8:
527         case MB_TERM_CALL_R8:
528 //      case MB_TERM_CALL_VOID :
529                 tree->reg1 = mono_regset_alloc_reg (rs, X86_EAX, tree->exclude_mask);
530                 tree->reg2 = mono_regset_alloc_reg (rs, X86_EDX, tree->exclude_mask);
531                 tree->reg3 = mono_regset_alloc_reg (rs, X86_ECX, tree->exclude_mask);
532                 return;
533         default: break;
534         }
535
536         switch (goal) {
537         case MB_NTERM_reg:
538         case MB_NTERM_lreg: {
539                 switch (tree->op) {
540                 case MB_TERM_SHL:
541                 case MB_TERM_SHR:
542                 case MB_TERM_SHR_UN:
543                         tree->exclude_mask |= (1 << X86_ECX);
544                         tree->left->exclude_mask |= (1 << X86_ECX);
545                         break;
546                 case MB_TERM_MUL:
547                 case MB_TERM_MUL_OVF:
548                 case MB_TERM_MUL_OVF_UN:
549                 case MB_TERM_DIV:
550                 case MB_TERM_DIV_UN:
551                 case MB_TERM_REM:
552                 case MB_TERM_REM_UN:
553                         tree->reg1 = mono_regset_alloc_reg (rs, X86_EAX, tree->exclude_mask);
554                         tree->reg2 = mono_regset_alloc_reg (rs, X86_EDX, tree->exclude_mask);
555                         if (goal == MB_NTERM_reg) {
556                                 tree->left->exclude_mask |= (1 << X86_EDX);
557                                 tree->right->exclude_mask |= (1 << X86_EDX) | (1 << X86_EAX);
558                         }
559                         break;
560                 default:
561                         break;
562                 }
563                 break;
564         }
565         default:
566                 break;
567         }
568 }
569
570 static void
571 tree_allocate_regs (MBTree *tree, int goal, MonoRegSet *rs) 
572 {
573         MBTree *kids[10];
574         int ern = mono_burg_rule (tree->state, goal);
575         const guint16 *nts = mono_burg_nts [ern];
576         int i;
577         
578         mono_burg_kids (tree, ern, kids);
579
580         //printf ("RALLOC START %d %p %d\n",  tree->op, rs->free_mask, goal);
581
582         if (nts [0] && kids [0] == tree) {
583                 /* chain rule */
584                 tree_allocate_regs (kids [0], nts [0], rs);
585                 return;
586         }
587
588         for (i = 0; nts [i]; i++)
589                 tree_preallocate_regs (kids [i], nts [i], rs);
590
591         for (i = 0; nts [i]; i++)
592                 tree_allocate_regs (kids [i], nts [i], rs);
593
594         for (i = 0; nts [i]; i++) {
595                 mono_regset_free_reg (rs, kids [i]->reg1);
596                 mono_regset_free_reg (rs, kids [i]->reg2);
597                 mono_regset_free_reg (rs, kids [i]->reg3);
598         }
599
600         switch (goal) {
601         case MB_NTERM_reg:
602                 if (tree->reg1 < 0) { 
603                         tree->reg1 = mono_regset_alloc_reg (rs, -1, tree->exclude_mask);
604                         g_assert (tree->reg1 != -1);
605                 }
606                 break;
607
608         case MB_NTERM_lreg:
609                 if (tree->reg1 < 0) { 
610                         tree->reg1 = mono_regset_alloc_reg (rs, -1, tree->exclude_mask);
611                         g_assert (tree->reg1 != -1);
612                 }
613                 if (tree->reg2 < 0) { 
614                         tree->reg2 = mono_regset_alloc_reg (rs, -1, tree->exclude_mask);
615                         g_assert (tree->reg2 != -1);
616                 }
617                 break;
618
619         case MB_NTERM_freg:
620                 /* fixme: allocate floating point registers */
621                 break;
622       
623         case MB_NTERM_addr:
624                 if (tree->op == MB_TERM_ADD) {
625                         tree->reg1 = mono_regset_alloc_reg (rs, tree->left->reg1, tree->exclude_mask);
626                         tree->reg2 = mono_regset_alloc_reg (rs, tree->right->reg1, tree->exclude_mask);
627                 }
628                 break;
629                 
630         case MB_NTERM_base:
631                 if (tree->op == MB_TERM_ADD) {
632                         tree->reg1 = mono_regset_alloc_reg (rs, tree->left->reg1, tree->exclude_mask);
633                 }
634                 break;
635                
636         case MB_NTERM_index:
637                 if (tree->op == MB_TERM_SHL ||
638                     tree->op == MB_TERM_MUL) {
639                         tree->reg1 = mono_regset_alloc_reg (rs, tree->left->reg1, tree->exclude_mask);
640                 }
641                 break;
642                
643         default:
644                 /* do nothing */
645         }
646
647         //printf ("RALLOC END %d %p\n",  tree->op, rs->free_mask);
648         tree->emit = mono_burg_func [ern];
649 }
650
651 static void
652 arch_allocate_regs (MonoFlowGraph *cfg)
653 {
654         int i, j;
655         
656         for (i = 0; i < cfg->block_count; i++) {
657                 GPtrArray *forest = cfg->bblocks [i].forest;
658                 int top;
659
660                 if (!cfg->bblocks [i].reached) /* unreachable code */
661                         continue;
662
663                 top = forest->len;
664
665                 for (j = 0; j < top; j++) {
666                         MBTree *t1 = (MBTree *) g_ptr_array_index (forest, j);
667                         //printf ("AREGSTART %d:%d %p\n", i, j, cfg->rs->free_mask);
668                         tree_allocate_regs (t1, 1, cfg->rs);
669                         //printf ("AREGENDT %d:%d %p\n", i, j, cfg->rs->free_mask);
670                         g_assert (cfg->rs->free_mask == 0xffffffff);
671                 }
672         }
673 }
674
675 static void
676 tree_emit (int goal, MonoFlowGraph *cfg, MBTree *tree) 
677 {
678         MBTree *kids[10];
679         int i, ern = mono_burg_rule (tree->state, goal);
680         const guint16 *nts = mono_burg_nts [ern];
681         MBEmitFunc emit;
682         int offset;
683
684         mono_burg_kids (tree, ern, kids);
685
686         for (i = 0; nts [i]; i++) 
687                 tree_emit (nts [i], cfg, kids [i]);
688
689         tree->addr = offset = cfg->code - cfg->start;
690
691         // we assume an instruction uses a maximum of 128 bytes
692         if ((cfg->code_size - offset) <= 128) {
693                 int add = MIN ((cfg->code_size * 2), 1024);
694
695                 cfg->code_size += add;
696                 cfg->start = g_realloc (cfg->start, cfg->code_size);
697                 g_assert (cfg->start);
698                 cfg->code = cfg->start + offset;
699         }
700
701         if ((emit = mono_burg_func [ern]))
702                 emit (tree, cfg);
703
704         g_assert ((cfg->code - cfg->start) < cfg->code_size);
705 }
706
707 static void
708 mono_emit_cfg (MonoFlowGraph *cfg)
709 {
710         int i, j;
711
712         for (i = 0; i < cfg->block_count; i++) {
713                 MonoBBlock *bb = &cfg->bblocks [i];
714                 GPtrArray *forest = bb->forest;
715                 int top;
716
717                 if (!bb->reached) /* unreachable code */
718                         continue;
719                 
720                 top = forest->len;
721
722                 bb->addr = cfg->code - cfg->start;
723           
724                 for (j = 0; j < top; j++) {
725                         MBTree *t1 = (MBTree *) g_ptr_array_index (forest, j);
726                         
727                         tree_emit (1, cfg, t1);
728                 }
729         }
730                 
731         cfg->epilog = cfg->code - cfg->start;
732 }
733
734 static void
735 mono_compute_branches (MonoFlowGraph *cfg)
736 {
737         guint8 *end;
738         int i, j;
739
740         end = cfg->code;
741
742         for (j = 0; j < cfg->block_count; j++) {
743                 MonoBBlock *bb = &cfg->bblocks [j];
744                 GPtrArray *forest = bb->forest;
745                 int top;
746                 
747                 if (!bb->reached) /* unreachable code */
748                         continue;
749
750                 top = forest->len;
751         
752                 for (i = 0; i < top; i++) {
753                         MBTree *t1 = (MBTree *) g_ptr_array_index (forest, i);
754
755                         if (t1->is_jump) {
756
757                                 if (t1->op == MB_TERM_SWITCH) {
758                                         MonoBBlock **jt = (MonoBBlock **)t1->data.p;
759                                         guint32 *rt = (guint32 *)t1->data.p;
760
761                                         int m = *((guint32 *)t1->data.p) + 1;
762                                         int j;
763                                         
764                                         for (j = 1; j <= m; j++)
765                                                 rt [j] = (int)(jt [j]->addr + cfg->start);
766                                 }
767
768                                 /* emit the jump instruction again to update addresses */
769                                 cfg->code = cfg->start + t1->addr;
770                                 ((MBEmitFunc)t1->emit) (t1, cfg);
771
772                         }
773                 }
774         }
775
776         cfg->code = end;
777 }
778
779 static int
780 match_debug_method (MonoMethod* method)
781 {
782         GList *tmp = mono_debug_methods;
783
784         for (; tmp; tmp = tmp->next) {
785                 if (strcmp (method->name, tmp->data) == 0) {
786                         return 1;
787                 }
788         }
789         return 0;
790 }
791
792 /**
793  * arch_compile_method:
794  * @method: pointer to the method info
795  *
796  * JIT compilation of a single method. This method also writes the result 
797  * back to method->addr, an thus overwrites the trampoline function.
798  *
799  * Returns: a pointer to the newly created code.
800  */
801 gpointer
802 arch_compile_method (MonoMethod *method)
803 {
804         MonoFlowGraph *cfg;
805         MonoMemPool *mp = mono_mempool_new ();
806
807         g_assert (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL));
808         g_assert (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL));
809
810         if (mono_jit_trace_calls || mono_jit_dump_asm || mono_jit_dump_forest) {
811                 printf ("Start JIT compilation of %s.%s:%s\n", method->klass->name_space,
812                         method->klass->name, method->name);
813         }
814
815         if (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) {
816                 MonoClassField *field;
817                 const char *name = method->name;
818                 static guint target_offset = 0;
819                 static guint method_offset = 0;
820                 guint8 *code;
821                 gboolean delegate = FALSE;
822
823                 if (method->klass->parent && 
824                     method->klass->parent->parent == mono_defaults.delegate_class)
825                         delegate = TRUE;
826                                 
827                 if (!target_offset) {
828                         mono_class_init (mono_defaults.delegate_class);
829
830                         field = mono_class_get_field_from_name (mono_defaults.delegate_class, "m_target");
831                         target_offset = field->offset;
832                         field = mono_class_get_field_from_name (mono_defaults.delegate_class, "method_ptr");
833                         method_offset = field->offset;
834                 }
835                 
836                 if (delegate && *name == '.' && (strcmp (name, ".ctor") == 0)) {
837                         method->addr = code = g_malloc (32);
838                         x86_push_reg (code, X86_EBP);
839                         x86_mov_reg_reg (code, X86_EBP, X86_ESP, 4);
840                         
841                         /* load the this pointer */
842                         x86_mov_reg_membase (code, X86_EAX, X86_EBP, 8, 4); 
843                         /* load m_target arg */
844                         x86_mov_reg_membase (code, X86_EDX, X86_EBP, 12, 4);
845                         /* store mtarget */
846                         x86_mov_membase_reg (code, X86_EAX, target_offset, X86_EDX, 4); 
847                         /* load method_ptr arg */
848                         x86_mov_reg_membase (code, X86_EDX, X86_EBP, 16, 4);
849                         /* store method_ptr */
850                         x86_mov_membase_reg (code, X86_EAX, method_offset, X86_EDX, 4); 
851
852                         x86_leave (code);
853                         x86_ret (code);
854
855                         g_assert ((code - (guint8*)method->addr) < 32);
856
857                 } else if (delegate && *name == 'I' && (strcmp (name, "Invoke") == 0)) {
858                         MonoMethodSignature *csig = method->signature;
859                         int i, arg_size, target, this_pos = 4;
860                         guint8 *source;
861                         
862                         if (csig->ret->type == MONO_TYPE_VALUETYPE) {
863                                 g_assert (!csig->ret->byref);
864                                 this_pos = 8;
865                         }
866
867                         arg_size = 0;
868                         if (csig->param_count) {
869                                 int align;
870                                 
871                                 for (i = 0; i < csig->param_count; ++i) {
872                                         arg_size += mono_type_stack_size (csig->params [i], &align);
873                                         g_assert (align == 4);
874                                 }
875                         }
876
877                         method->addr = g_malloc (64 + arg_size);
878
879                         for (i = 0; i < 2; i ++) {
880                                 int j;
881
882                                 code = method->addr;
883                                 /* load the this pointer */
884                                 x86_mov_reg_membase (code, X86_EAX, X86_ESP, this_pos, 4);
885                                 /* load mtarget */
886                                 x86_mov_reg_membase (code, X86_EDX, X86_EAX, target_offset, 4); 
887                                 /* check if zero (static method call without this pointer) */
888                                 x86_alu_reg_imm (code, X86_CMP, X86_EDX, 0);
889                                 x86_branch32 (code, X86_CC_EQ, target, TRUE); 
890                                 source = code;
891
892                                 /* virtual delegate methods: we have to replace the this pointer 
893                                  * withe the actual target */
894                                 x86_mov_membase_reg (code, X86_ESP, this_pos, X86_EDX, 4); 
895                                 /* jump to method_ptr() */
896                                 x86_jump_membase (code, X86_EAX, method_offset);
897
898                                 /* static delegate methods: we have to remove the this pointer 
899                                  * from the activation frame - I do this do creating a new 
900                                  * stack frame an copy all arguments except the this pointer */
901
902                                 target = code - source;
903                                 g_assert ((arg_size & 3) == 0);
904                                 for (j = 0; j < (arg_size>>2); j++) {
905                                         x86_push_membase (code, X86_ESP, (arg_size + this_pos));
906                                 }
907
908                                 if (this_pos == 8) 
909                                         x86_push_membase (code, X86_ESP, (arg_size + 4));
910                                 
911                                 x86_call_membase (code, X86_EAX, method_offset);
912                                 if (this_pos == 8) 
913                                         x86_alu_reg_imm (code, X86_ADD, X86_ESP, arg_size + 4);
914                                 else
915                                         x86_alu_reg_imm (code, X86_ADD, X86_ESP, arg_size);
916                                 
917                                 x86_ret (code);
918
919                         }
920
921                         g_assert ((code - (guint8*)method->addr) < (64 + arg_size));
922
923                 } else {
924                         if (mono_debug_handle)
925                                 return NULL;
926                         g_error ("Don't know how to exec runtime method %s.%s::%s", 
927                                  method->klass->name_space, method->klass->name, method->name);
928                 }
929         
930         } else {
931                 MonoMethodHeader *header = ((MonoMethodNormal *)method)->header;
932                 MonoJitInfo *ji = g_new0 (MonoJitInfo, 1);
933                 
934                 cfg = mono_cfg_new (method, mp);
935
936                 mono_analyze_flow (cfg);
937                 if (cfg->invalid)
938                         return NULL;
939
940                 mono_analyze_stack (cfg);
941                 if (cfg->invalid)
942                         return NULL;
943         
944                 cfg->rs = mono_regset_new (X86_NREG);
945                 mono_regset_reserve_reg (cfg->rs, X86_ESP);
946                 mono_regset_reserve_reg (cfg->rs, X86_EBP);
947
948                 cfg->code_size = 256;
949                 cfg->start = cfg->code = g_malloc (cfg->code_size);
950
951                 if (match_debug_method (method))
952                         x86_breakpoint (cfg->code);
953
954                 if (mono_jit_dump_forest) {
955                         int i;
956                         printf ("FOREST %s.%s:%s\n", method->klass->name_space,
957                                 method->klass->name, method->name);
958                         for (i = 0; i < cfg->block_count; i++) {
959                                 printf ("BLOCK %d:\n", i);
960                                 mono_print_forest (cfg->bblocks [i].forest);
961                         }
962                 }
963         
964                 mono_label_cfg (cfg);
965                 if (cfg->invalid)
966                         return NULL;
967
968                 arch_allocate_regs (cfg);
969
970                 /* align to 8 byte boundary */
971                 cfg->locals_size += 7;
972                 cfg->locals_size &= ~7;
973
974                 arch_emit_prologue (cfg);
975                 mono_emit_cfg (cfg);
976                 arch_emit_epilogue (cfg);               
977
978                 method->addr = cfg->start;
979
980                 mono_compute_branches (cfg);
981                 
982                 if (mono_jit_dump_asm) {
983                         char *id = g_strdup_printf ("%s.%s_%s", method->klass->name_space,
984                                                     method->klass->name, method->name);
985                         mono_disassemble_code (cfg->start, cfg->code - cfg->start, id);
986                         g_free (id);
987                 }
988                 if (mono_debug_handle)
989                         mono_debug_add_method (mono_debug_handle, cfg);
990
991                 ji->code_size = cfg->code - cfg->start;
992                 ji->used_regs = cfg->rs->used_mask;
993                 ji->method = method;
994                 ji->code_start = method->addr;
995                 mono_jit_info_table_add (mono_jit_info_table, ji);
996
997                 if (header->num_clauses) {
998                         int i, start_block, end_block;
999
1000                         ji->num_clauses = header->num_clauses;
1001                         ji->clauses = g_new0 (MonoJitExceptionInfo, header->num_clauses);
1002
1003                         for (i = 0; i < header->num_clauses; i++) {
1004                                 MonoExceptionClause *ec = &header->clauses [i];
1005                                 MonoJitExceptionInfo *ei = &ji->clauses [i];
1006                         
1007                                 ei->flags = ec->flags;
1008                                 ei->token_or_filter = ec->token_or_filter;
1009
1010                                 g_assert (cfg->bcinfo [ec->try_offset].is_block_start);
1011                                 start_block = cfg->bcinfo [ec->try_offset].block_id;
1012                                 end_block = cfg->bcinfo [ec->try_offset + ec->try_len].block_id;
1013                                 g_assert (cfg->bcinfo [ec->try_offset + ec->try_len].is_block_start);
1014                                 
1015                                 ei->try_start = cfg->start + cfg->bblocks [start_block].addr;
1016                                 ei->try_end = cfg->start + cfg->bblocks [end_block].addr;
1017                                 
1018                                 g_assert (cfg->bcinfo [ec->handler_offset].is_block_start);
1019                                 start_block = cfg->bcinfo [ec->handler_offset].block_id;
1020                                 ei->handler_start = cfg->start + cfg->bblocks [start_block].addr;       
1021                                 
1022                                 //printf ("TEST %x %x %x\n", ei->try_start, ei->try_end, ei->handler_start);
1023                         }
1024                 }
1025                 
1026                 mono_regset_free (cfg->rs);
1027
1028                 mono_cfg_free (cfg);
1029
1030                 mono_mempool_destroy (mp);
1031
1032         }
1033
1034         if (mono_jit_trace_calls || mono_jit_dump_asm || mono_jit_dump_forest) {
1035                 printf ("END JIT compilation of %s.%s:%s %p %p\n", method->klass->name_space,
1036                         method->klass->name, method->name, method, method->addr);
1037         }
1038
1039
1040         return method->addr;
1041 }
1042
1043 /*
1044  * arch_get_restore_context:
1045  *
1046  * Returns a pointer to a method which restores a previously saved sigcontext.
1047  */
1048 static gpointer
1049 arch_get_restore_context ()
1050 {
1051         static guint8 *start = NULL;
1052         guint8 *code;
1053
1054         if (start)
1055                 return start;
1056
1057         /* restore_contect (struct sigcontext *ctx) */
1058         /* we do not restore X86_EAX, X86_EDX */
1059
1060         start = code = malloc (1024);
1061         
1062         /* load ctx */
1063         x86_mov_reg_membase (code, X86_EAX, X86_ESP, 4, 4);
1064
1065         /* get return address, stored in EDX */
1066         x86_mov_reg_membase (code, X86_EDX, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, eip), 4);
1067
1068         /* restore EBX */
1069         x86_mov_reg_membase (code, X86_EBX, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, ebx), 4);
1070         /* restore EDI */
1071         x86_mov_reg_membase (code, X86_EDI, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, edi), 4);
1072         /* restore ESI */
1073         x86_mov_reg_membase (code, X86_ESI, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, esi), 4);
1074         /* restore ESP */
1075         x86_mov_reg_membase (code, X86_ESP, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, esp), 4);
1076         /* restore EBP */
1077         x86_mov_reg_membase (code, X86_EBP, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, ebp), 4);
1078         /* restore ECX. the exception object is passed here to the catch handler */
1079         x86_mov_reg_membase (code, X86_ECX, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, ecx), 4);
1080
1081         /* jump to the saved IP */
1082         x86_jump_reg (code, X86_EDX);
1083
1084         return start;
1085 }
1086
1087 /*
1088  * arch_get_call_finally:
1089  *
1090  * Returns a pointer to a method which calls a finally handler.
1091  */
1092 static gpointer
1093 arch_get_call_finally ()
1094 {
1095         static guint8 start [28];
1096         static int inited = 0;
1097         guint8 *code;
1098
1099         if (inited)
1100                 return start;
1101
1102         inited = 1;
1103         /* call_finally (struct sigcontext *ctx, unsigned long eip) */
1104         code = start;
1105
1106         x86_push_reg (code, X86_EBP);
1107         x86_mov_reg_reg (code, X86_EBP, X86_ESP, 4);
1108         x86_push_reg (code, X86_EBX);
1109         x86_push_reg (code, X86_EDI);
1110         x86_push_reg (code, X86_ESI);
1111
1112         /* load ctx */
1113         x86_mov_reg_membase (code, X86_EAX, X86_EBP, 8, 4);
1114         /* load eip */
1115         x86_mov_reg_membase (code, X86_ECX, X86_EBP, 12, 4);
1116         /* save EBP */
1117         x86_push_reg (code, X86_EBP);
1118         /* set new EBP */
1119         x86_mov_reg_membase (code, X86_EBP, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, ebp), 4);
1120         /* call the handler */
1121         x86_call_reg (code, X86_ECX);
1122         /* restore EBP */
1123         x86_pop_reg (code, X86_EBP);
1124         /* restore saved regs */
1125         x86_pop_reg (code, X86_ESI);
1126         x86_pop_reg (code, X86_EDI);
1127         x86_pop_reg (code, X86_EBX);
1128         x86_leave (code);
1129         x86_ret (code);
1130
1131         g_assert ((code - start) < 28);
1132         return start;
1133 }
1134
1135 /**
1136  * arch_handle_exception:
1137  * @ctx: saved processor state
1138  * @obj:
1139  */
1140 void
1141 arch_handle_exception (struct sigcontext *ctx, gpointer obj)
1142 {
1143         MonoDomain *domain = mono_domain_get ();
1144         MonoJitInfo *ji;
1145         gpointer ip = (gpointer)ctx->eip;
1146         static void (*restore_context) (struct sigcontext *);
1147         static void (*call_finally) (struct sigcontext *, unsigned long);
1148        
1149         g_assert (ctx != NULL);
1150         g_assert (obj != NULL);
1151
1152         ji = mono_jit_info_table_find (mono_jit_info_table, ip);
1153
1154         if (!restore_context)
1155                 restore_context = arch_get_restore_context ();
1156         
1157         if (!call_finally)
1158                 call_finally = arch_get_call_finally ();
1159
1160         if (ji) { /* we are inside managed code */
1161                 MonoMethod *m = ji->method;
1162                 unsigned next_bp;
1163                 int offset = 2;
1164
1165                 if (ji->num_clauses) {
1166                         int i;
1167
1168                         g_assert (ji->clauses);
1169                         
1170                         for (i = 0; i < ji->num_clauses; i++) {
1171                                 MonoJitExceptionInfo *ei = &ji->clauses [i];
1172
1173                                 if (ei->try_start <= ip && ip <= (ei->try_end)) { 
1174                                         /* catch block */
1175                                         if (ei->flags == 0 && mono_object_isinst (obj, 
1176                                                 mono_class_get (m->klass->image, ei->token_or_filter))) {
1177                                         
1178                                                 ctx->eip = (unsigned long)ei->handler_start;
1179                                                 ctx->ecx = (unsigned long)obj;
1180                                                 restore_context (ctx);
1181                                                 g_assert_not_reached ();
1182                                         }
1183                                 }
1184                         }
1185
1186                         /* no handler found - we need to call all finally handlers */
1187                         for (i = 0; i < ji->num_clauses; i++) {
1188                                 MonoJitExceptionInfo *ei = &ji->clauses [i];
1189
1190                                 if (ei->try_start <= ip && ip < (ei->try_end) &&
1191                                     (ei->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
1192                                         call_finally (ctx, (unsigned long)ei->handler_start);
1193                                 }
1194                         }
1195                 }
1196
1197                 if (mono_object_isinst (obj, mono_defaults.exception_class)) {
1198                         char  *strace = mono_string_to_utf8 (((MonoException*)obj)->stack_trace);
1199                         char  *tmp;
1200
1201                         if (!strcmp (strace, "TODO: implement stack traces")){
1202                                 g_free (strace);
1203                                 strace = g_strdup ("");
1204                         }
1205
1206                         tmp = g_strdup_printf ("%sin %s.%s:%s ()\n", strace, m->klass->name_space,  
1207                                                m->klass->name, m->name);
1208
1209                         g_free (strace);
1210
1211                         ((MonoException*)obj)->stack_trace = mono_string_new (domain, tmp);
1212                         g_free (tmp);
1213                 }
1214
1215                 /* continue unwinding */
1216
1217                 /* restore caller saved registers */
1218                 if (ji->used_regs & X86_ESI_MASK) {
1219                         ctx->esi = *((int *)ctx->ebp + offset);
1220                         offset++;
1221                 }
1222                 if (ji->used_regs & X86_EDI_MASK) {
1223                         ctx->edi = *((int *)ctx->ebp + offset);
1224                         offset++;
1225                 }
1226                 if (ji->used_regs & X86_EBX_MASK) {
1227                         ctx->ebx = *((int *)ctx->ebp + offset);
1228                 }
1229
1230                 ctx->esp = ctx->ebp;
1231                 ctx->eip = *((int *)ctx->ebp + 1);
1232                 ctx->ebp = *((int *)ctx->ebp);
1233                 
1234                 if (next_bp < (unsigned)mono_end_of_stack)
1235                         arch_handle_exception (ctx, obj);
1236                 else
1237                         mono_jit_abort (obj);
1238
1239         } else {
1240                 gpointer *lmf_addr = TlsGetValue (lmf_thread_id);
1241                 MonoLMF *lmf;
1242                 MonoMethod *m;
1243
1244                 g_assert (lmf_addr);
1245                 lmf = *((MonoLMF **)lmf_addr);
1246
1247                 if (!lmf)
1248                         mono_jit_abort (obj);
1249
1250                 m = lmf->method;
1251
1252                 *lmf_addr = lmf->previous_lmf;
1253
1254                 ctx->esi = lmf->esi;
1255                 ctx->edi = lmf->edi;
1256                 ctx->ebx = lmf->ebx;
1257                 ctx->ebp = lmf->ebp;
1258                 ctx->eip = lmf->eip;
1259                 ctx->esp = (unsigned long)lmf;
1260
1261                 if (mono_object_isinst (obj, mono_defaults.exception_class)) {
1262                         char  *strace = mono_string_to_utf8 (((MonoException*)obj)->stack_trace);
1263                         char  *tmp;
1264
1265                         if (!strcmp (strace, "TODO: implement stack traces"))
1266                                 strace = g_strdup ("");
1267
1268                         tmp = g_strdup_printf ("%sin (unmanaged) %s.%s:%s ()\n", strace, m->klass->name_space,  
1269                                                m->klass->name, m->name);
1270
1271                         g_free (strace);
1272
1273                         ((MonoException*)obj)->stack_trace = mono_string_new (domain, tmp);
1274                         g_free (tmp);
1275                 }
1276
1277                 if (ctx->eip < (unsigned)mono_end_of_stack)
1278                         arch_handle_exception (ctx, obj);
1279                 else
1280                         mono_jit_abort (obj);
1281         }
1282
1283         g_assert_not_reached ();
1284 }
1285
1286 static void
1287 throw_exception (unsigned long eax, unsigned long ecx, unsigned long edx, unsigned long ebx,
1288                  unsigned long esi, unsigned long edi, unsigned long ebp, MonoObject *exc,
1289                  unsigned long eip,  unsigned long esp)
1290 {
1291         struct sigcontext ctx;
1292         
1293         ctx.esp = esp;
1294         ctx.eip = eip;
1295         ctx.ebp = ebp;
1296         ctx.edi = edi;
1297         ctx.esi = esi;
1298         ctx.ebx = ebx;
1299         ctx.edx = edx;
1300         ctx.ecx = ecx;
1301         ctx.eax = eax;
1302         
1303         arch_handle_exception (&ctx, exc);
1304
1305         g_assert_not_reached ();
1306 }
1307
1308 gpointer 
1309 arch_get_throw_exception (void)
1310 {
1311         static guint8 start [24];
1312         static int inited = 0;
1313         guint8 *code;
1314
1315         if (inited)
1316                 return start;
1317
1318         inited = 1;
1319         code = start;
1320
1321         x86_push_reg (code, X86_ESP);
1322         x86_push_membase (code, X86_ESP, 4); /* IP */
1323         x86_push_membase (code, X86_ESP, 12); /* exception */
1324         x86_push_reg (code, X86_EBP);
1325         x86_push_reg (code, X86_EDI);
1326         x86_push_reg (code, X86_ESI);
1327         x86_push_reg (code, X86_EBX);
1328         x86_push_reg (code, X86_EDX);
1329         x86_push_reg (code, X86_ECX);
1330         x86_push_reg (code, X86_EAX);
1331         x86_call_code (code, throw_exception);
1332         /* we should never reach this breakpoint */
1333         x86_breakpoint (code);
1334
1335         g_assert ((code - start) < 24);
1336         return start;
1337 }
1338
1339
1340
1341