2003-04-27 Martin Baulig <martin@ximian.com>
[mono.git] / mono / mini / mini.c
1 /*
2  * mini.c: The new Mono code generator.
3  *
4  * Author:
5  *   Paolo Molaro (lupus@ximian.com)
6  *   Dietmar Maurer (dietmar@ximian.com)
7  *
8  * (C) 2002 Ximian, Inc.
9  */
10
11 #include <config.h>
12 #include <signal.h>
13 #include <unistd.h>
14
15 #include <mono/metadata/assembly.h>
16 #include <mono/metadata/loader.h>
17 #include <mono/metadata/cil-coff.h>
18 #include <mono/metadata/tabledefs.h>
19 #include <mono/metadata/class.h>
20 #include <mono/metadata/object.h>
21 #include <mono/metadata/exception.h>
22 #include <mono/metadata/opcodes.h>
23 #include <mono/metadata/mono-endian.h>
24 #include <mono/metadata/tokentype.h>
25 #include <mono/metadata/tabledefs.h>
26 #include <mono/metadata/threads.h>
27 #include <mono/metadata/marshal.h>
28 #include <mono/metadata/socket-io.h>
29 #include <mono/metadata/appdomain.h>
30 #include <mono/metadata/debug-helpers.h>
31 #include <mono/io-layer/io-layer.h>
32 #include "mono/metadata/profiler.h"
33 #include <mono/metadata/profiler-private.h>
34 #include <mono/metadata/mono-config.h>
35 #include <mono/metadata/environment.h>
36 #include <mono/metadata/mono-debug.h>
37 #include <mono/metadata/mono-debug-debugger.h>
38
39 #include "mini.h"
40 #include <string.h>
41 #include <ctype.h>
42 #include "inssel.h"
43
44 #include "jit-icalls.c"
45
46 #define MONO_CHECK_THIS(ins) (cfg->method->signature->hasthis && (ins)->ssa_op == MONO_SSA_LOAD && (ins)->inst_left->inst_c0 == 0)
47
48 static gpointer mono_jit_compile_method (MonoMethod *method);
49
50 static void handle_stobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, MonoInst *src, 
51                           const unsigned char *ip, MonoClass *klass, gboolean to_end, gboolean native);
52
53 extern guint8 mono_burg_arity [];
54 /* helper methods signature */
55 static MonoMethodSignature *helper_sig_long_long_long = NULL;
56 static MonoMethodSignature *helper_sig_long_long_int = NULL;
57 static MonoMethodSignature *helper_sig_newarr = NULL;
58 static MonoMethodSignature *helper_sig_ldstr = NULL;
59 static MonoMethodSignature *helper_sig_domain_get = NULL;
60 static MonoMethodSignature *helper_sig_object_new = NULL;
61 static MonoMethodSignature *helper_sig_compile = NULL;
62 static MonoMethodSignature *helper_sig_compile_virt = NULL;
63 static MonoMethodSignature *helper_sig_obj_ptr = NULL;
64 static MonoMethodSignature *helper_sig_ptr_void = NULL;
65 static MonoMethodSignature *helper_sig_void_ptr = NULL;
66 static MonoMethodSignature *helper_sig_void_obj = NULL;
67 static MonoMethodSignature *helper_sig_void_ptr_ptr = NULL;
68 static MonoMethodSignature *helper_sig_void_ptr_ptr_ptr = NULL;
69 static MonoMethodSignature *helper_sig_ptr_ptr_ptr = NULL;
70 static MonoMethodSignature *helper_sig_ptr_obj = NULL;
71 static MonoMethodSignature *helper_sig_initobj = NULL;
72 static MonoMethodSignature *helper_sig_memcpy = NULL;
73 static MonoMethodSignature *helper_sig_memset = NULL;
74 static MonoMethodSignature *helper_sig_ulong_double = NULL;
75 static MonoMethodSignature *helper_sig_long_double = NULL;
76 static MonoMethodSignature *helper_sig_uint_double = NULL;
77 static MonoMethodSignature *helper_sig_int_double = NULL;
78 static MonoMethodSignature *helper_sig_stelem_ref = NULL;
79
80 static guint32 default_opt = MONO_OPT_PEEPHOLE;
81
82 guint32 mono_jit_tls_id = 0;
83 gboolean mono_jit_trace_calls = FALSE;
84 gboolean mono_break_on_exc = FALSE;
85 gboolean mono_compile_aot = FALSE;
86 gboolean mono_trace_coverage = FALSE;
87 gboolean mono_jit_profile = FALSE;
88 MonoDebugFormat mono_debug_format = MONO_DEBUG_FORMAT_NONE;
89
90 CRITICAL_SECTION *metadata_section = NULL;
91
92 static int mini_verbose = 0;
93
94 #ifdef MONO_USE_EXC_TABLES
95 static gboolean
96 mono_type_blittable (MonoType *type)
97 {
98         if (type->byref)
99                 return FALSE;
100
101         switch (type->type){
102         case MONO_TYPE_VOID:
103         case MONO_TYPE_I1:
104         case MONO_TYPE_U1:
105         case MONO_TYPE_I2:
106         case MONO_TYPE_U2:
107         case MONO_TYPE_I4:
108         case MONO_TYPE_U4:
109         case MONO_TYPE_I8:
110         case MONO_TYPE_U8:
111         case MONO_TYPE_R4:
112         case MONO_TYPE_R8:
113         case MONO_TYPE_I:
114         case MONO_TYPE_U:
115         case MONO_TYPE_OBJECT:
116                 return TRUE;
117         case MONO_TYPE_VALUETYPE:
118         case MONO_TYPE_CLASS:
119                 return type->data.klass->blittable;
120                 break;
121         default:
122                 break;
123         }
124
125         return FALSE;
126 }
127
128 gboolean
129 mono_method_blittable (MonoMethod *method)
130 {
131         MonoMethodSignature *sig;
132         int i;
133
134         if (!method->addr)
135                 return FALSE;
136
137         if (!mono_arch_has_unwind_info (method->addr)) {
138                 return FALSE;
139         }
140
141         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
142                 return TRUE;
143
144         sig = method->signature;
145
146         if (!mono_type_blittable (sig->ret))
147                 return FALSE;
148
149         for (i = 0; i < sig->param_count; i++)
150                 if (!mono_type_blittable (sig->params [i]))
151                         return FALSE;
152
153         return TRUE;
154 }
155 #endif
156
157 /* debug function */
158 static void
159 print_method_from_ip (void *ip)
160 {
161         MonoJitInfo *ji;
162         char *method;
163         
164         ji = mono_jit_info_table_find (mono_domain_get (), ip);
165         if (!ji) {
166                 g_print ("No method at %p\n", ip);
167                 return;
168         }
169         method = mono_method_full_name (ji->method, TRUE);
170         g_print ("IP at offset 0x%x of method %s (%p %p)\n", (char*)ip - (char*)ji->code_start, method, ji->code_start, (char*)ji->code_start + ji->code_size);
171         g_free (method);
172
173 }
174
175 #define MONO_INIT_VARINFO(vi,id) do { \
176         (vi)->range.first_use.pos.bid = 0xffff; \
177         (vi)->reg = -1; \
178         (vi)->idx = (id); \
179 } while (0)
180
181 /*
182  * Basic blocks have two numeric identifiers:
183  * dfn: Depth First Number
184  * block_num: unique ID assigned at bblock creation
185  */
186 #define NEW_BBLOCK(cfg) (mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock)))
187 #define ADD_BBLOCK(cfg,bbhash,b) do {   \
188                 g_hash_table_insert (bbhash, (b)->cil_code, (b));       \
189                 (b)->block_num = cfg->num_bblocks++;    \
190                 (b)->real_offset = real_offset; \
191         } while (0)
192
193 #define GET_BBLOCK(cfg,bbhash,tblock,ip) do {   \
194                 (tblock) = g_hash_table_lookup (bbhash, (ip));  \
195                 if (!(tblock)) {        \
196                         if ((ip) >= end || (ip) < header->code) goto unverified; \
197                         (tblock) = NEW_BBLOCK (cfg);    \
198                         (tblock)->cil_code = (ip);      \
199                         ADD_BBLOCK (cfg, (bbhash), (tblock));   \
200                 }       \
201                 (tblock)->real_offset = real_offset; \
202         } while (0)
203
204 #define CHECK_BBLOCK(target,ip,tblock) do {     \
205                 if ((target) < (ip) && !(tblock)->code) {       \
206                         bb_recheck = g_list_prepend (bb_recheck, (tblock));     \
207                         if (cfg->verbose_level > 2) g_print ("queued block %d for check at IL%04x from IL%04x\n", (tblock)->block_num, (target) - header->code, (ip) - header->code);   \
208                 }       \
209         } while (0)
210
211 #define NEW_ICONST(cfg,dest,val) do {   \
212                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
213                 (dest)->opcode = OP_ICONST;     \
214                 (dest)->inst_c0 = (val);        \
215                 (dest)->type = STACK_I4;        \
216         } while (0)
217
218 /* FIXME: have a different definition of NEW_PCONST for 64 bit systems */
219 #define NEW_PCONST(cfg,dest,val) do {   \
220                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
221                 (dest)->opcode = OP_ICONST;     \
222                 (dest)->inst_p0 = (val);        \
223                 (dest)->type = STACK_PTR;       \
224         } while (0)
225
226 #define NEW_CLASSCONST(cfg,dest,val) do {       \
227                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
228                 (dest)->opcode = mono_compile_aot ? OP_AOTCONST : OP_ICONST;    \
229                 (dest)->inst_p0 = (val);        \
230                 (dest)->inst_i1 = (gpointer)MONO_PATCH_INFO_CLASS; \
231                 (dest)->type = STACK_PTR;       \
232         } while (0)
233
234 #define NEW_IMAGECONST(cfg,dest,val) do {       \
235                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
236                 (dest)->opcode = mono_compile_aot ? OP_AOTCONST : OP_ICONST;    \
237                 (dest)->inst_p0 = (val);        \
238                 (dest)->inst_i1 = (gpointer)MONO_PATCH_INFO_IMAGE; \
239                 (dest)->type = STACK_PTR;       \
240         } while (0)
241
242 #define NEW_FIELDCONST(cfg,dest,field) do {     \
243                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
244                 (dest)->opcode = mono_compile_aot ? OP_AOTCONST : OP_ICONST;    \
245                 (dest)->inst_p0 = (field);      \
246                 (dest)->inst_i1 = (gpointer)MONO_PATCH_INFO_FIELD; \
247                 (dest)->type = STACK_PTR;       \
248         } while (0)
249
250 #define NEW_METHODCONST(cfg,dest,val) do {      \
251                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
252                 (dest)->opcode = mono_compile_aot ? OP_AOTCONST : OP_ICONST;    \
253                 (dest)->inst_p0 = (val);        \
254                 (dest)->inst_i1 = (gpointer)MONO_PATCH_INFO_METHODCONST; \
255                 (dest)->type = STACK_PTR;       \
256         } while (0)
257
258 #define NEW_DOMAINCONST(cfg,dest) do { \
259                if ((cfg->opt & MONO_OPT_SAHRED) || mono_compile_aot) { \
260                        NEW_TEMPLOAD (cfg, dest, mono_get_domainvar (cfg)->inst_c0); \
261                } else { \
262                        NEW_PCONST (cfg, dest, (cfg)->domain); \
263                } \
264         } while (0)
265
266 #define GET_VARINFO_INST(cfg,num) ((cfg)->varinfo [(num)]->inst)
267
268 #define NEW_ARGLOAD(cfg,dest,num) do {  \
269                 if (arg_array [(num)]->opcode == OP_ICONST) (dest) = arg_array [(num)]; else { \
270                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
271                 (dest)->ssa_op = MONO_SSA_LOAD; \
272                 (dest)->inst_i0 = arg_array [(num)];    \
273                 (dest)->opcode = mono_type_to_ldind ((dest)->inst_i0->inst_vtype);      \
274                 type_to_eval_stack_type (param_types [(num)], (dest));  \
275                 (dest)->klass = (dest)->inst_i0->klass; \
276         }} while (0)
277
278 #define NEW_LOCLOAD(cfg,dest,num) do {  \
279                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
280                 (dest)->ssa_op = MONO_SSA_LOAD; \
281                 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)];       \
282                 (dest)->opcode = mono_type_to_ldind ((dest)->inst_i0->inst_vtype);      \
283                 type_to_eval_stack_type (header->locals [(num)], (dest));       \
284                 (dest)->klass = (dest)->inst_i0->klass; \
285         } while (0)
286
287 #define NEW_LOCLOADA(cfg,dest,num) do { \
288                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
289                 (dest)->ssa_op = MONO_SSA_MAYBE_LOAD;   \
290                 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)];       \
291                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
292                 (dest)->opcode = OP_LDADDR;     \
293                 (dest)->type = STACK_MP;        \
294                 (dest)->klass = (dest)->inst_i0->klass; \
295                 (cfg)->disable_ssa = TRUE; \
296         } while (0)
297
298 #define NEW_RETLOADA(cfg,dest) do {     \
299                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
300                 (dest)->ssa_op = MONO_SSA_MAYBE_LOAD;   \
301                 (dest)->inst_i0 = (cfg)->ret;   \
302                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
303                 (dest)->opcode = CEE_LDIND_I;   \
304                 (dest)->type = STACK_MP;        \
305                 (dest)->klass = (dest)->inst_i0->klass; \
306                 (cfg)->disable_ssa = TRUE; \
307         } while (0)
308
309 #define NEW_ARGLOADA(cfg,dest,num) do { \
310                 if (arg_array [(num)]->opcode == OP_ICONST) goto inline_failure; \
311                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
312                 (dest)->ssa_op = MONO_SSA_MAYBE_LOAD;   \
313                 (dest)->inst_i0 = arg_array [(num)];    \
314                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
315                 (dest)->opcode = OP_LDADDR;     \
316                 (dest)->type = STACK_MP;        \
317                 (dest)->klass = (dest)->inst_i0->klass; \
318                 (cfg)->disable_ssa = TRUE; \
319         } while (0)
320
321 #define NEW_TEMPLOAD(cfg,dest,num) do { \
322                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
323                 (dest)->ssa_op = MONO_SSA_LOAD; \
324                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
325                 (dest)->opcode = mono_type_to_ldind ((dest)->inst_i0->inst_vtype);      \
326                 type_to_eval_stack_type ((dest)->inst_i0->inst_vtype, (dest));  \
327                 (dest)->klass = (dest)->inst_i0->klass; \
328         } while (0)
329
330 #define NEW_TEMPLOADA(cfg,dest,num) do {        \
331                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
332                 (dest)->ssa_op = MONO_SSA_MAYBE_LOAD;   \
333                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
334                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
335                 (dest)->opcode = OP_LDADDR;     \
336                 (dest)->type = STACK_MP;        \
337                 (dest)->klass = (dest)->inst_i0->klass; \
338                 (cfg)->disable_ssa = TRUE; \
339         } while (0)
340
341
342 #define NEW_INDLOAD(cfg,dest,addr,vtype) do {   \
343                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
344                 (dest)->inst_left = addr;       \
345                 (dest)->opcode = mono_type_to_ldind (vtype);    \
346                 type_to_eval_stack_type (vtype, (dest));        \
347                 /* FIXME: (dest)->klass = (dest)->inst_i0->klass;*/     \
348         } while (0)
349
350 #define NEW_INDSTORE(cfg,dest,addr,value,vtype) do {    \
351                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
352                 (dest)->inst_i0 = addr; \
353                 (dest)->opcode = mono_type_to_stind (vtype);    \
354                 (dest)->inst_i1 = (value);      \
355                 /* FIXME: (dest)->klass = (dest)->inst_i0->klass;*/     \
356         } while (0)
357
358 #define NEW_TEMPSTORE(cfg,dest,num,inst) do {   \
359                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
360                 (dest)->ssa_op = MONO_SSA_STORE;        \
361                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
362                 (dest)->opcode = mono_type_to_stind ((dest)->inst_i0->inst_vtype);      \
363                 (dest)->inst_i1 = (inst);       \
364                 (dest)->klass = (dest)->inst_i0->klass; \
365         } while (0)
366
367 #define NEW_LOCSTORE(cfg,dest,num,inst) do {    \
368                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
369                 (dest)->opcode = mono_type_to_stind (header->locals [(num)]);   \
370                 (dest)->ssa_op = MONO_SSA_STORE;        \
371                 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)];       \
372                 (dest)->inst_i1 = (inst);       \
373                 (dest)->klass = (dest)->inst_i0->klass; \
374         } while (0)
375
376 #define NEW_ARGSTORE(cfg,dest,num,inst) do {    \
377                 if (arg_array [(num)]->opcode == OP_ICONST) goto inline_failure; \
378                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
379                 (dest)->opcode = mono_type_to_stind (param_types [(num)]);      \
380                 (dest)->ssa_op = MONO_SSA_STORE;        \
381                 (dest)->inst_i0 = arg_array [(num)];    \
382                 (dest)->inst_i1 = (inst);       \
383                 (dest)->klass = (dest)->inst_i0->klass; \
384         } while (0)
385
386 #define ADD_BINOP(op) do {      \
387                 MONO_INST_NEW (cfg, ins, (op)); \
388                 ins->cil_code = ip;     \
389                 sp -= 2;        \
390                 ins->inst_i0 = sp [0];  \
391                 ins->inst_i1 = sp [1];  \
392                 *sp++ = ins;    \
393                 type_from_op (ins);     \
394                 CHECK_TYPE (ins);       \
395         } while (0)
396
397 #define ADD_UNOP(op) do {       \
398                 MONO_INST_NEW (cfg, ins, (op)); \
399                 ins->cil_code = ip;     \
400                 sp--;   \
401                 ins->inst_i0 = sp [0];  \
402                 *sp++ = ins;    \
403                 type_from_op (ins);     \
404                 CHECK_TYPE (ins);       \
405         } while (0)
406
407 #define ADD_BINCOND(next_block) do {    \
408                 MonoInst *cmp;  \
409                 MONO_INST_NEW(cfg, cmp, OP_COMPARE);    \
410                 sp -= 2;                \
411                 cmp->inst_i0 = sp [0];  \
412                 cmp->inst_i1 = sp [1];  \
413                 cmp->cil_code = ins->cil_code;  \
414                 type_from_op (cmp);     \
415                 CHECK_TYPE (cmp);       \
416                 ins->inst_i0 = cmp;     \
417                 MONO_ADD_INS (bblock, ins);     \
418                 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);      \
419                 GET_BBLOCK (cfg, bbhash, tblock, target);               \
420                 link_bblock (cfg, bblock, tblock);      \
421                 ins->inst_true_bb = tblock;     \
422                 CHECK_BBLOCK (target, ip, tblock);      \
423                 if ((next_block)) {     \
424                         link_bblock (cfg, bblock, (next_block));        \
425                         ins->inst_false_bb = (next_block);      \
426                         start_new_bblock = 1;   \
427                 } else {        \
428                         GET_BBLOCK (cfg, bbhash, tblock, ip);           \
429                         link_bblock (cfg, bblock, tblock);      \
430                         ins->inst_false_bb = tblock;    \
431                         start_new_bblock = 2;   \
432                 }       \
433         } while (0)
434
435 /* FIXME: handle float, long ... */
436 #define ADD_UNCOND(istrue) do { \
437                 MonoInst *cmp;  \
438                 MONO_INST_NEW(cfg, cmp, OP_COMPARE);    \
439                 sp--;           \
440                 cmp->inst_i0 = sp [0];  \
441                 switch (cmp->inst_i0->type) { \
442                 case STACK_I8: \
443                         cmp->inst_i1 = zero_int64; break; \
444                 case STACK_R8: \
445                         cmp->inst_i1 = zero_r8; break; \
446                 case STACK_PTR: \
447                 case STACK_MP: \
448                         cmp->inst_i1 = zero_ptr; break; \
449                 case STACK_OBJ: \
450                         cmp->inst_i1 = zero_obj; break; \
451                 default: \
452                         cmp->inst_i1 = zero_int32;  \
453                 }  \
454                 cmp->cil_code = ins->cil_code;  \
455                 type_from_op (cmp);     \
456                 CHECK_TYPE (cmp);       \
457                 ins->inst_i0 = cmp;     \
458                 ins->opcode = (istrue)? CEE_BNE_UN: CEE_BEQ;    \
459                 MONO_ADD_INS (bblock, ins);     \
460                 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);      \
461                 GET_BBLOCK (cfg, bbhash, tblock, target);               \
462                 link_bblock (cfg, bblock, tblock);      \
463                 ins->inst_true_bb = tblock;     \
464                 CHECK_BBLOCK (target, ip, tblock);      \
465                 GET_BBLOCK (cfg, bbhash, tblock, ip);           \
466                 link_bblock (cfg, bblock, tblock);      \
467                 ins->inst_false_bb = tblock;    \
468                 start_new_bblock = 2;   \
469         } while (0)
470
471 #define NEW_LDELEMA(cfg,dest,sp,k) do { \
472                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
473                 (dest)->opcode = CEE_LDELEMA;   \
474                 (dest)->inst_left = (sp) [0];   \
475                 (dest)->inst_right = (sp) [1];  \
476                 (dest)->type = STACK_MP;        \
477                 (dest)->klass = (k);    \
478         } while (0)
479
480 #define NEW_GROUP(cfg,dest,el1,el2) do {        \
481                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
482                 (dest)->opcode = OP_GROUP;      \
483                 (dest)->inst_left = (el1);      \
484                 (dest)->inst_right = (el2);     \
485         } while (0)
486
487 static GHashTable *coverage_hash = NULL;
488
489 MonoCoverageInfo *
490 mono_allocate_coverage_info (MonoMethod *method, int size)
491 {
492         MonoCoverageInfo *res;
493
494         if (!coverage_hash)
495                 coverage_hash = g_hash_table_new (NULL, NULL);
496
497         res = g_malloc0 (sizeof (MonoCoverageInfo) + sizeof (int) * size * 2);
498
499         res->entries = size;
500
501         g_hash_table_insert (coverage_hash, method, res);
502
503         return res;
504 }
505
506 MonoCoverageInfo *
507 mono_get_coverage_info (MonoMethod *method)
508 {
509         if (!coverage_hash)
510                 return NULL;
511
512         return g_hash_table_lookup (coverage_hash, method);
513 }
514                 
515 #if 0
516 static gint
517 compare_bblock (gconstpointer a, gconstpointer b)
518 {
519         const MonoBasicBlock *b1 = a;
520         const MonoBasicBlock *b2 = b;
521
522         return b2->cil_code - b1->cil_code;
523 }
524 #endif
525
526 /* *
527  * link_bblock: Links two basic blocks
528  *
529  * links two basic blocks in the control flow graph, the 'from'
530  * argument is the starting block and the 'to' argument is the block
531  * the control flow ends to after 'from'.
532  */
533 static void
534 link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
535 {
536         MonoBasicBlock **newa;
537         int i, found;
538
539 #if 0
540         if (from->cil_code) {
541                 if (to->cil_code)
542                         g_print ("edge from IL%04x to IL_%04x\n", from->cil_code - cfg->cil_code, to->cil_code - cfg->cil_code);
543                 else
544                         g_print ("edge from IL%04x to exit\n", from->cil_code - cfg->cil_code);
545         } else {
546                 if (to->cil_code)
547                         g_print ("edge from entry to IL_%04x\n", to->cil_code - cfg->cil_code);
548                 else
549                         g_print ("edge from entry to exit\n");
550         }
551 #endif
552         found = FALSE;
553         for (i = 0; i < from->out_count; ++i) {
554                 if (to == from->out_bb [i]) {
555                         found = TRUE;
556                         break;
557                 }
558         }
559         if (!found) {
560                 newa = mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (from->out_count + 1));
561                 for (i = 0; i < from->out_count; ++i) {
562                         newa [i] = from->out_bb [i];
563                 }
564                 newa [i] = to;
565                 from->out_count++;
566                 from->out_bb = newa;
567         }
568
569         found = FALSE;
570         for (i = 0; i < to->in_count; ++i) {
571                 if (from == to->in_bb [i]) {
572                         found = TRUE;
573                         break;
574                 }
575         }
576         if (!found) {
577                 newa = mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (to->in_count + 1));
578                 for (i = 0; i < to->in_count; ++i) {
579                         newa [i] = to->in_bb [i];
580                 }
581                 newa [i] = from;
582                 to->in_count++;
583                 to->in_bb = newa;
584         }
585 }
586
587 /*
588  * We mark each basic block with a region ID. We use that to avoid BB
589  * optimizations when blocks are in different regions. 
590  */
591 static int
592 mono_find_block_region (MonoCompile *cfg, int offset, int *filter_lengths)
593 {
594         MonoMethod *method = cfg->method;
595         MonoMethodHeader *header = ((MonoMethodNormal *)method)->header;
596         MonoExceptionClause *clause;
597         int i;
598
599         /* first search for handlers and filters */
600         for (i = 0; i < header->num_clauses; ++i) {
601                 clause = &header->clauses [i];
602                 if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->token_or_filter) &&
603                     (offset < (clause->token_or_filter + filter_lengths [i])))
604                         return (i << 8) | 128 | clause->flags;
605                            
606                 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
607                         return (i << 8) | 64 | clause->flags;
608                 }
609         }
610
611         /* search the try blocks */
612         for (i = 0; i < header->num_clauses; ++i) {
613                 clause = &header->clauses [i];
614                 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
615                         return (i << 8) | clause->flags;
616         }
617
618         return -1;
619 }
620
621 static MonoBasicBlock *
622 mono_find_final_block (MonoCompile *cfg, unsigned char *ip, unsigned char *target, int type)
623 {
624         MonoMethod *method = cfg->method;
625         MonoMethodHeader *header = ((MonoMethodNormal *)method)->header;
626         MonoExceptionClause *clause;
627         MonoBasicBlock *handler;
628         int i;
629
630         for (i = 0; i < header->num_clauses; ++i) {
631                 clause = &header->clauses [i];
632                 if (MONO_OFFSET_IN_CLAUSE (clause, (ip - header->code)) && 
633                     (!MONO_OFFSET_IN_CLAUSE (clause, (target - header->code)))) {
634                         if (clause->flags & type) {
635                                 handler = g_hash_table_lookup (cfg->bb_hash, header->code + clause->handler_offset);
636                                 g_assert (handler);
637                                 return handler;
638                         }
639                 }
640         }
641         return NULL;
642 }
643
644
645 static void
646 df_visit (MonoBasicBlock *start, int *dfn, MonoBasicBlock **array)
647 {
648         int i;
649
650         array [*dfn] = start;
651         /*g_print ("visit %d at %p\n", *dfn, start->cil_code);*/
652         for (i = 0; i < start->out_count; ++i) {
653                 if (start->out_bb [i]->dfn)
654                         continue;
655                 (*dfn)++;
656                 start->out_bb [i]->dfn = *dfn;
657                 start->out_bb [i]->df_parent = start;
658                 array [*dfn] = start->out_bb [i];
659                 df_visit (start->out_bb [i], dfn, array);
660         }
661 }
662
663 typedef struct {
664         const guchar *code;
665         MonoBasicBlock *best;
666 } PrevStruct;
667
668 static void
669 previous_foreach (gconstpointer key, gpointer val, gpointer data)
670 {
671         PrevStruct *p = data;
672         MonoBasicBlock *bb = val;
673         //printf ("FIDPREV %d %p  %p %p %p %p %d %d %d\n", bb->block_num, p->code, bb, p->best, bb->cil_code, p->best->cil_code,
674         //bb->method == p->best->method, bb->cil_code < p->code, bb->cil_code > p->best->cil_code);
675
676         if (bb->cil_code && bb->cil_code < p->code && bb->cil_code > p->best->cil_code)
677                 p->best = bb;
678 }
679
680 static MonoBasicBlock*
681 find_previous (GHashTable *bb_hash, MonoBasicBlock *start, const guchar *code) {
682         PrevStruct p;
683
684         p.code = code;
685         p.best = start;
686
687         g_hash_table_foreach (bb_hash, (GHFunc)previous_foreach, &p);
688         return p.best;
689 }
690
691 static void
692 split_bblock (MonoCompile *cfg, MonoBasicBlock *first, MonoBasicBlock *second) {
693         int i, j;
694         MonoInst *inst;
695         MonoBasicBlock *bb;
696
697         if (second->code)
698                 return;
699         
700         /* 
701          * FIXME: take into account all the details:
702          * second may have been the target of more than one bblock
703          */
704         second->out_count = first->out_count;
705         second->out_bb = first->out_bb;
706
707         for (i = 0; i < first->out_count; ++i) {
708                 bb = first->out_bb [i];
709                 for (j = 0; j < bb->in_count; ++j) {
710                         if (bb->in_bb [j] == first)
711                                 bb->in_bb [j] = second;
712                 }
713         }
714
715         first->out_count = 0;
716         first->out_bb = NULL;
717         link_bblock (cfg, first, second);
718
719         second->last_ins = first->last_ins;
720
721         /*g_print ("start search at %p for %p\n", first->cil_code, second->cil_code);*/
722         for (inst = first->code; inst && inst->next; inst = inst->next) {
723                 /*char *code = mono_disasm_code_one (NULL, cfg->method, inst->next->cil_code, NULL);
724                 g_print ("found %p: %s", inst->next->cil_code, code);
725                 g_free (code);*/
726                 if (inst->cil_code < second->cil_code && inst->next->cil_code >= second->cil_code) {
727                         second->code = inst->next;
728                         inst->next = NULL;
729                         first->last_ins = inst;
730                         second->next_bb = first->next_bb;
731                         first->next_bb = second;
732                         return;
733                 }
734         }
735         if (!second->code) {
736                 g_warning ("bblock split failed in %s::%s\n", cfg->method->klass->name, cfg->method->name);
737                 //G_BREAKPOINT ();
738         }
739 }
740
741 guint
742 mono_type_to_ldind (MonoType *type)
743 {
744         int t = type->type;
745
746         if (type->byref)
747                 return CEE_LDIND_I;
748
749 handle_enum:
750         switch (t) {
751         case MONO_TYPE_I1:
752                 return CEE_LDIND_I1;
753         case MONO_TYPE_U1:
754         case MONO_TYPE_BOOLEAN:
755                 return CEE_LDIND_U1;
756         case MONO_TYPE_I2:
757                 return CEE_LDIND_I2;
758         case MONO_TYPE_U2:
759         case MONO_TYPE_CHAR:
760                 return CEE_LDIND_U2;
761         case MONO_TYPE_I4:
762                 return CEE_LDIND_I4;
763         case MONO_TYPE_U4:
764                 return CEE_LDIND_U4;
765         case MONO_TYPE_I:
766         case MONO_TYPE_U:
767         case MONO_TYPE_PTR:
768         case MONO_TYPE_FNPTR:
769                 return CEE_LDIND_I;
770         case MONO_TYPE_CLASS:
771         case MONO_TYPE_STRING:
772         case MONO_TYPE_OBJECT:
773         case MONO_TYPE_SZARRAY:
774         case MONO_TYPE_ARRAY:    
775                 return CEE_LDIND_REF;
776         case MONO_TYPE_I8:
777         case MONO_TYPE_U8:
778                 return CEE_LDIND_I8;
779         case MONO_TYPE_R4:
780                 return CEE_LDIND_R4;
781         case MONO_TYPE_R8:
782                 return CEE_LDIND_R8;
783         case MONO_TYPE_VALUETYPE:
784                 if (type->data.klass->enumtype) {
785                         t = type->data.klass->enum_basetype->type;
786                         goto handle_enum;
787                 }
788                 return CEE_LDOBJ;
789         default:
790                 g_error ("unknown type 0x%02x in type_to_ldind", type->type);
791         }
792         return -1;
793 }
794
795 guint
796 mono_type_to_stind (MonoType *type)
797 {
798         int t = type->type;
799
800         if (type->byref)
801                 return CEE_STIND_I;
802
803 handle_enum:
804         switch (t) {
805         case MONO_TYPE_I1:
806         case MONO_TYPE_U1:
807         case MONO_TYPE_BOOLEAN:
808                 return CEE_STIND_I1;
809         case MONO_TYPE_I2:
810         case MONO_TYPE_U2:
811         case MONO_TYPE_CHAR:
812                 return CEE_STIND_I2;
813         case MONO_TYPE_I4:
814         case MONO_TYPE_U4:
815                 return CEE_STIND_I4;
816         case MONO_TYPE_I:
817         case MONO_TYPE_U:
818         case MONO_TYPE_PTR:
819         case MONO_TYPE_FNPTR:
820                 return CEE_STIND_I;
821         case MONO_TYPE_CLASS:
822         case MONO_TYPE_STRING:
823         case MONO_TYPE_OBJECT:
824         case MONO_TYPE_SZARRAY:
825         case MONO_TYPE_ARRAY:    
826                 return CEE_STIND_REF;
827         case MONO_TYPE_I8:
828         case MONO_TYPE_U8:
829                 return CEE_STIND_I8;
830         case MONO_TYPE_R4:
831                 return CEE_STIND_R4;
832         case MONO_TYPE_R8:
833                 return CEE_STIND_R8;
834         case MONO_TYPE_VALUETYPE:
835                 if (type->data.klass->enumtype) {
836                         t = type->data.klass->enum_basetype->type;
837                         goto handle_enum;
838                 }
839                 return CEE_STOBJ;
840                 /* fail right now */
841         default:
842                 g_error ("unknown type %02x in type_to_stind", type->type);
843         }
844         return -1;
845 }
846
847 /*
848  * Returns the type used in the eval stack when @type is loaded.
849  * FIXME: return a MonoType/MonoClass for the byref and VALUETYPE cases.
850  */
851 static void
852 type_to_eval_stack_type (MonoType *type, MonoInst *inst) {
853         int t = type->type;
854
855         if (type->byref) {
856                 inst->type = STACK_MP;
857                 return;
858         }
859
860 handle_enum:
861         switch (t) {
862         case MONO_TYPE_I1:
863         case MONO_TYPE_U1:
864         case MONO_TYPE_BOOLEAN:
865         case MONO_TYPE_I2:
866         case MONO_TYPE_U2:
867         case MONO_TYPE_CHAR:
868         case MONO_TYPE_I4:
869         case MONO_TYPE_U4:
870                 inst->type = STACK_I4;
871                 return;
872         case MONO_TYPE_I:
873         case MONO_TYPE_U:
874         case MONO_TYPE_PTR:
875         case MONO_TYPE_FNPTR:
876                 inst->type = STACK_PTR;
877                 return;
878         case MONO_TYPE_CLASS:
879         case MONO_TYPE_STRING:
880         case MONO_TYPE_OBJECT:
881         case MONO_TYPE_SZARRAY:
882         case MONO_TYPE_ARRAY:    
883                 inst->type = STACK_OBJ;
884                 return;
885         case MONO_TYPE_I8:
886         case MONO_TYPE_U8:
887                 inst->type = STACK_I8;
888                 return;
889         case MONO_TYPE_R4:
890         case MONO_TYPE_R8:
891                 inst->type = STACK_R8;
892                 return;
893         case MONO_TYPE_VALUETYPE:
894                 if (type->data.klass->enumtype) {
895                         t = type->data.klass->enum_basetype->type;
896                         goto handle_enum;
897                 } else {
898                         inst->klass = type->data.klass;
899                         inst->type = STACK_VTYPE;
900                         return;
901                 }
902         default:
903                 g_error ("unknown type 0x%02x in eval stack type", type->type);
904         }
905 }
906
907 /*
908  * The following tables are used to quickly validate the IL code in type_from_op ().
909  */
910 static const char
911 bin_num_table [STACK_MAX] [STACK_MAX] = {
912         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
913         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
914         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
915         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
916         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_R8,  STACK_INV, STACK_INV, STACK_INV},
917         {STACK_INV, STACK_MP,  STACK_INV, STACK_MP,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV},
918         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
919         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
920 };
921
922 static const char 
923 neg_table [] = {
924         STACK_INV, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_INV, STACK_INV, STACK_INV
925 };
926
927 /* reduce the size of this table */
928 static const char
929 bin_int_table [STACK_MAX] [STACK_MAX] = {
930         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
931         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
932         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
933         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
934         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
935         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
936         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
937         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
938 };
939
940 static const char
941 bin_comp_table [STACK_MAX] [STACK_MAX] = {
942         {0},
943         {0, 1, 0, 1, 0, 0, 4, 0},
944         {0, 0, 1, 0, 0, 0, 0, 0},
945         {0, 1, 0, 1, 0, 2, 4, 0},
946         {0, 0, 0, 0, 1, 0, 0, 0},
947         {0, 0, 0, 2, 0, 1, 0, 0},
948         {0, 4, 0, 4, 0, 0, 3, 0},
949         {0, 0, 0, 0, 0, 0, 0, 0},
950 };
951
952 /* reduce the size of this table */
953 static const char
954 shift_table [STACK_MAX] [STACK_MAX] = {
955         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
956         {STACK_INV, STACK_I4,  STACK_INV, STACK_I4,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
957         {STACK_INV, STACK_I8,  STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
958         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
959         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
960         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
961         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
962         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
963 };
964
965 /*
966  * Tables to map from the non-specific opcode to the matching
967  * type-specific opcode.
968  */
969 /* handles from CEE_ADD to CEE_SHR_UN (CEE_REM_UN for floats) */
970 static const guint16
971 binops_op_map [STACK_MAX] = {
972         0, 0, OP_LADD-CEE_ADD, OP_PADD-CEE_ADD, OP_FADD-CEE_ADD, 0
973 };
974
975 /* handles from CEE_NEG to CEE_CONV_U8 */
976 static const guint16
977 unops_op_map [STACK_MAX] = {
978         0, 0, OP_LNEG-CEE_NEG, OP_PNEG-CEE_NEG, OP_FNEG-CEE_NEG, 0
979 };
980
981 /* handles from CEE_CONV_U2 to CEE_SUB_OVF_UN */
982 static const guint16
983 ovfops_op_map [STACK_MAX] = {
984         0, 0, OP_LCONV_TO_U2-CEE_CONV_U2, OP_PCONV_TO_U2-CEE_CONV_U2, OP_FCONV_TO_U2-CEE_CONV_U2, 0
985 };
986
987 /* handles from CEE_CONV_OVF_I1_UN to CEE_CONV_OVF_U_UN */
988 static const guint16
989 ovf2ops_op_map [STACK_MAX] = {
990         0, 0, OP_LCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, OP_PCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, OP_FCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, 0
991 };
992
993 /* handles from CEE_CONV_OVF_I1 to CEE_CONV_OVF_U8 */
994 static const guint16
995 ovf3ops_op_map [STACK_MAX] = {
996         0, 0, OP_LCONV_TO_OVF_I1-CEE_CONV_OVF_I1, OP_PCONV_TO_OVF_I1-CEE_CONV_OVF_I1, OP_FCONV_TO_OVF_I1-CEE_CONV_OVF_I1, 0
997 };
998
999 /* handles from CEE_CEQ to CEE_CLT_UN */
1000 static const guint16
1001 ceqops_op_map [STACK_MAX] = {
1002         0, 0, OP_LCEQ-CEE_CEQ, OP_PCEQ-CEE_CEQ, OP_FCEQ-CEE_CEQ, 0
1003 };
1004
1005 /*
1006  * Sets ins->type (the type on the eval stack) according to the
1007  * type of the opcode and the arguments to it.
1008  * Invalid IL code is marked by setting ins->type to the invalid value STACK_INV.
1009  *
1010  * FIXME: this function sets ins->type unconditionally in some cases, but
1011  * it should set it to invalid for some types (a conv.x on an object)
1012  */
1013 static void
1014 type_from_op (MonoInst *ins) {
1015         switch (ins->opcode) {
1016         /* binops */
1017         case CEE_ADD:
1018         case CEE_SUB:
1019         case CEE_MUL:
1020         case CEE_DIV:
1021         case CEE_REM:
1022                 /* FIXME: check unverifiable args for STACK_MP */
1023                 ins->type = bin_num_table [ins->inst_i0->type] [ins->inst_i1->type];
1024                 ins->opcode += binops_op_map [ins->type];
1025                 return;
1026         case CEE_DIV_UN:
1027         case CEE_REM_UN:
1028         case CEE_AND:
1029         case CEE_OR:
1030         case CEE_XOR:
1031                 ins->type = bin_int_table [ins->inst_i0->type] [ins->inst_i1->type];
1032                 ins->opcode += binops_op_map [ins->type];
1033                 return;
1034         case CEE_SHL:
1035         case CEE_SHR:
1036         case CEE_SHR_UN:
1037                 ins->type = shift_table [ins->inst_i0->type] [ins->inst_i1->type];
1038                 ins->opcode += binops_op_map [ins->type];
1039                 return;
1040         case OP_COMPARE:
1041                 /* FIXME: handle some specifics with ins->next->type */
1042                 ins->type = bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] ? STACK_I4: STACK_INV;
1043                 return;
1044         case 256+CEE_CEQ:
1045         case 256+CEE_CGT:
1046         case 256+CEE_CGT_UN:
1047         case 256+CEE_CLT:
1048         case 256+CEE_CLT_UN:
1049                 ins->type = bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] ? STACK_I4: STACK_INV;
1050                 ins->opcode += ceqops_op_map [ins->inst_i0->type];
1051                 return;
1052         /* unops */
1053         case CEE_NEG:
1054                 ins->type = neg_table [ins->inst_i0->type];
1055                 ins->opcode += unops_op_map [ins->type];
1056                 return;
1057         case CEE_NOT:
1058                 if (ins->inst_i0->type >= STACK_I4 && ins->inst_i0->type <= STACK_PTR)
1059                         ins->type = ins->inst_i0->type;
1060                 else
1061                         ins->type = STACK_INV;
1062                 ins->opcode += unops_op_map [ins->type];
1063                 return;
1064         case CEE_CONV_I1:
1065         case CEE_CONV_I2:
1066         case CEE_CONV_I4:
1067         case CEE_CONV_U4:
1068                 ins->type = STACK_I4;
1069                 ins->opcode += unops_op_map [ins->inst_i0->type];
1070                 return;
1071         case CEE_CONV_R_UN:
1072                 ins->type = STACK_R8;
1073                 switch (ins->inst_i0->type) {
1074                 case STACK_I4:
1075                 case STACK_PTR:
1076                         break;
1077                 case STACK_I8:
1078                         ins->opcode = OP_LCONV_TO_R_UN; 
1079                         break;
1080                 }
1081                 return;
1082         case CEE_CONV_OVF_I1:
1083         case CEE_CONV_OVF_U1:
1084         case CEE_CONV_OVF_I2:
1085         case CEE_CONV_OVF_U2:
1086         case CEE_CONV_OVF_I4:
1087         case CEE_CONV_OVF_U4:
1088                 ins->type = STACK_I4;
1089                 ins->opcode += ovf3ops_op_map [ins->inst_i0->type];
1090                 return;
1091         case CEE_CONV_OVF_I_UN:
1092         case CEE_CONV_OVF_U_UN:
1093                 ins->type = STACK_PTR;
1094                 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1095                 return;
1096         case CEE_CONV_OVF_I1_UN:
1097         case CEE_CONV_OVF_I2_UN:
1098         case CEE_CONV_OVF_I4_UN:
1099         case CEE_CONV_OVF_U1_UN:
1100         case CEE_CONV_OVF_U2_UN:
1101         case CEE_CONV_OVF_U4_UN:
1102                 ins->type = STACK_I4;
1103                 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1104                 return;
1105         case CEE_CONV_U:
1106                 ins->type = STACK_PTR;
1107                 switch (ins->inst_i0->type) {
1108                 case STACK_I4:
1109                 case STACK_PTR:
1110                 case STACK_MP:
1111                         break;
1112                 case STACK_I8:
1113                         ins->opcode = OP_LCONV_TO_U;
1114                         break;
1115                 case STACK_R8:
1116                         ins->opcode = OP_FCONV_TO_U;
1117                         break;
1118                 }
1119                 return;
1120         case CEE_CONV_I8:
1121         case CEE_CONV_U8:
1122                 ins->type = STACK_I8;
1123                 ins->opcode += unops_op_map [ins->inst_i0->type];
1124                 return;
1125         case CEE_CONV_OVF_I8:
1126         case CEE_CONV_OVF_U8:
1127                 ins->type = STACK_I8;
1128                 ins->opcode += ovf3ops_op_map [ins->inst_i0->type];
1129                 return;
1130         case CEE_CONV_OVF_U8_UN:
1131         case CEE_CONV_OVF_I8_UN:
1132                 ins->type = STACK_I8;
1133                 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1134                 return;
1135         case CEE_CONV_R4:
1136         case CEE_CONV_R8:
1137                 ins->type = STACK_R8;
1138                 ins->opcode += unops_op_map [ins->inst_i0->type];
1139                 return;
1140         case CEE_CKFINITE:
1141                 ins->type = STACK_R8;           
1142                 return;
1143         case CEE_CONV_U2:
1144         case CEE_CONV_U1:
1145                 ins->type = STACK_I4;
1146                 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1147                 break;
1148         case CEE_CONV_I:
1149         case CEE_CONV_OVF_I:
1150         case CEE_CONV_OVF_U:
1151                 ins->type = STACK_PTR;
1152                 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1153                 return;
1154         case CEE_ADD_OVF:
1155         case CEE_ADD_OVF_UN:
1156         case CEE_MUL_OVF:
1157         case CEE_MUL_OVF_UN:
1158         case CEE_SUB_OVF:
1159         case CEE_SUB_OVF_UN:
1160                 ins->type = bin_num_table [ins->inst_i0->type] [ins->inst_i1->type];
1161                 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1162                 return;
1163         default:
1164                 g_error ("opcode 0x%04x not handled in type from op", ins->opcode);
1165                 break;
1166         }
1167 }
1168
1169 static const char 
1170 ldind_type [] = {
1171         STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I8, STACK_MP, STACK_R8, STACK_R8, STACK_OBJ
1172 };
1173
1174 /* map ldelem.x to the matching ldind.x opcode */
1175 static const guchar
1176 ldelem_to_ldind [] = {
1177         CEE_LDIND_I1,
1178         CEE_LDIND_U1,
1179         CEE_LDIND_I2,
1180         CEE_LDIND_U2,
1181         CEE_LDIND_I4,
1182         CEE_LDIND_U4,
1183         CEE_LDIND_I8,
1184         CEE_LDIND_I,
1185         CEE_LDIND_R4,
1186         CEE_LDIND_R8,
1187         CEE_LDIND_REF
1188 };
1189
1190 /* map stelem.x to the matching stind.x opcode */
1191 static const guchar
1192 stelem_to_stind [] = {
1193         CEE_STIND_I,
1194         CEE_STIND_I1,
1195         CEE_STIND_I2,
1196         CEE_STIND_I4,
1197         CEE_STIND_I8,
1198         CEE_STIND_R4,
1199         CEE_STIND_R8,
1200         CEE_STIND_REF
1201 };
1202
1203 #if 0
1204
1205 static const char
1206 param_table [STACK_MAX] [STACK_MAX] = {
1207         {0},
1208 };
1209
1210 static int
1211 check_values_to_signature (MonoInst *args, MonoType *this, MonoMethodSignature *sig) {
1212         int i;
1213
1214         if (sig->hasthis) {
1215                 switch (args->type) {
1216                 case STACK_I4:
1217                 case STACK_I8:
1218                 case STACK_R8:
1219                 case STACK_VTYPE:
1220                 case STACK_INV:
1221                         return 0;
1222                 }
1223                 args++;
1224         }
1225         for (i = 0; i < sig->param_count; ++i) {
1226                 switch (args [i].type) {
1227                 case STACK_INV:
1228                         return 0;
1229                 case STACK_MP:
1230                         if (!sig->params [i]->byref)
1231                                 return 0;
1232                         continue;
1233                 case STACK_OBJ:
1234                         if (sig->params [i]->byref)
1235                                 return 0;
1236                         switch (sig->params [i]->type) {
1237                         case MONO_TYPE_CLASS:
1238                         case MONO_TYPE_STRING:
1239                         case MONO_TYPE_OBJECT:
1240                         case MONO_TYPE_SZARRAY:
1241                         case MONO_TYPE_ARRAY:
1242                                 break;
1243                         default:
1244                                 return 0;
1245                         }
1246                         continue;
1247                 case STACK_R8:
1248                         if (sig->params [i]->byref)
1249                                 return 0;
1250                         if (sig->params [i]->type != MONO_TYPE_R4 && sig->params [i]->type != MONO_TYPE_R8)
1251                                 return 0;
1252                         continue;
1253                 case STACK_PTR:
1254                 case STACK_I4:
1255                 case STACK_I8:
1256                 case STACK_VTYPE:
1257                         break;
1258                 }
1259                 /*if (!param_table [args [i].type] [sig->params [i]->type])
1260                         return 0;*/
1261         }
1262         return 1;
1263 }
1264 #endif
1265
1266 /*
1267  * When we need a pointer to the current domain many times in a method, we
1268  * call mono_domain_get() once and we store the result in a local variable.
1269  * This function returns the variable that represents the MonoDomain*.
1270  */
1271 inline static MonoInst *
1272 mono_get_domainvar (MonoCompile *cfg)
1273 {
1274         if (!cfg->domainvar)
1275                 cfg->domainvar = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1276         return cfg->domainvar;
1277 }
1278
1279 MonoInst*
1280 mono_compile_create_var (MonoCompile *cfg, MonoType *type, int opcode)
1281 {
1282         MonoInst *inst;
1283         int num = cfg->num_varinfo;
1284
1285         if ((num + 1) >= cfg->varinfo_count) {
1286                 cfg->varinfo_count = (cfg->varinfo_count + 2) * 2;
1287                 cfg->varinfo = (MonoInst **)g_realloc (cfg->varinfo, sizeof (MonoInst*) * cfg->varinfo_count);
1288                 cfg->vars = (MonoMethodVar **)g_realloc (cfg->vars, sizeof (MonoMethodVar*) * cfg->varinfo_count);      
1289         }
1290
1291         mono_jit_stats.allocate_var++;
1292
1293         MONO_INST_NEW (cfg, inst, opcode);
1294         inst->inst_c0 = num;
1295         inst->inst_vtype = type;
1296         inst->klass = mono_class_from_mono_type (type);
1297         /* if set to 1 the variable is native */
1298         inst->unused = 0;
1299
1300         cfg->varinfo [num] = inst;
1301
1302         cfg->vars [num] = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoMethodVar));
1303         MONO_INIT_VARINFO (cfg->vars [num], num);
1304
1305         cfg->num_varinfo++;
1306         //g_print ("created temp %d of type %s\n", num, mono_type_get_name (type));
1307         return inst;
1308 }
1309
1310 static MonoType*
1311 type_from_stack_type (MonoInst *ins) {
1312         switch (ins->type) {
1313         case STACK_I4: return &mono_defaults.int32_class->byval_arg;
1314         case STACK_I8: return &mono_defaults.int64_class->byval_arg;
1315         case STACK_PTR: return &mono_defaults.int_class->byval_arg;
1316         case STACK_R8: return &mono_defaults.double_class->byval_arg;
1317         case STACK_MP: return &mono_defaults.int_class->byval_arg;
1318         case STACK_OBJ: return &mono_defaults.object_class->byval_arg;
1319         case STACK_VTYPE: return &ins->klass->byval_arg;
1320         default:
1321                 g_error ("stack type %d to montype not handled\n", ins->type);
1322         }
1323         return NULL;
1324 }
1325
1326 static MonoClass*
1327 array_access_to_klass (int opcode)
1328 {
1329         switch (opcode) {
1330         case CEE_LDELEM_U1:
1331                 return mono_defaults.byte_class;
1332         case CEE_LDELEM_U2:
1333                 return mono_defaults.uint16_class;
1334         case CEE_LDELEM_I:
1335         case CEE_STELEM_I:
1336                 return mono_defaults.int_class;
1337         case CEE_LDELEM_I1:
1338         case CEE_STELEM_I1:
1339                 return mono_defaults.sbyte_class;
1340         case CEE_LDELEM_I2:
1341         case CEE_STELEM_I2:
1342                 return mono_defaults.int16_class;
1343         case CEE_LDELEM_I4:
1344         case CEE_STELEM_I4:
1345                 return mono_defaults.int32_class;
1346         case CEE_LDELEM_U4:
1347                 return mono_defaults.uint32_class;
1348         case CEE_LDELEM_I8:
1349         case CEE_STELEM_I8:
1350                 return mono_defaults.int64_class;
1351         case CEE_LDELEM_R4:
1352         case CEE_STELEM_R4:
1353                 return mono_defaults.single_class;
1354         case CEE_LDELEM_R8:
1355         case CEE_STELEM_R8:
1356                 return mono_defaults.double_class;
1357         case CEE_LDELEM_REF:
1358         case CEE_STELEM_REF:
1359                 return mono_defaults.object_class;
1360         default:
1361                 g_assert_not_reached ();
1362         }
1363         return NULL;
1364 }
1365
1366 static void
1367 mono_add_ins_to_end (MonoBasicBlock *bb, MonoInst *inst)
1368 {
1369         MonoInst *prev;
1370         if (!bb->code) {
1371                 MONO_ADD_INS (bb, inst);
1372                 return;
1373         }
1374         switch (bb->last_ins->opcode) {
1375         case CEE_BEQ:
1376         case CEE_BGE:
1377         case CEE_BGT:
1378         case CEE_BLE:
1379         case CEE_BLT:
1380         case CEE_BNE_UN:
1381         case CEE_BGE_UN:
1382         case CEE_BGT_UN:
1383         case CEE_BLE_UN:
1384         case CEE_BLT_UN:
1385         case CEE_BR:
1386                 prev = bb->code;
1387                 while (prev->next && prev->next != bb->last_ins)
1388                         prev = prev->next;
1389                 if (prev == bb->code) {
1390                         if (bb->last_ins == bb->code) {
1391                                 inst->next = bb->code;
1392                                 bb->code = inst;
1393                         } else {
1394                                 inst->next = prev->next;
1395                                 prev->next = inst;
1396                         }
1397                 } else {
1398                         inst->next = bb->last_ins;
1399                         prev->next = inst;
1400                 }
1401                 break;
1402         //      g_warning ("handle conditional jump in add_ins_to_end ()\n");
1403         default:
1404                 MONO_ADD_INS (bb, inst);
1405                 break;
1406         }
1407 }
1408
1409 void
1410 mono_add_varcopy_to_end (MonoCompile *cfg, MonoBasicBlock *bb, int src, int dest)
1411 {
1412         MonoInst *inst, *load;
1413
1414         NEW_TEMPLOAD (cfg, load, src);
1415
1416         NEW_TEMPSTORE (cfg, inst, dest, load);
1417         if (inst->opcode == CEE_STOBJ) {
1418                 NEW_TEMPLOADA (cfg, inst, dest);
1419                 handle_stobj (cfg, bb, inst, load, NULL, inst->klass, TRUE, FALSE);
1420         } else {
1421                 inst->cil_code = NULL;
1422                 mono_add_ins_to_end (bb, inst);
1423         }
1424 }
1425
1426 /*
1427  * This function is called to handle items that are left on the evaluation stack
1428  * at basic block boundaries. What happens is that we save the values to local variables
1429  * and we reload them later when first entering the target basic block (with the
1430  * handle_loaded_temps () function).
1431  * A single joint point will use the same variables (stored in the array bb->out_stack or
1432  * bb->in_stack, if the basic block is before or after the joint point).
1433  */
1434 static int
1435 handle_stack_args (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst **sp, int count) {
1436         int i;
1437         MonoBasicBlock *outb;
1438         MonoInst *inst, **locals;
1439
1440         if (!count)
1441                 return 0;
1442         if (cfg->verbose_level > 3)
1443                 g_print ("%d item(s) on exit from B%d\n", count, bb->block_num);
1444         if (!bb->out_scount) {
1445                 int found = 0;
1446                 bb->out_scount = count;
1447                 //g_print ("bblock %d has out:", bb->block_num);
1448                 for (i = 0; i < bb->out_count; ++i) {
1449                         outb = bb->out_bb [i];
1450                         //g_print (" %d", outb->block_num);
1451                         if (outb->in_stack) {
1452                                 found = 1;
1453                                 bb->out_stack = outb->in_stack;
1454                                 break;
1455                         }
1456                 }
1457                 //g_print ("\n");
1458                 if (!found) {
1459                         bb->out_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * count);
1460                         for (i = 0; i < count; ++i) {
1461                                 /* 
1462                                  * dietmar suggests that we can reuse temps already allocated 
1463                                  * for this purpouse, if they occupy the same stack slot and if 
1464                                  * they are of the same type.
1465                                  */
1466                                 bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
1467                         }
1468                 }
1469         }
1470         locals = bb->out_stack;
1471         for (i = 0; i < count; ++i) {
1472                 /* add store ops at the end of the bb, before the branch */
1473                 NEW_TEMPSTORE (cfg, inst, locals [i]->inst_c0, sp [i]);
1474                 if (inst->opcode == CEE_STOBJ) {
1475                         NEW_TEMPLOADA (cfg, inst, locals [i]->inst_c0);
1476                         handle_stobj (cfg, bb, inst, sp [i], sp [i]->cil_code, inst->klass, TRUE, FALSE);
1477                 } else {
1478                         inst->cil_code = sp [i]->cil_code;
1479                         mono_add_ins_to_end (bb, inst);
1480                 }
1481                 if (cfg->verbose_level > 3)
1482                         g_print ("storing %d to temp %d\n", i, locals [i]->inst_c0);
1483         }
1484         
1485         for (i = 0; i < bb->out_count; ++i) {
1486                 outb = bb->out_bb [i];
1487                 if (outb->in_scount)
1488                         continue; /* check they are the same locals */
1489                 outb->in_scount = count;
1490                 outb->in_stack = locals;
1491         }
1492         return 0;
1493 }
1494
1495 static int
1496 ret_type_to_call_opcode (MonoType *type, int calli, int virt)
1497 {
1498         int t = type->type;
1499
1500         if (type->byref)
1501                 return calli? OP_CALL_REG: virt? CEE_CALLVIRT: CEE_CALL;
1502
1503 handle_enum:
1504         switch (t) {
1505         case MONO_TYPE_VOID:
1506                 return calli? OP_VOIDCALL_REG: virt? OP_VOIDCALLVIRT: OP_VOIDCALL;
1507         case MONO_TYPE_I1:
1508         case MONO_TYPE_U1:
1509         case MONO_TYPE_BOOLEAN:
1510         case MONO_TYPE_I2:
1511         case MONO_TYPE_U2:
1512         case MONO_TYPE_CHAR:
1513         case MONO_TYPE_I4:
1514         case MONO_TYPE_U4:
1515                 return calli? OP_CALL_REG: virt? CEE_CALLVIRT: CEE_CALL;
1516         case MONO_TYPE_I:
1517         case MONO_TYPE_U:
1518         case MONO_TYPE_PTR:
1519                 return calli? OP_CALL_REG: virt? CEE_CALLVIRT: CEE_CALL;
1520         case MONO_TYPE_CLASS:
1521         case MONO_TYPE_STRING:
1522         case MONO_TYPE_OBJECT:
1523         case MONO_TYPE_SZARRAY:
1524         case MONO_TYPE_ARRAY:    
1525                 return calli? OP_CALL_REG: virt? CEE_CALLVIRT: CEE_CALL;
1526         case MONO_TYPE_I8:
1527         case MONO_TYPE_U8:
1528                 return calli? OP_LCALL_REG: virt? OP_LCALLVIRT: OP_LCALL;
1529         case MONO_TYPE_R4:
1530         case MONO_TYPE_R8:
1531                 return calli? OP_FCALL_REG: virt? OP_FCALLVIRT: OP_FCALL;
1532         case MONO_TYPE_VALUETYPE:
1533                 if (type->data.klass->enumtype) {
1534                         t = type->data.klass->enum_basetype->type;
1535                         goto handle_enum;
1536                 } else
1537                         return calli? OP_VCALL_REG: virt? OP_VCALLVIRT: OP_VCALL;
1538         default:
1539                 g_error ("unknown type %02x in ret_type_to_call_opcode", type->type);
1540         }
1541         return -1;
1542 }
1543
1544 void
1545 mono_create_jump_table (MonoCompile *cfg, MonoInst *label, MonoBasicBlock **bbs, int num_blocks)
1546 {
1547         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
1548         
1549         ji->ip.label = label;
1550         ji->type = MONO_PATCH_INFO_SWITCH;
1551         ji->data.table = bbs;
1552         ji->next = cfg->patch_info;
1553         ji->table_size = num_blocks;
1554         cfg->patch_info = ji;
1555 }
1556
1557 /*
1558  * When we add a tree of instructions, we need to ensure the instructions currently
1559  * on the stack are executed before (like, if we load a value from a local).
1560  * We ensure this by saving the currently loaded values to temps and rewriting the
1561  * instructions to load the values.
1562  * This is not done for opcodes that terminate a basic block (because it's handled already
1563  * by handle_stack_args ()) and for opcodes that can't change values, like POP.
1564  */
1565 static void
1566 handle_loaded_temps (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst **stack, MonoInst **sp)
1567 {
1568         MonoInst *load, *store, *temp, *ins;
1569
1570         while (stack < sp) {
1571                 ins = *stack;
1572                 /* handle also other constants */
1573                 if (ins->opcode != OP_ICONST) {
1574                         temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1575                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
1576                         store->cil_code = ins->cil_code;
1577                         if (store->opcode == CEE_STOBJ) {
1578                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
1579                                 handle_stobj (cfg, bblock, store, ins, ins->cil_code, temp->klass, FALSE, FALSE);
1580                         } else
1581                                 MONO_ADD_INS (bblock, store);
1582                         NEW_TEMPLOAD (cfg, load, temp->inst_c0);
1583                         load->cil_code = ins->cil_code;
1584                         *stack = load;
1585                 }
1586                 stack++;
1587         }
1588 }
1589
1590 inline static int
1591 mono_spill_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoCallInst *call, MonoMethodSignature *sig, gboolean ret_object, 
1592                  const guint8 *ip, gboolean to_end)
1593 {
1594         MonoInst *temp, *store, *ins = (MonoInst*)call;
1595         MonoType *ret = sig->ret;
1596
1597         if (!MONO_TYPE_IS_VOID (ret) || ret_object) {
1598                 if (ret_object) {
1599                         call->inst.type = STACK_OBJ;
1600                         call->inst.opcode = CEE_CALL;
1601                         temp = mono_compile_create_var (cfg, &mono_defaults.string_class->byval_arg, OP_LOCAL);
1602                 } else {
1603                         type_to_eval_stack_type (ret, ins);
1604                         temp = mono_compile_create_var (cfg, ret, OP_LOCAL);
1605                 }
1606
1607                 if (MONO_TYPE_ISSTRUCT (ret)) {
1608                         MonoInst *loada;
1609
1610                         /* we use this to allocate native sized structs */
1611                         temp->unused = sig->pinvoke;
1612
1613                         NEW_TEMPLOADA (cfg, loada, temp->inst_c0);
1614                         if (call->inst.opcode == OP_VCALL)
1615                                 ins->inst_left = loada;
1616                         else
1617                                 ins->inst_right = loada; /* a virtual or indirect call */
1618
1619                         if (to_end)
1620                                 mono_add_ins_to_end (bblock, ins);
1621                         else
1622                                 MONO_ADD_INS (bblock, ins);
1623                 } else {
1624                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
1625                         store->cil_code = ip;
1626                         if (to_end)
1627                                 mono_add_ins_to_end (bblock, store);
1628                         else
1629                                 MONO_ADD_INS (bblock, store);
1630                 }
1631                 return temp->inst_c0;
1632         } else {
1633                 if (to_end)
1634                         mono_add_ins_to_end (bblock, ins);
1635                 else
1636                         MONO_ADD_INS (bblock, ins);
1637                 return -1;
1638         }
1639 }
1640
1641 inline static MonoCallInst *
1642 mono_emit_call_args (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, 
1643                      MonoInst **args, int calli, int virtual, const guint8 *ip, gboolean to_end)
1644 {
1645         MonoCallInst *call;
1646         int i;
1647
1648         MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (sig->ret, calli, virtual));
1649         
1650         call->inst.cil_code = ip;
1651         call->args = args;
1652         call->signature = sig;
1653         call = mono_arch_call_opcode (cfg, bblock, call, virtual);
1654
1655         for (i = 0; i < (sig->param_count + sig->hasthis); ++i) {
1656                 if (call->args [i]) {
1657                         if (to_end)
1658                                 mono_add_ins_to_end (bblock, call->args [i]);
1659                         else
1660                                 MONO_ADD_INS (bblock, call->args [i]);
1661                 }
1662         }
1663         return call;
1664 }
1665
1666 inline static int
1667 mono_emit_calli (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, 
1668                  MonoInst **args, MonoInst *addr, const guint8 *ip)
1669 {
1670         MonoCallInst *call = mono_emit_call_args (cfg, bblock, sig, args, TRUE, FALSE, ip, FALSE);
1671
1672         call->inst.inst_i0 = addr;
1673
1674         return mono_spill_call (cfg, bblock, call, sig, FALSE, ip, FALSE);
1675 }
1676
1677 static MonoCallInst*
1678 mono_emit_method_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method, MonoMethodSignature *sig,
1679                        MonoInst **args, const guint8 *ip, MonoInst *this)
1680 {
1681         gboolean virtual = this != NULL;
1682         MonoCallInst *call;
1683
1684         call = mono_emit_call_args (cfg, bblock, sig, args, FALSE, virtual, ip, FALSE);
1685
1686         if (this && sig->hasthis && 
1687             (method->klass->marshalbyref || method->klass == mono_defaults.object_class) && 
1688             !(method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !MONO_CHECK_THIS (this)) {
1689                 call->method = mono_marshal_get_remoting_invoke_with_check (method);
1690         } else {
1691                 call->method = method;
1692         }
1693         call->inst.flags |= MONO_INST_HAS_METHOD;
1694         call->inst.inst_left = this;
1695
1696         return call;
1697 }
1698
1699 inline static int
1700 mono_emit_method_call_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,  
1701                        MonoInst **args, const guint8 *ip, MonoInst *this)
1702 {
1703         MonoCallInst *call = mono_emit_method_call (cfg, bblock, method, method->signature, args, ip, this);
1704
1705         return mono_spill_call (cfg, bblock, call, method->signature, method->string_ctor, ip, FALSE);
1706 }
1707
1708 inline static int
1709 mono_emit_native_call (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoMethodSignature *sig,
1710                        MonoInst **args, const guint8 *ip, gboolean to_end)
1711 {
1712         MonoCallInst *call;
1713
1714         g_assert (sig);
1715
1716         call = mono_emit_call_args (cfg, bblock, sig, args, FALSE, FALSE, ip, to_end);
1717         call->fptr = func;
1718         return mono_spill_call (cfg, bblock, call, sig, func == mono_array_new_va, ip, to_end);
1719 }
1720
1721 inline static int
1722 mono_emit_jit_icall (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoInst **args, const guint8 *ip)
1723 {
1724         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (func);
1725         
1726         if (!info) {
1727                 g_warning ("unregistered JIT ICall");
1728                 g_assert_not_reached ();
1729         }
1730
1731         return mono_emit_native_call (cfg, bblock, info->wrapper, info->sig, args, ip, FALSE);
1732 }
1733
1734 static void
1735 mono_emulate_opcode (MonoCompile *cfg, MonoInst *tree, MonoInst **iargs, MonoJitICallInfo *info)
1736 {
1737         MonoInst *ins, *temp = NULL, *store, *load;
1738         int i, nargs;
1739         MonoCallInst *call;
1740
1741         /*g_print ("emulating: ");
1742         mono_print_tree (tree);
1743         g_print ("\n");*/
1744         MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (info->sig->ret, FALSE, FALSE));
1745         ins = (MonoInst*)call;
1746         
1747         call->inst.cil_code = tree->cil_code;
1748         call->args = iargs;
1749         call->signature = info->sig;
1750
1751         call = mono_arch_call_opcode (cfg, cfg->cbb, call, FALSE);
1752
1753         if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
1754                 temp = mono_compile_create_var (cfg, info->sig->ret, OP_LOCAL);
1755                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
1756                 store->cil_code = tree->cil_code;
1757         } else {
1758                 store = ins;
1759         }
1760
1761         nargs = info->sig->param_count + info->sig->hasthis;
1762
1763         for (i = 1; i < nargs; i++) {
1764                 call->args [i - 1]->next = call->args [i];
1765         }
1766
1767         if (nargs)
1768                 call->args [nargs - 1]->next = store;
1769
1770         if (cfg->prev_ins) {
1771                 store->next = cfg->prev_ins->next;
1772                 if (nargs)
1773                         cfg->prev_ins->next =  call->args [0];
1774                 else
1775                         cfg->prev_ins->next = store;
1776         } else {
1777                 store->next = cfg->cbb->code;
1778                 if (nargs)              
1779                         cfg->cbb->code = call->args [0];
1780                 else
1781                         cfg->cbb->code = store;
1782         }
1783
1784         
1785         call->fptr = info->wrapper;
1786
1787         if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
1788                 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
1789                 *tree = *load;
1790         }
1791 }
1792
1793 static MonoMethodSignature *
1794 mono_get_element_address_signature (int arity)
1795 {
1796         static GHashTable *sighash = NULL;
1797         MonoMethodSignature *res;
1798         int i;
1799
1800         if (!sighash)
1801                 sighash = g_hash_table_new (NULL, NULL);
1802
1803
1804         if ((res = g_hash_table_lookup (sighash, (gpointer)arity)))
1805                 return res;
1806
1807         res = mono_metadata_signature_alloc (mono_defaults.corlib, arity + 1);
1808
1809         res->params [0] = &mono_defaults.array_class->byval_arg; 
1810         
1811         for (i = 1; i <= arity; i++)
1812                 res->params [i] = &mono_defaults.int_class->byval_arg;
1813
1814         res->ret = &mono_defaults.int_class->byval_arg;
1815
1816         g_hash_table_insert (sighash, (gpointer)arity, res);
1817
1818         return res;
1819 }
1820
1821 static void
1822 handle_stobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, MonoInst *src, const unsigned char *ip, MonoClass *klass, gboolean to_end, gboolean native) {
1823         MonoInst *iargs [3];
1824         int n;
1825
1826         g_assert (klass);
1827         /*
1828          * This check breaks with spilled vars... need to handle it during verification anyway.
1829          * g_assert (klass && klass == src->klass && klass == dest->klass);
1830          */
1831
1832         if (native)
1833                 n = mono_class_native_size (klass, NULL);
1834         else
1835                 n = mono_class_value_size (klass, NULL);
1836
1837         iargs [0] = dest;
1838         iargs [1] = src;
1839         NEW_ICONST (cfg, iargs [2], n);
1840
1841         mono_emit_native_call (cfg, bblock, helper_memcpy, helper_sig_memcpy, iargs, ip, to_end);
1842 }
1843
1844 static void
1845 handle_initobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, const guchar *ip, MonoClass *klass, MonoInst **stack_start, MonoInst **sp)
1846 {
1847         MonoInst *iargs [2];
1848         MonoInst *ins, *zero_int32;
1849         int n;
1850
1851         NEW_ICONST (cfg, zero_int32, 0);
1852
1853         mono_class_init (klass);
1854         n = mono_class_value_size (klass, NULL);
1855         MONO_INST_NEW (cfg, ins, 0);
1856         ins->cil_code = ip;
1857         ins->inst_left = dest;
1858         ins->inst_right = zero_int32;
1859         switch (n) {
1860         case 1:
1861                 ins->opcode = CEE_STIND_I1;
1862                 MONO_ADD_INS (bblock, ins);
1863                 break;
1864         case 2:
1865                 ins->opcode = CEE_STIND_I2;
1866                 MONO_ADD_INS (bblock, ins);
1867                 break;
1868         case 4:
1869                 ins->opcode = CEE_STIND_I4;
1870                 MONO_ADD_INS (bblock, ins);
1871                 break;
1872         default:
1873                 handle_loaded_temps (cfg, bblock, stack_start, sp);
1874                 NEW_ICONST (cfg, ins, n);
1875                 iargs [0] = dest;
1876                 iargs [1] = ins;
1877                 mono_emit_jit_icall (cfg, bblock, helper_initobj, iargs, ip);
1878                 break;
1879         }
1880 }
1881
1882 #define CODE_IS_STLOC(ip) (((ip) [0] >= CEE_STLOC_0 && (ip) [0] <= CEE_STLOC_3) || ((ip) [0] == CEE_STLOC_S))
1883
1884 static gboolean
1885 mono_method_check_inlining (MonoMethod *method)
1886 {
1887         MonoMethodHeader *header = ((MonoMethodNormal *)method)->header;
1888         MonoMethodSignature *signature = method->signature;
1889         int i;
1890
1891         /* fixme: we should inline wrappers */
1892         if (method->wrapper_type != MONO_WRAPPER_NONE)
1893                 return FALSE;
1894
1895         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
1896             (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
1897             (method->iflags & METHOD_IMPL_ATTRIBUTE_NOINLINING) ||
1898             (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) ||
1899             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1900             (method->klass->marshalbyref) ||
1901             !header || header->num_clauses ||
1902             /* fixme: why cant we inline valuetype returns? */
1903             MONO_TYPE_ISSTRUCT (signature->ret))
1904                 return FALSE;
1905
1906         /* its not worth to inline methods with valuetype arguments?? */
1907         for (i = 0; i < signature->param_count; i++) {
1908                 if (MONO_TYPE_ISSTRUCT (signature->params [i])) {
1909                         return FALSE;
1910                 }
1911         }
1912
1913         //if (!MONO_TYPE_IS_VOID (signature->ret)) return FALSE;
1914
1915         /* also consider num_locals? */
1916         if (header->code_size < 20)
1917                 return TRUE;
1918
1919         return FALSE;
1920 }
1921
1922 static MonoInst*
1923 mini_get_opcode_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
1924 {
1925         int pc, op;
1926         MonoInst *ins;
1927
1928         if (cmethod->klass == mono_defaults.string_class) {
1929                 if (cmethod->name [0] != 'g' || strcmp (cmethod->name, "get_Chars"))
1930                         return NULL;
1931                 op = OP_GETCHR;
1932         } else if (cmethod->klass == mono_defaults.math_class) {
1933                 if (strcmp (cmethod->name, "Sin") == 0)
1934                         op = OP_SIN;
1935                 else if (strcmp (cmethod->name, "Cos") == 0)
1936                         op = OP_COS;
1937                 else if (strcmp (cmethod->name, "Tan") == 0)
1938                         op = OP_TAN;
1939                 else if (strcmp (cmethod->name, "Atan") == 0)
1940                         op = OP_ATAN;
1941                 else if (strcmp (cmethod->name, "Sqrt") == 0)
1942                         op = OP_SQRT;
1943                 else if (strcmp (cmethod->name, "Abs") == 0 && fsig->params [0]->type == MONO_TYPE_R8)
1944                         op = OP_ABS;
1945                 else
1946                         return NULL;
1947         } else {
1948                 return NULL;
1949         }
1950         pc = fsig->param_count + fsig->hasthis;
1951         MONO_INST_NEW (cfg, ins, op);
1952
1953         if (pc > 0) {
1954                 ins->inst_i0 = args [0];
1955                 if (pc > 1)
1956                         ins->inst_i1 = args [1];
1957         }
1958
1959         return ins;
1960 }
1961
1962 static void
1963 mono_save_args (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, MonoInst **sp, MonoInst **args)
1964 {
1965         MonoInst *store, *temp;
1966         int i;
1967
1968         g_assert (!MONO_TYPE_ISSTRUCT (sig->ret));
1969
1970         if (!sig->hasthis && sig->param_count == 0) 
1971                 return;
1972
1973         if (sig->hasthis) {
1974                 if (sp [0]->opcode == OP_ICONST) {
1975                         *args++ = sp [0];
1976                 } else {
1977                         temp = mono_compile_create_var (cfg, type_from_stack_type (*sp), OP_LOCAL);
1978                         *args++ = temp;
1979                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
1980                         store->cil_code = sp [0]->cil_code;
1981                         MONO_ADD_INS (bblock, store);
1982                 }
1983                 sp++;
1984         }
1985
1986         for (i = 0; i < sig->param_count; ++i) {
1987                 if (sp [0]->opcode == OP_ICONST) {
1988                         *args++ = sp [0];
1989                 } else {
1990                         temp = mono_compile_create_var (cfg, type_from_stack_type (*sp), OP_LOCAL);
1991                         *args++ = temp;
1992                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
1993                         store->cil_code = sp [0]->cil_code;
1994                         if (store->opcode == CEE_STOBJ) {
1995                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
1996                                 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, temp->klass, FALSE, FALSE);
1997                         } else {
1998                                 MONO_ADD_INS (bblock, store);
1999                         } 
2000                 }
2001                 sp++;
2002         }
2003 }
2004
2005 /*
2006  * Some of these comments may well be out-of-date.
2007  * Design decisions: we do a single pass over the IL code (and we do bblock 
2008  * splitting/merging in the few cases when it's required: a back jump to an IL
2009  * address that was not already seen as bblock starting point).
2010  * Code is validated as we go (full verification is still better left to metadata/verify.c).
2011  * Complex operations are decomposed in simpler ones right away. We need to let the 
2012  * arch-specific code peek and poke inside this process somehow (except when the 
2013  * optimizations can take advantage of the full semantic info of coarse opcodes).
2014  * All the opcodes of the form opcode.s are 'normalized' to opcode.
2015  * MonoInst->opcode initially is the IL opcode or some simplification of that 
2016  * (OP_LOAD, OP_STORE). The arch-specific code may rearrange it to an arch-specific 
2017  * opcode with value bigger than OP_LAST.
2018  * At this point the IR can be handed over to an interpreter, a dumb code generator
2019  * or to the optimizing code generator that will translate it to SSA form.
2020  *
2021  * Profiling directed optimizations.
2022  * We may compile by default with few or no optimizations and instrument the code
2023  * or the user may indicate what methods to optimize the most either in a config file
2024  * or through repeated runs where the compiler applies offline the optimizations to 
2025  * each method and then decides if it was worth it.
2026  *
2027  * TODO:
2028  * * consider using an array instead of an hash table (bb_hash)
2029  */
2030
2031 #define CHECK_TYPE(ins) if (!(ins)->type) goto unverified
2032 #define CHECK_STACK(num) if ((sp - stack_start) < (num)) goto unverified
2033 #define CHECK_STACK_OVF(num) if (((sp - stack_start) + (num)) > header->max_stack) goto unverified
2034
2035 /* offset from br.s -> br like opcodes */
2036 #define BIG_BRANCH_OFFSET 13
2037
2038 /*
2039  * mono_method_to_ir: translates IL into basic blocks containing trees
2040  */
2041 static int
2042 mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
2043                    int locals_offset, MonoInst *return_var, GList *dont_inline, MonoInst **inline_args, 
2044                    guint inline_offset)
2045 {
2046         MonoInst *zero_int32, *zero_int64, *zero_ptr, *zero_obj, *zero_r8;
2047         MonoInst *ins, **sp, **stack_start;
2048         MonoBasicBlock *bblock, *tblock = NULL, *init_localsbb = NULL;
2049         GHashTable *bbhash;
2050         MonoMethod *cmethod;
2051         MonoInst **arg_array;
2052         MonoMethodHeader *header;
2053         MonoImage *image;
2054         guint32 token, ins_flag;
2055         MonoClass *klass;
2056         unsigned char *ip, *end, *target;
2057         static double r8_0 = 0.0;
2058         MonoMethodSignature *sig;
2059         MonoType **param_types;
2060         GList *bb_recheck = NULL, *tmp;
2061         int i, n, start_new_bblock, align;
2062         int num_calls = 0, inline_costs = 0;
2063         int *filter_lengths = NULL;
2064         int breakpoint_id = 0;
2065         guint real_offset;
2066
2067         image = method->klass->image;
2068         header = ((MonoMethodNormal *)method)->header;
2069         sig = method->signature;
2070         ip = (unsigned char*)header->code;
2071         end = ip + header->code_size;
2072         mono_jit_stats.cil_code_size += header->code_size;
2073
2074         if (cfg->method == method) {
2075                 real_offset = 0;
2076                 bbhash = cfg->bb_hash;
2077         } else {
2078                 real_offset = inline_offset;
2079                 bbhash = g_hash_table_new (g_direct_hash, NULL);
2080         }
2081
2082         if (cfg->method == method) {
2083
2084                 /* ENTRY BLOCK */
2085                 cfg->bb_entry = start_bblock = NEW_BBLOCK (cfg);
2086                 start_bblock->cil_code = NULL;
2087                 start_bblock->cil_length = 0;
2088                 start_bblock->block_num = cfg->num_bblocks++;
2089
2090                 /* EXIT BLOCK */
2091                 cfg->bb_exit = end_bblock = NEW_BBLOCK (cfg);
2092                 end_bblock->cil_code = NULL;
2093                 end_bblock->cil_length = 0;
2094                 end_bblock->block_num = cfg->num_bblocks++;
2095                 g_assert (cfg->num_bblocks == 2);
2096
2097                 arg_array = alloca (sizeof (MonoInst *) * (sig->hasthis + sig->param_count));
2098                 for (i = sig->hasthis + sig->param_count - 1; i >= 0; i--)
2099                         arg_array [i] = cfg->varinfo [i];
2100
2101                 if (mono_compile_aot) 
2102                         cfg->opt |= MONO_OPT_SAHRED;
2103
2104                 if (header->num_clauses) {
2105                         int size = sizeof (int) * header->num_clauses;
2106                         filter_lengths = alloca (size);
2107                         memset (filter_lengths, 0, size);
2108                 }
2109                 /* handle exception clauses */
2110                 for (i = 0; i < header->num_clauses; ++i) {
2111                         //unsigned char *p = ip;
2112                         MonoExceptionClause *clause = &header->clauses [i];
2113                         GET_BBLOCK (cfg, bbhash, tblock, ip + clause->try_offset);
2114                         tblock->real_offset = clause->try_offset;
2115                         GET_BBLOCK (cfg, bbhash, tblock, ip + clause->handler_offset);
2116                         tblock->real_offset = clause->handler_offset;
2117                         /*g_print ("clause try IL_%04x to IL_%04x handler %d at IL_%04x to IL_%04x\n", clause->try_offset, clause->try_offset + clause->try_len, clause->flags, clause->handler_offset, clause->handler_offset + clause->handler_len);
2118                           while (p < end) {
2119                           g_print ("%s", mono_disasm_code_one (NULL, method, p, &p));
2120                           }*/
2121                         /* catch and filter blocks get the exception object on the stack */
2122                         if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE ||
2123                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
2124                                 /* mostly like handle_stack_args (), but just sets the input args */
2125                                 /* g_print ("handling clause at IL_%04x\n", clause->handler_offset); */
2126                                 if (!cfg->exvar) {
2127                                         cfg->exvar = mono_compile_create_var (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL);
2128                                         /* prevent it from being register allocated */
2129                                         cfg->exvar->flags |= MONO_INST_INDIRECT;
2130                                 }
2131                                 tblock->in_scount = 1;
2132                                 tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
2133                                 tblock->in_stack [0] = cfg->exvar;
2134                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
2135                                         GET_BBLOCK (cfg, bbhash, tblock, ip + clause->token_or_filter);
2136                                         tblock->real_offset = clause->token_or_filter;
2137                                         tblock->in_scount = 1;
2138                                         tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
2139                                         tblock->in_stack [0] = cfg->exvar;
2140                                 }
2141                         }
2142                 }
2143
2144         } else {
2145                 arg_array = alloca (sizeof (MonoInst *) * (sig->hasthis + sig->param_count));
2146                 mono_save_args (cfg, start_bblock, sig, inline_args, arg_array);
2147         }
2148
2149         /* FIRST CODE BLOCK */
2150         bblock = NEW_BBLOCK (cfg);
2151         bblock->cil_code = ip;
2152
2153         ADD_BBLOCK (cfg, bbhash, bblock);
2154
2155         if (cfg->method == method) {
2156                 breakpoint_id = mono_debugger_method_has_breakpoint (method);
2157                 if (breakpoint_id && (mono_debug_format != MONO_DEBUG_FORMAT_DEBUGGER)) {
2158                         MONO_INST_NEW (cfg, ins, CEE_BREAK);
2159                         MONO_ADD_INS (bblock, ins);
2160                 }
2161         }
2162         
2163         if ((header->init_locals || (cfg->method == method && (cfg->opt & MONO_OPT_SAHRED)))) {
2164                 /* we use a separate basic block for the initialization code */
2165                 cfg->bb_init = init_localsbb = NEW_BBLOCK (cfg);
2166                 init_localsbb->real_offset = real_offset;
2167                 start_bblock->next_bb = init_localsbb;
2168                 init_localsbb->next_bb = bblock;
2169                 link_bblock (cfg, start_bblock, init_localsbb);
2170                 link_bblock (cfg, init_localsbb, bblock);
2171                 init_localsbb->block_num = cfg->num_bblocks++;
2172         } else {
2173                 start_bblock->next_bb = bblock;
2174                 link_bblock (cfg, start_bblock, bblock);
2175         }
2176
2177         mono_debug_init_method (cfg, bblock, breakpoint_id);
2178
2179         param_types = mono_mempool_alloc (cfg->mempool, sizeof (MonoType*) * (sig->hasthis + sig->param_count));
2180         if (sig->hasthis)
2181                 param_types [0] = method->klass->valuetype?&method->klass->this_arg:&method->klass->byval_arg;
2182         for (n = 0; n < sig->param_count; ++n)
2183                 param_types [n + sig->hasthis] = sig->params [n];
2184
2185         /* do this somewhere outside - not here */
2186         NEW_ICONST (cfg, zero_int32, 0);
2187         NEW_ICONST (cfg, zero_int64, 0);
2188         zero_int64->type = STACK_I8;
2189         NEW_PCONST (cfg, zero_ptr, 0);
2190         NEW_PCONST (cfg, zero_obj, 0);
2191         zero_obj->type = STACK_OBJ;
2192
2193         MONO_INST_NEW (cfg, zero_r8, OP_R8CONST);
2194         zero_r8->type = STACK_R8;
2195         zero_r8->inst_p0 = &r8_0;
2196
2197         /* add a check for this != NULL to inlined methods */
2198         if (cfg->method != method && sig->hasthis) {
2199                 MONO_INST_NEW (cfg, ins, OP_CHECK_THIS);
2200                 NEW_ARGLOAD (cfg, ins->inst_left, 0);
2201                 ins->cil_code = ip;
2202                 MONO_ADD_INS (bblock, ins);
2203         }
2204
2205         /* we use a spare stack slot in SWITCH and NEWOBJ and others */
2206         stack_start = sp = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (header->max_stack + 1));
2207
2208         ins_flag = 0;
2209         start_new_bblock = 0;
2210         while (ip < end) {
2211
2212                 if (cfg->method == method)
2213                         real_offset = ip - header->code;
2214                 else
2215                         real_offset = inline_offset;
2216
2217                 if (start_new_bblock) {
2218                         bblock->cil_length = ip - bblock->cil_code;
2219                         if (start_new_bblock == 2) {
2220                                 g_assert (ip == tblock->cil_code);
2221                         } else {
2222                                 GET_BBLOCK (cfg, bbhash, tblock, ip);
2223                         }
2224                         bblock->next_bb = tblock;
2225                         bblock = tblock;
2226                         start_new_bblock = 0;
2227                         for (i = 0; i < bblock->in_scount; ++i) {
2228                                 NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
2229                                 *sp++ = ins;
2230                         }
2231                 } else {
2232                         if ((tblock = g_hash_table_lookup (bbhash, ip)) && (tblock != bblock)) {
2233                                 link_bblock (cfg, bblock, tblock);
2234                                 if (sp != stack_start) {
2235                                         handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
2236                                         sp = stack_start;
2237                                 }
2238                                 bblock->next_bb = tblock;
2239                                 bblock = tblock;
2240                                 for (i = 0; i < bblock->in_scount; ++i) {
2241                                         NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
2242                                         *sp++ = ins;
2243                                 }
2244                         }
2245                 }
2246
2247                 if (cfg->verbose_level > 3)
2248                         g_print ("converting (in B%d: stack: %d) %s", bblock->block_num, sp-stack_start, mono_disasm_code_one (NULL, method, ip, NULL));
2249
2250                 switch (*ip) {
2251                 case CEE_NOP:
2252                         ++ip;
2253                         break;
2254                 case CEE_BREAK:
2255                         MONO_INST_NEW (cfg, ins, CEE_BREAK);
2256                         ins->cil_code = ip++;
2257                         MONO_ADD_INS (bblock, ins);
2258                         break;
2259                 case CEE_LDARG_0:
2260                 case CEE_LDARG_1:
2261                 case CEE_LDARG_2:
2262                 case CEE_LDARG_3:
2263                         CHECK_STACK_OVF (1);
2264                         n = (*ip)-CEE_LDARG_0;
2265                         NEW_ARGLOAD (cfg, ins, n);
2266                         ins->cil_code = ip++;
2267                         *sp++ = ins;
2268                         break;
2269                 case CEE_LDLOC_0:
2270                 case CEE_LDLOC_1:
2271                 case CEE_LDLOC_2:
2272                 case CEE_LDLOC_3:
2273                         CHECK_STACK_OVF (1);
2274                         n = (*ip)-CEE_LDLOC_0;
2275                         NEW_LOCLOAD (cfg, ins, n);
2276                         ins->cil_code = ip++;
2277                         *sp++ = ins;
2278                         break;
2279                 case CEE_STLOC_0:
2280                 case CEE_STLOC_1:
2281                 case CEE_STLOC_2:
2282                 case CEE_STLOC_3:
2283                         CHECK_STACK (1);
2284                         n = (*ip)-CEE_STLOC_0;
2285                         --sp;
2286                         handle_loaded_temps (cfg, bblock, stack_start, sp);
2287                         NEW_LOCSTORE (cfg, ins, n, *sp);
2288                         ins->cil_code = ip;
2289                         if (ins->opcode == CEE_STOBJ) {
2290                                 NEW_LOCLOADA (cfg, ins, n);
2291                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
2292                         } else
2293                                 MONO_ADD_INS (bblock, ins);
2294                         ++ip;
2295                         inline_costs += 1;
2296                         break;
2297                 case CEE_LDARG_S:
2298                         CHECK_STACK_OVF (1);
2299                         NEW_ARGLOAD (cfg, ins, ip [1]);
2300                         ins->cil_code = ip;
2301                         *sp++ = ins;
2302                         ip += 2;
2303                         break;
2304                 case CEE_LDARGA_S:
2305                         CHECK_STACK_OVF (1);
2306                         NEW_ARGLOADA (cfg, ins, ip [1]);
2307                         ins->cil_code = ip;
2308                         *sp++ = ins;
2309                         ip += 2;
2310                         break;
2311                 case CEE_STARG_S:
2312                         CHECK_STACK (1);
2313                         --sp;
2314                         NEW_ARGSTORE (cfg, ins, ip [1], *sp);
2315                         handle_loaded_temps (cfg, bblock, stack_start, sp);
2316                         ins->cil_code = ip;
2317                         if (ins->opcode == CEE_STOBJ) {
2318                                 NEW_ARGLOADA (cfg, ins, ip [1]);
2319                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
2320                         } else
2321                                 MONO_ADD_INS (bblock, ins);
2322                         ip += 2;
2323                         break;
2324                 case CEE_LDLOC_S:
2325                         CHECK_STACK_OVF (1);
2326                         NEW_LOCLOAD (cfg, ins, ip [1]);
2327                         ins->cil_code = ip;
2328                         *sp++ = ins;
2329                         ip += 2;
2330                         break;
2331                 case CEE_LDLOCA_S:
2332                         CHECK_STACK_OVF (1);
2333                         NEW_LOCLOADA (cfg, ins, ip [1]);
2334                         ins->cil_code = ip;
2335                         *sp++ = ins;
2336                         ip += 2;
2337                         break;
2338                 case CEE_STLOC_S:
2339                         CHECK_STACK (1);
2340                         --sp;
2341                         handle_loaded_temps (cfg, bblock, stack_start, sp);
2342                         NEW_LOCSTORE (cfg, ins, ip [1], *sp);
2343                         ins->cil_code = ip;
2344                         if (ins->opcode == CEE_STOBJ) {
2345                                 NEW_LOCLOADA (cfg, ins, ip [1]);
2346                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
2347                         } else
2348                                 MONO_ADD_INS (bblock, ins);
2349                         ip += 2;
2350                         inline_costs += 1;
2351                         break;
2352                 case CEE_LDNULL:
2353                         CHECK_STACK_OVF (1);
2354                         NEW_PCONST (cfg, ins, NULL);
2355                         ins->cil_code = ip;
2356                         ins->type = STACK_OBJ;
2357                         ++ip;
2358                         *sp++ = ins;
2359                         break;
2360                 case CEE_LDC_I4_M1:
2361                         CHECK_STACK_OVF (1);
2362                         NEW_ICONST (cfg, ins, -1);
2363                         ins->cil_code = ip;
2364                         ++ip;
2365                         *sp++ = ins;
2366                         break;
2367                 case CEE_LDC_I4_0:
2368                 case CEE_LDC_I4_1:
2369                 case CEE_LDC_I4_2:
2370                 case CEE_LDC_I4_3:
2371                 case CEE_LDC_I4_4:
2372                 case CEE_LDC_I4_5:
2373                 case CEE_LDC_I4_6:
2374                 case CEE_LDC_I4_7:
2375                 case CEE_LDC_I4_8:
2376                         CHECK_STACK_OVF (1);
2377                         NEW_ICONST (cfg, ins, (*ip) - CEE_LDC_I4_0);
2378                         ins->cil_code = ip;
2379                         ++ip;
2380                         *sp++ = ins;
2381                         break;
2382                 case CEE_LDC_I4_S:
2383                         CHECK_STACK_OVF (1);
2384                         ++ip;
2385                         NEW_ICONST (cfg, ins, *((signed char*)ip));
2386                         ins->cil_code = ip;
2387                         ++ip;
2388                         *sp++ = ins;
2389                         break;
2390                 case CEE_LDC_I4:
2391                         CHECK_STACK_OVF (1);
2392                         NEW_ICONST (cfg, ins, (gint32)read32 (ip + 1));
2393                         ins->cil_code = ip;
2394                         ip += 5;
2395                         *sp++ = ins;
2396                         break;
2397                 case CEE_LDC_I8:
2398                         CHECK_STACK_OVF (1);
2399                         MONO_INST_NEW (cfg, ins, OP_I8CONST);
2400                         ins->cil_code = ip;
2401                         ins->type = STACK_I8;
2402                         ++ip;
2403                         ins->inst_l = (gint64)read64 (ip);
2404                         ip += 8;
2405                         *sp++ = ins;
2406                         break;
2407                 case CEE_LDC_R4: {
2408                         float *f = g_malloc (sizeof (float));
2409                         CHECK_STACK_OVF (1);
2410                         MONO_INST_NEW (cfg, ins, OP_R4CONST);
2411                         ins->type = STACK_R8;
2412                         ++ip;
2413                         readr4 (ip, f);
2414                         ins->inst_p0 = f;
2415                         ip += 4;
2416                         *sp++ = ins;                    
2417                         break;
2418                 }
2419                 case CEE_LDC_R8: {
2420                         double *d = g_malloc (sizeof (double));
2421                         CHECK_STACK_OVF (1);
2422                         MONO_INST_NEW (cfg, ins, OP_R8CONST);
2423                         ins->type = STACK_R8;
2424                         ++ip;
2425                         readr8 (ip, d);
2426                         ins->inst_p0 = d;
2427                         ip += 8;
2428                         *sp++ = ins;                    
2429                         break;
2430                 }
2431                 case CEE_DUP: {
2432                         MonoInst *temp, *store;
2433                         CHECK_STACK (1);
2434                         CHECK_STACK_OVF (1);
2435                         sp--;
2436                         ins = *sp;
2437                 
2438                         /* 
2439                          * small optimization: if the loaded value was from a local already,
2440                          * just load it twice.
2441                          */
2442                         if (ins->ssa_op == MONO_SSA_LOAD && 
2443                             (ins->inst_i0->opcode == OP_LOCAL || ins->inst_i0->opcode == OP_ARG)) {
2444                                 sp++;
2445                                 MONO_INST_NEW (cfg, temp, 0);
2446                                 *temp = *ins;
2447                                 temp->cil_code = ip;
2448                                 *sp++ = temp;
2449                         } else {
2450                                 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
2451                                 temp->cil_code = ip;
2452                                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2453                                 store->cil_code = ip;
2454                                 MONO_ADD_INS (bblock, store);
2455                                 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
2456                                 *sp++ = ins;
2457                                 ins->cil_code = ip;
2458                                 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
2459                                 *sp++ = ins;
2460                                 ins->cil_code = ip;
2461                         }
2462                         ++ip;
2463                         inline_costs += 2;
2464                         break;
2465                 }
2466                 case CEE_POP:
2467                         CHECK_STACK (1);
2468                         MONO_INST_NEW (cfg, ins, CEE_POP);
2469                         MONO_ADD_INS (bblock, ins);
2470                         ins->cil_code = ip++;
2471                         --sp;
2472                         ins->inst_i0 = *sp;
2473                         break;
2474                 case CEE_JMP:
2475                         if (stack_start != sp)
2476                                 goto unverified;
2477                         MONO_INST_NEW (cfg, ins, CEE_JMP);
2478                         token = read32 (ip + 1);
2479                         /* FIXME: check the signature matches */
2480                         cmethod = mono_get_method (image, token, NULL);
2481                         /*
2482                          * The current magic trampoline can't handle this
2483                          * apparently, so we compile the method right away.
2484                          * Later, we may need to fix the trampoline or use a different one.
2485                          */
2486                         ins->inst_p0 = mono_compile_method (cmethod);
2487                         MONO_ADD_INS (bblock, ins);
2488                         ip += 5;
2489                         start_new_bblock = 1;
2490                         break;
2491                 case CEE_CALLI:
2492                 case CEE_CALL:
2493                 case CEE_CALLVIRT: {
2494                         MonoInst *addr = NULL;
2495                         MonoMethodSignature *fsig = NULL;
2496                         MonoMethodHeader *cheader;
2497                         int temp, array_rank = 0;
2498                         int virtual = *ip == CEE_CALLVIRT;
2499
2500                         token = read32 (ip + 1);
2501
2502                         if (*ip == CEE_CALLI) {
2503                                 cmethod = NULL;
2504                                 cheader = NULL;
2505                                 CHECK_STACK (1);
2506                                 --sp;
2507                                 addr = *sp;
2508                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
2509                                         fsig = (MonoMethodSignature *)mono_method_get_wrapper_data (method, token);
2510                                 else
2511                                         fsig = mono_metadata_parse_signature (image, token);
2512
2513                                 n = fsig->param_count + fsig->hasthis;
2514
2515                         } else {
2516                                 cmethod = mono_get_method (image, token, NULL);
2517                                 cheader = ((MonoMethodNormal *)cmethod)->header;
2518
2519                                 if (!cmethod->klass->inited)
2520                                         mono_class_init (cmethod->klass);
2521
2522                                 if (cmethod->signature->pinvoke) {
2523 #ifdef MONO_USE_EXC_TABLES
2524                                         if (mono_method_blittable (cmethod)) {
2525                                                 fsig = cmethod->signature;
2526                                         } else {
2527 #endif
2528                                                 MonoMethod *wrapper = mono_marshal_get_native_wrapper (cmethod);
2529                                                 fsig = wrapper->signature;
2530 #ifdef MONO_USE_EXC_TABLES
2531                                         }
2532 #endif
2533                                 } else {
2534                                         fsig = cmethod->signature;
2535                                 }
2536
2537                                 n = fsig->param_count + fsig->hasthis;
2538
2539                                 if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL &&
2540                                     cmethod->klass->parent == mono_defaults.array_class) {
2541                                         array_rank = cmethod->klass->rank;
2542                                 }
2543
2544                                 if (cmethod->string_ctor)
2545                                         g_assert_not_reached ();
2546
2547                         }
2548
2549                         CHECK_STACK (n);
2550
2551                         //g_assert (!virtual || fsig->hasthis);
2552
2553                         sp -= n;
2554
2555                         if (cmethod && (cfg->opt & MONO_OPT_INTRINS) && (ins = mini_get_opcode_for_method (cfg, cmethod, fsig, sp))) {
2556                                 ins->cil_code = ip;
2557
2558                                 if (MONO_TYPE_IS_VOID (fsig->ret)) {
2559                                         MONO_ADD_INS (bblock, ins);
2560                                 } else {
2561                                         type_to_eval_stack_type (fsig->ret, ins);
2562                                         *sp = ins;
2563                                         sp++;
2564                                 }
2565
2566                                 ip += 5;
2567                                 break;
2568                         }
2569
2570                         if ((cfg->opt & MONO_OPT_INLINE) && 
2571                             (!virtual || !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) || (cmethod->flags & METHOD_ATTRIBUTE_FINAL)) && 
2572                             cmethod && cheader && mono_method_check_inlining (cmethod) &&
2573                             method != cmethod && !g_list_find (dont_inline, cmethod)) {
2574                                 MonoInst *rvar = NULL;
2575                                 MonoBasicBlock *ebblock, *sbblock;
2576                                 int costs, new_locals_offset;
2577                                 
2578                                 if (cfg->verbose_level > 2)
2579                                         g_print ("INLINE START %p %s\n", cmethod,  mono_method_full_name (cmethod, TRUE));
2580
2581                                 if (!cmethod->inline_info) {
2582                                         mono_jit_stats.inlineable_methods++;
2583                                         cmethod->inline_info = 1;
2584                                 }
2585                                 /* allocate space to store the return value */
2586                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) 
2587                                         rvar =  mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
2588
2589                                 /* allocate local variables */
2590                                 new_locals_offset = cfg->num_varinfo;
2591                                 for (i = 0; i < cheader->num_locals; ++i)
2592                                         mono_compile_create_var (cfg, cheader->locals [i], OP_LOCAL);
2593                                 
2594                                 /* allocate starte and end blocks */
2595                                 sbblock = NEW_BBLOCK (cfg);
2596                                 sbblock->block_num = cfg->num_bblocks++;
2597                                 sbblock->real_offset = real_offset;
2598
2599                                 ebblock = NEW_BBLOCK (cfg);
2600                                 ebblock->block_num = cfg->num_bblocks++;
2601                                 ebblock->real_offset = real_offset;
2602                                 
2603                                 dont_inline = g_list_prepend (dont_inline, method);
2604                                 costs = mono_method_to_ir (cfg, cmethod, sbblock, ebblock, new_locals_offset, rvar, dont_inline, sp, real_offset);
2605                                 dont_inline = g_list_remove (dont_inline, method);
2606                                 
2607                                 if (costs >= 0 && costs < 60) {
2608
2609                                         mono_jit_stats.inlined_methods++;
2610
2611                                         /* always add some code to avoid block split failures */
2612                                         MONO_INST_NEW (cfg, ins, CEE_NOP);
2613                                         MONO_ADD_INS (bblock, ins);
2614                                         ins->cil_code = ip;
2615
2616                                         ip += 5;
2617                                         real_offset += 5;
2618
2619                                         bblock->next_bb = sbblock;
2620                                         link_bblock (cfg, bblock, sbblock);
2621
2622                                         GET_BBLOCK (cfg, bbhash, bblock, ip);
2623                                         ebblock->next_bb = bblock;
2624                                         link_bblock (cfg, ebblock, bblock);
2625
2626                                         if (rvar) {
2627                                                 NEW_TEMPLOAD (cfg, ins, rvar->inst_c0);
2628                                                 *sp++ = ins;
2629                                         }
2630                                         if (sp != stack_start) {
2631                                                 handle_stack_args (cfg, ebblock, stack_start, sp - stack_start);
2632                                                 sp = stack_start;
2633                                         }
2634                                         start_new_bblock = 1;
2635                                         if (cfg->verbose_level > 2)
2636                                                 g_print ("INLINE END %s\n", mono_method_full_name (cmethod, TRUE));
2637                                         
2638                                         // { static int c = 0; printf ("ICOUNT %d %d %s\n", c++, costs, mono_method_full_name (cmethod, TRUE)); }
2639
2640                                         inline_costs += costs;
2641                                         break;
2642                                 } else {
2643
2644                                         if (cfg->verbose_level > 2)
2645                                                 g_print ("INLINE ABORTED %s\n", mono_method_full_name (cmethod, TRUE));
2646
2647                                 }
2648                         }
2649                         
2650                         inline_costs += 10 * num_calls++;
2651                         handle_loaded_temps (cfg, bblock, stack_start, sp);
2652
2653                         /* tail recursion elimination */
2654                         if ((cfg->opt & MONO_OPT_TAILC) && *ip == CEE_CALL && cmethod == cfg->method && ip [5] == CEE_RET) {
2655                                 gboolean has_vtargs = FALSE;
2656                                 int i;
2657                                 
2658                                 /* keep it simple */
2659                                 for (i =  fsig->param_count - 1; i >= 0; i--) {
2660                                         if (MONO_TYPE_ISSTRUCT (cmethod->signature->params [i])) 
2661                                                 has_vtargs = TRUE;
2662                                 }
2663
2664                                 if (!has_vtargs) {
2665                                         for (i = 0; i < n; ++i) {
2666                                                 NEW_ARGSTORE (cfg, ins, i, sp [i]);
2667                                                 ins->cil_code = ip;
2668                                                 MONO_ADD_INS (bblock, ins);
2669                                         }
2670                                         MONO_INST_NEW (cfg, ins, CEE_BR);
2671                                         ins->cil_code = ip;
2672                                         MONO_ADD_INS (bblock, ins);
2673                                         tblock = start_bblock->out_bb [0];
2674                                         link_bblock (cfg, bblock, tblock);
2675                                         ins->inst_target_bb = tblock;
2676                                         start_new_bblock = 1;
2677                                         ip += 5;
2678                                         
2679                                         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
2680                                                 /* just create a dummy - the value is never used */
2681                                                 ins = mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
2682                                                 NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
2683                                                 sp++;
2684                                         }
2685
2686                                         break;
2687                                 }
2688                         }
2689
2690                         if (*ip == CEE_CALLI) {
2691
2692                                 if ((temp = mono_emit_calli (cfg, bblock, fsig, sp, addr, ip)) != -1) {
2693                                         NEW_TEMPLOAD (cfg, *sp, temp);
2694                                         sp++;
2695                                 }
2696                                         
2697                         } else if (array_rank) {
2698                                 MonoMethodSignature *esig;
2699                                 MonoInst *addr;
2700
2701                                 if (strcmp (cmethod->name, "Set") == 0) { /* array Set */ 
2702                                         esig = mono_get_element_address_signature (fsig->param_count - 1);
2703                                         
2704                                         temp = mono_emit_native_call (cfg, bblock, ves_array_element_address, esig, sp, ip, FALSE);
2705                                         NEW_TEMPLOAD (cfg, addr, temp);
2706                                         NEW_INDSTORE (cfg, ins, addr, sp [fsig->param_count], fsig->params [fsig->param_count - 1]);
2707                                         ins->cil_code = ip;
2708                                         if (ins->opcode == CEE_STOBJ) {
2709                                                 handle_stobj (cfg, bblock, addr, sp [fsig->param_count], ip, mono_class_from_mono_type (fsig->params [fsig->param_count-1]), FALSE, FALSE);
2710                                         } else {
2711                                                 MONO_ADD_INS (bblock, ins);
2712                                         }
2713
2714                                 } else if (strcmp (cmethod->name, "Get") == 0) { /* array Get */
2715                                         esig = mono_get_element_address_signature (fsig->param_count);
2716
2717                                         temp = mono_emit_native_call (cfg, bblock, ves_array_element_address, esig, sp, ip, FALSE);
2718                                         NEW_TEMPLOAD (cfg, addr, temp);
2719                                         NEW_INDLOAD (cfg, ins, addr, fsig->ret);
2720                                         ins->cil_code = ip;
2721
2722                                         *sp++ = ins;
2723                                 } else if (strcmp (cmethod->name, "Address") == 0) { /* array Address */
2724                                         /* implement me */
2725                                         esig = mono_get_element_address_signature (fsig->param_count);
2726
2727                                         temp = mono_emit_native_call (cfg, bblock, ves_array_element_address, esig, sp, ip, FALSE);
2728                                         NEW_TEMPLOAD (cfg, *sp, temp);
2729                                         sp++;
2730                                 } else {
2731                                         g_assert_not_reached ();
2732                                 }
2733
2734                         } else {
2735                                 if (0 && CODE_IS_STLOC (ip + 5) && (!MONO_TYPE_ISSTRUCT (fsig->ret)) && (!MONO_TYPE_IS_VOID (fsig->ret) || cmethod->string_ctor)) {
2736                                         /* no need to spill */
2737                                         ins = (MonoInst*)mono_emit_method_call (cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL);
2738                                         *sp++ = ins;
2739                                 } else {
2740                                         if ((temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, sp, ip, virtual ? sp [0] : NULL)) != -1) {
2741                                                 NEW_TEMPLOAD (cfg, *sp, temp);
2742                                                 sp++;
2743                                         }
2744                                 }
2745                         }
2746
2747                         ip += 5;
2748                         break;
2749                 }
2750                 case CEE_RET:
2751                         if (cfg->method != method) {
2752                                 /* return from inlined methode */
2753                                 if (return_var) {
2754                                         MonoInst *store;
2755                                         CHECK_STACK (1);
2756                                         --sp;
2757                                         //g_assert (returnvar != -1);
2758                                         NEW_TEMPSTORE (cfg, store, return_var->inst_c0, *sp);
2759                                         store->cil_code = sp [0]->cil_code;
2760                                         if (store->opcode == CEE_STOBJ) {
2761                                                 g_assert_not_reached ();
2762                                                 NEW_TEMPLOADA (cfg, store, return_var->inst_c0);
2763                                                 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, return_var->klass, FALSE, FALSE);
2764                                         } else
2765                                                 MONO_ADD_INS (bblock, store);
2766                                 } 
2767                         } else {
2768                                 if (cfg->ret) {
2769                                         g_assert (!return_var);
2770                                         CHECK_STACK (1);
2771                                         --sp;
2772                                         MONO_INST_NEW (cfg, ins, CEE_NOP);
2773                                         ins->opcode = mono_type_to_stind (method->signature->ret);
2774                                         if (ins->opcode == CEE_STOBJ) {
2775                                                 NEW_RETLOADA (cfg, ins);
2776                                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
2777                                         } else {
2778                                                 ins->opcode = OP_SETRET;
2779                                                 ins->cil_code = ip;
2780                                                 ins->inst_i0 = *sp;;
2781                                                 ins->inst_i1 = NULL;
2782                                                 MONO_ADD_INS (bblock, ins);
2783                                         }
2784                                 }
2785                         }
2786                         if (sp != stack_start)
2787                                 goto unverified;
2788                         MONO_INST_NEW (cfg, ins, CEE_BR);
2789                         ins->cil_code = ip++;
2790                         ins->inst_target_bb = end_bblock;
2791                         MONO_ADD_INS (bblock, ins);
2792                         link_bblock (cfg, bblock, end_bblock);
2793                         start_new_bblock = 1;
2794                         break;
2795                 case CEE_BR_S:
2796                         MONO_INST_NEW (cfg, ins, CEE_BR);
2797                         ins->cil_code = ip++;
2798                         MONO_ADD_INS (bblock, ins);
2799                         target = ip + 1 + (signed char)(*ip);
2800                         ++ip;
2801                         GET_BBLOCK (cfg, bbhash, tblock, target);
2802                         link_bblock (cfg, bblock, tblock);
2803                         CHECK_BBLOCK (target, ip, tblock);
2804                         ins->inst_target_bb = tblock;
2805                         if (sp != stack_start) {
2806                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
2807                                 sp = stack_start;
2808                         }
2809                         start_new_bblock = 1;
2810                         inline_costs += 10;
2811                         break;
2812                 case CEE_BRFALSE_S:
2813                 case CEE_BRTRUE_S:
2814                         CHECK_STACK (1);
2815                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
2816                         ins->cil_code = ip++;
2817                         target = ip + 1 + *(signed char*)ip;
2818                         ip++;
2819                         ADD_UNCOND (ins->opcode == CEE_BRTRUE);
2820                         if (sp != stack_start) {
2821                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
2822                                 sp = stack_start;
2823                         }
2824                         inline_costs += 10;
2825                         break;
2826                 case CEE_BEQ_S:
2827                 case CEE_BGE_S:
2828                 case CEE_BGT_S:
2829                 case CEE_BLE_S:
2830                 case CEE_BLT_S:
2831                 case CEE_BNE_UN_S:
2832                 case CEE_BGE_UN_S:
2833                 case CEE_BGT_UN_S:
2834                 case CEE_BLE_UN_S:
2835                 case CEE_BLT_UN_S:
2836                         CHECK_STACK (2);
2837                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
2838                         ins->cil_code = ip++;
2839                         target = ip + 1 + *(signed char*)ip;
2840                         ip++;
2841                         ADD_BINCOND (NULL);
2842                         if (sp != stack_start) {
2843                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
2844                                 sp = stack_start;
2845                         }
2846                         inline_costs += 10;
2847                         break;
2848                 case CEE_BR:
2849                         MONO_INST_NEW (cfg, ins, CEE_BR);
2850                         ins->cil_code = ip++;
2851                         MONO_ADD_INS (bblock, ins);
2852                         target = ip + 4 + (gint32)read32(ip);
2853                         ip += 4;
2854                         GET_BBLOCK (cfg, bbhash, tblock, target);
2855                         link_bblock (cfg, bblock, tblock);
2856                         CHECK_BBLOCK (target, ip, tblock);
2857                         ins->inst_target_bb = tblock;
2858                         if (sp != stack_start) {
2859                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
2860                                 sp = stack_start;
2861                         }
2862                         start_new_bblock = 1;
2863                         inline_costs += 10;
2864                         break;
2865                 case CEE_BRFALSE:
2866                 case CEE_BRTRUE:
2867                         CHECK_STACK (1);
2868                         MONO_INST_NEW (cfg, ins, *ip);
2869                         ins->cil_code = ip++;
2870                         target = ip + 4 + (gint32)read32(ip);
2871                         ip += 4;
2872                         ADD_UNCOND(ins->opcode == CEE_BRTRUE);
2873                         if (sp != stack_start) {
2874                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
2875                                 sp = stack_start;
2876                         }
2877                         inline_costs += 10;
2878                         break;
2879                 case CEE_BEQ:
2880                 case CEE_BGE:
2881                 case CEE_BGT:
2882                 case CEE_BLE:
2883                 case CEE_BLT:
2884                 case CEE_BNE_UN:
2885                 case CEE_BGE_UN:
2886                 case CEE_BGT_UN:
2887                 case CEE_BLE_UN:
2888                 case CEE_BLT_UN:
2889                         CHECK_STACK (2);
2890                         MONO_INST_NEW (cfg, ins, *ip);
2891                         ins->cil_code = ip++;
2892                         target = ip + 4 + (gint32)read32(ip);
2893                         ip += 4;
2894                         ADD_BINCOND(NULL);
2895                         if (sp != stack_start) {
2896                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
2897                                 sp = stack_start;
2898                         }
2899                         inline_costs += 10;
2900                         break;
2901                 case CEE_SWITCH:
2902                         CHECK_STACK (1);
2903                         n = read32 (ip + 1);
2904                         MONO_INST_NEW (cfg, ins, *ip);
2905                         --sp;
2906                         ins->inst_left = *sp;
2907                         if (ins->inst_left->type != STACK_I4) goto unverified;
2908                         ins->cil_code = ip;
2909                         ip += 5;
2910                         target = ip + n * sizeof (guint32);
2911                         MONO_ADD_INS (bblock, ins);
2912                         GET_BBLOCK (cfg, bbhash, tblock, target);
2913                         link_bblock (cfg, bblock, tblock);
2914                         ins->klass = GUINT_TO_POINTER (n);
2915                         ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (n + 1));
2916                         ins->inst_many_bb [n] = tblock;
2917
2918                         for (i = 0; i < n; ++i) {
2919                                 GET_BBLOCK (cfg, bbhash, tblock, target + (gint32)read32(ip));
2920                                 link_bblock (cfg, bblock, tblock);
2921                                 ins->inst_many_bb [i] = tblock;
2922                                 ip += 4;
2923                         }
2924                         /* FIXME: handle stack args */
2925                         inline_costs += 20;
2926                         break;
2927                 case CEE_LDIND_I1:
2928                 case CEE_LDIND_U1:
2929                 case CEE_LDIND_I2:
2930                 case CEE_LDIND_U2:
2931                 case CEE_LDIND_I4:
2932                 case CEE_LDIND_U4:
2933                 case CEE_LDIND_I8:
2934                 case CEE_LDIND_I:
2935                 case CEE_LDIND_R4:
2936                 case CEE_LDIND_R8:
2937                 case CEE_LDIND_REF:
2938                         CHECK_STACK (1);
2939                         MONO_INST_NEW (cfg, ins, *ip);
2940                         ins->cil_code = ip;
2941                         --sp;
2942                         ins->inst_i0 = *sp;
2943                         *sp++ = ins;
2944                         ins->type = ldind_type [*ip - CEE_LDIND_I1];
2945                         ins->flags |= ins_flag;
2946                         ins_flag = 0;
2947                         ++ip;
2948                         break;
2949                 case CEE_STIND_REF:
2950                 case CEE_STIND_I1:
2951                 case CEE_STIND_I2:
2952                 case CEE_STIND_I4:
2953                 case CEE_STIND_I8:
2954                 case CEE_STIND_R4:
2955                 case CEE_STIND_R8:
2956                         CHECK_STACK (2);
2957                         MONO_INST_NEW (cfg, ins, *ip);
2958                         ins->cil_code = ip++;
2959                         sp -= 2;
2960                         handle_loaded_temps (cfg, bblock, stack_start, sp);
2961                         MONO_ADD_INS (bblock, ins);
2962                         ins->inst_i0 = sp [0];
2963                         ins->inst_i1 = sp [1];
2964                         ins->flags |= ins_flag;
2965                         ins_flag = 0;
2966                         inline_costs += 1;
2967                         break;
2968                 case CEE_ADD:
2969                 case CEE_SUB:
2970                 case CEE_MUL:
2971                 case CEE_DIV:
2972                 case CEE_DIV_UN:
2973                 case CEE_REM:
2974                 case CEE_REM_UN:
2975                 case CEE_AND:
2976                 case CEE_OR:
2977                 case CEE_XOR:
2978                 case CEE_SHL:
2979                 case CEE_SHR:
2980                 case CEE_SHR_UN:
2981                         CHECK_STACK (2);
2982                         ADD_BINOP (*ip);
2983                         ip++;
2984                         break;
2985                 case CEE_NEG:
2986                 case CEE_NOT:
2987                 case CEE_CONV_I1:
2988                 case CEE_CONV_I2:
2989                 case CEE_CONV_I4:
2990                 case CEE_CONV_I8:
2991                 case CEE_CONV_R4:
2992                 case CEE_CONV_R8:
2993                 case CEE_CONV_U4:
2994                 case CEE_CONV_U8:
2995                 case CEE_CONV_OVF_I8:
2996                 case CEE_CONV_OVF_U8:
2997                 case CEE_CONV_R_UN:
2998                         CHECK_STACK (1);
2999                         ADD_UNOP (*ip);
3000                         ip++;
3001                         break;
3002                 case CEE_CONV_OVF_I4:
3003                 case CEE_CONV_OVF_I1:
3004                 case CEE_CONV_OVF_I2:
3005                 case CEE_CONV_OVF_I:
3006                 case CEE_CONV_OVF_U:
3007                         CHECK_STACK (1);
3008
3009                         if (sp [-1]->type == STACK_R8) {
3010                                 ADD_UNOP (CEE_CONV_OVF_I8);
3011                                 ADD_UNOP (*ip);
3012                         } else {
3013                                 ADD_UNOP (*ip);
3014                         }
3015
3016                         ip++;
3017                         break;
3018                 case CEE_CONV_OVF_U1:
3019                 case CEE_CONV_OVF_U2:
3020                 case CEE_CONV_OVF_U4:
3021                         CHECK_STACK (1);
3022
3023                         if (sp [-1]->type == STACK_R8) {
3024                                 ADD_UNOP (CEE_CONV_OVF_U8);
3025                                 ADD_UNOP (*ip);
3026                         } else {
3027                                 ADD_UNOP (*ip);
3028                         }
3029
3030                         ip++;
3031                         break;
3032                 case CEE_CONV_OVF_I1_UN:
3033                 case CEE_CONV_OVF_I2_UN:
3034                 case CEE_CONV_OVF_I4_UN:
3035                 case CEE_CONV_OVF_I8_UN:
3036                 case CEE_CONV_OVF_U1_UN:
3037                 case CEE_CONV_OVF_U2_UN:
3038                 case CEE_CONV_OVF_U4_UN:
3039                 case CEE_CONV_OVF_U8_UN:
3040                 case CEE_CONV_OVF_I_UN:
3041                 case CEE_CONV_OVF_U_UN:
3042                         CHECK_STACK (1);
3043                         ADD_UNOP (*ip);
3044                         ip++;
3045                         break;
3046                 case CEE_CPOBJ:
3047                         g_error ("opcode 0x%02x not handled", *ip);
3048                         break;
3049                 case CEE_LDOBJ: {
3050                         MonoInst *iargs [3];
3051                         CHECK_STACK (1);
3052                         --sp;
3053                         token = read32 (ip + 1);
3054                         if (method->wrapper_type != MONO_WRAPPER_NONE)
3055                                 klass = mono_method_get_wrapper_data (method, token);
3056                         else
3057                                 klass = mono_class_get (image, token);
3058
3059                         mono_class_init (klass);
3060                         n = mono_class_value_size (klass, NULL);
3061                         ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
3062                         NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
3063                         iargs [1] = *sp;
3064                         NEW_ICONST (cfg, iargs [2], n);
3065                         iargs [2]->cil_code = ip;
3066
3067                         mono_emit_jit_icall (cfg, bblock, helper_memcpy, iargs, ip);
3068                         NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
3069                         ++sp;
3070                         ip += 5;
3071                         inline_costs += 1;
3072                         break;
3073                 }
3074                 case CEE_LDSTR:
3075                         CHECK_STACK_OVF (1);
3076                         n = read32 (ip + 1);
3077
3078                         if (mono_compile_aot) {
3079                                 cfg->ldstr_list = g_list_prepend (cfg->ldstr_list, (gpointer)n);
3080                         }
3081
3082                         if ((cfg->opt & MONO_OPT_SAHRED) || mono_compile_aot) {
3083                                 int temp;
3084                                 MonoInst *iargs [3];
3085                                 NEW_TEMPLOAD (cfg, iargs [0], mono_get_domainvar (cfg)->inst_c0);
3086                                 NEW_IMAGECONST (cfg, iargs [1], image);
3087                                 NEW_ICONST (cfg, iargs [2], mono_metadata_token_index (n));
3088                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldstr, iargs, ip);
3089                                 NEW_TEMPLOAD (cfg, *sp, temp);
3090                                 mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
3091                         } else {
3092                                 NEW_PCONST (cfg, ins, NULL);
3093                                 ins->cil_code = ip;
3094                                 ins->type = STACK_OBJ;
3095                                 ins->inst_p0 = mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
3096                                 *sp = ins;
3097                         }
3098                         sp++;
3099                         ip += 5;
3100                         break;
3101                 case CEE_NEWOBJ: {
3102                         MonoInst *iargs [2];
3103                         int temp;
3104
3105                         token = read32 (ip + 1);
3106                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
3107                                 cmethod = mono_method_get_wrapper_data (method, token);
3108                         } else
3109                                 cmethod = mono_get_method (image, token, NULL);
3110
3111                         mono_class_init (cmethod->klass);
3112
3113                         n = cmethod->signature->param_count;
3114                         CHECK_STACK (n);
3115
3116                         /* move the args to allow room for 'this' in the first position */
3117                         while (n--) {
3118                                 --sp;
3119                                 sp [1] = sp [0];
3120                         }
3121
3122                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3123                         
3124
3125                         if (cmethod->klass->parent == mono_defaults.array_class) {
3126                                 NEW_METHODCONST (cfg, *sp, cmethod);
3127                                 temp = mono_emit_native_call (cfg, bblock, mono_array_new_va, cmethod->signature, sp, ip, FALSE);
3128
3129                         } else if (cmethod->string_ctor) {
3130                                 /* we simply pass a null pointer */
3131                                 NEW_PCONST (cfg, *sp, NULL); 
3132                                 /* now call the string ctor */
3133                                 temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, sp, ip, NULL);
3134                         } else {
3135                                 if (cmethod->klass->valuetype) {
3136                                         iargs [0] = mono_compile_create_var (cfg, &cmethod->klass->byval_arg, OP_LOCAL);
3137                                         temp = iargs [0]->inst_c0;
3138                                         NEW_TEMPLOADA (cfg, *sp, temp);
3139                                 } else {
3140                                         NEW_DOMAINCONST (cfg, iargs [0]);
3141                                         NEW_CLASSCONST (cfg, iargs [1], cmethod->klass);
3142
3143                                         temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
3144                                         NEW_TEMPLOAD (cfg, *sp, temp);
3145                                 }
3146
3147                                 /* now call the actual ctor */
3148                                 mono_emit_method_call_spilled (cfg, bblock, cmethod, sp, ip, NULL);
3149                         }
3150
3151                         NEW_TEMPLOAD (cfg, *sp, temp);
3152                         sp++;
3153                         
3154                         ip += 5;
3155                         inline_costs += 5;
3156                         break;
3157                 }
3158                 case CEE_ISINST:
3159                         CHECK_STACK (1);
3160                         MONO_INST_NEW (cfg, ins, *ip);
3161                         --sp;
3162                         klass = mono_class_get (image, read32 (ip + 1));
3163                         mono_class_init (klass);
3164                         ins->type = STACK_OBJ;
3165                         ins->inst_left = *sp;
3166                         ins->inst_newa_class = klass;
3167                         ins->cil_code = ip;
3168                         ip += 5;
3169                         *sp++ = ins;
3170                         break;
3171                 case CEE_UNBOX: {
3172                         MonoInst *add, *vtoffset;
3173                         /* FIXME: need to check class: move to inssel.brg? */
3174                         CHECK_STACK (1);
3175                         --sp;
3176                         token = read32 (ip + 1);
3177                         if (method->wrapper_type != MONO_WRAPPER_NONE)
3178                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
3179                         else 
3180                                 klass = mono_class_get (image, token);
3181                         mono_class_init (klass);
3182                         MONO_INST_NEW (cfg, add, CEE_ADD);
3183                         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
3184                         add->inst_left = *sp;
3185                         add->inst_right = vtoffset;
3186                         add->type = STACK_MP;
3187                         *sp++ = add;
3188                         ip += 5;
3189                         inline_costs += 1;
3190                         break;
3191                 }
3192                 case CEE_CASTCLASS:
3193                         CHECK_STACK (1);
3194                         MONO_INST_NEW (cfg, ins, *ip);
3195                         --sp;
3196                         klass = mono_class_get (image, read32 (ip + 1));
3197                         mono_class_init (klass);
3198                         ins->type = STACK_OBJ;
3199                         ins->inst_left = *sp;
3200                         ins->klass = klass;
3201                         ins->inst_newa_class = klass;
3202                         ins->cil_code = ip;
3203                         ip += 5;
3204                         *sp++ = ins;
3205                         break;
3206                 case CEE_THROW:
3207                         CHECK_STACK (1);
3208                         MONO_INST_NEW (cfg, ins, *ip);
3209                         --sp;
3210                         ins->inst_left = *sp;
3211                         ins->cil_code = ip++;
3212                         MONO_ADD_INS (bblock, ins);
3213                         sp = stack_start;
3214                         start_new_bblock = 1;
3215                         break;
3216                 case CEE_LDFLD:
3217                 case CEE_LDFLDA:
3218                 case CEE_STFLD: {
3219                         MonoInst *offset_ins;
3220                         MonoClassField *field;
3221                         guint foffset;
3222
3223                         if (*ip == CEE_STFLD) {
3224                                 CHECK_STACK (2);
3225                                 sp -= 2;
3226                         } else {
3227                                 CHECK_STACK (1);
3228                                 --sp;
3229                         }
3230                         // FIXME: enable this test later.
3231                         //if (sp [0]->type != STACK_OBJ && sp [0]->type != STACK_MP)
3232                         //      goto unverified;
3233                         token = read32 (ip + 1);
3234                         field = mono_field_from_token (image, token, &klass);
3235                         mono_class_init (klass);
3236                         foffset = klass->valuetype? field->offset - sizeof (MonoObject): field->offset;
3237                         /* FIXME: mark instructions for use in SSA */
3238                         if (*ip == CEE_STFLD) {
3239                                 if (klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) {
3240                                         /* fixme: we need to inline that call somehow */
3241                                         MonoMethod *stfld_wrapper = mono_marshal_get_stfld_wrapper (field->type); 
3242                                         MonoInst *iargs [5];
3243                                         iargs [0] = sp [0];
3244                                         NEW_CLASSCONST (cfg, iargs [1], klass);
3245                                         NEW_FIELDCONST (cfg, iargs [2], field);
3246                                         NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
3247                                         iargs [4] = sp [1];
3248                                         mono_emit_method_call_spilled (cfg, bblock, stfld_wrapper, iargs, ip, NULL);
3249                                 } else {
3250                                         MonoInst *store;
3251                                         NEW_ICONST (cfg, offset_ins, foffset);
3252                                         MONO_INST_NEW (cfg, ins, CEE_ADD);
3253                                         ins->cil_code = ip;
3254                                         ins->inst_left = *sp;
3255                                         ins->inst_right = offset_ins;
3256                                         ins->type = STACK_MP;
3257
3258                                         MONO_INST_NEW (cfg, store, mono_type_to_stind (field->type));
3259                                         store->cil_code = ip;
3260                                         store->inst_left = ins;
3261                                         store->inst_right = sp [1];
3262                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3263                                         store->flags |= ins_flag;
3264                                         ins_flag = 0;
3265                                         if (store->opcode == CEE_STOBJ) {
3266                                                 handle_stobj (cfg, bblock, ins, sp [1], ip, 
3267                                                               mono_class_from_mono_type (field->type), FALSE, FALSE);
3268                                         } else
3269                                                 MONO_ADD_INS (bblock, store);
3270                                 }
3271                         } else {
3272                                 if (klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) {
3273                                         /* fixme: we need to inline that call somehow */
3274                                         MonoMethod *ldfld_wrapper = mono_marshal_get_ldfld_wrapper (field->type); 
3275                                         MonoInst *iargs [4];
3276                                         int temp;
3277                                         iargs [0] = sp [0];
3278                                         NEW_CLASSCONST (cfg, iargs [1], klass);
3279                                         NEW_FIELDCONST (cfg, iargs [2], field);
3280                                         NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
3281                                         temp = mono_emit_method_call_spilled (cfg, bblock, ldfld_wrapper, iargs, ip, NULL);
3282                                         if (*ip == CEE_LDFLDA) {
3283                                                 /* not sure howto handle this */
3284                                                 NEW_TEMPLOADA (cfg, *sp, temp);
3285                                         } else {
3286                                                 NEW_TEMPLOAD (cfg, *sp, temp);
3287                                         }
3288                                         sp++;
3289                                 } else {
3290                                         NEW_ICONST (cfg, offset_ins, foffset);
3291                                         MONO_INST_NEW (cfg, ins, CEE_ADD);
3292                                         ins->cil_code = ip;
3293                                         ins->inst_left = *sp;
3294                                         ins->inst_right = offset_ins;
3295                                         ins->type = STACK_MP;
3296
3297                                         if (*ip == CEE_LDFLDA) {
3298                                                 *sp++ = ins;
3299                                         } else {
3300                                                 MonoInst *load;
3301                                                 MONO_INST_NEW (cfg, load, mono_type_to_ldind (field->type));
3302                                                 type_to_eval_stack_type (field->type, load);
3303                                                 load->cil_code = ip;
3304                                                 load->inst_left = ins;
3305                                                 load->flags |= ins_flag;
3306                                                 ins_flag = 0;
3307                                                 *sp++ = load;
3308                                         }
3309                                 }
3310                         }
3311                         ip += 5;
3312                         break;
3313                 }
3314                 case CEE_LDSFLD:
3315                 case CEE_LDSFLDA:
3316                 case CEE_STSFLD: {
3317                         MonoClassField *field;
3318                         MonoVTable *vtable;
3319
3320                         token = read32 (ip + 1);
3321
3322                         field = mono_field_from_token (image, token, &klass);
3323                         mono_class_init (klass);
3324
3325                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3326                                 
3327                         if (((cfg->opt & MONO_OPT_SAHRED) || mono_compile_aot)) {
3328                                 int temp;
3329                                 MonoInst *iargs [2];
3330                                 g_assert (field->parent);
3331                                 NEW_TEMPLOAD (cfg, iargs [0], mono_get_domainvar (cfg)->inst_c0);
3332                                 NEW_FIELDCONST (cfg, iargs [1], field);
3333                                 temp = mono_emit_jit_icall (cfg, bblock, mono_class_static_field_address, iargs, ip);
3334                                 NEW_TEMPLOAD (cfg, ins, temp);
3335                         } else {
3336                                 vtable = mono_class_vtable (cfg->domain, klass);
3337                                 NEW_PCONST (cfg, ins, (char*)vtable->data + field->offset);
3338                                 ins->cil_code = ip;
3339                         }
3340
3341                         /* FIXME: mark instructions for use in SSA */
3342                         if (*ip == CEE_LDSFLDA) {
3343                                 *sp++ = ins;
3344                         } else if (*ip == CEE_STSFLD) {
3345                                 MonoInst *store;
3346                                 CHECK_STACK (1);
3347                                 sp--;
3348                                 MONO_INST_NEW (cfg, store, mono_type_to_stind (field->type));
3349                                 store->cil_code = ip;
3350                                 store->inst_left = ins;
3351                                 store->inst_right = sp [0];
3352                                 store->flags |= ins_flag;
3353                                 ins_flag = 0;
3354
3355                                 if (store->opcode == CEE_STOBJ) {
3356                                         handle_stobj (cfg, bblock, ins, sp [0], ip, mono_class_from_mono_type (field->type), FALSE, FALSE);
3357                                 } else
3358                                         MONO_ADD_INS (bblock, store);
3359                         } else {
3360                                 MonoInst *load;
3361                                 CHECK_STACK_OVF (1);
3362                                 MONO_INST_NEW (cfg, load, mono_type_to_ldind (field->type));
3363                                 type_to_eval_stack_type (field->type, load);
3364                                 load->cil_code = ip;
3365                                 load->inst_left = ins;
3366                                 *sp++ = load;
3367                                 load->flags |= ins_flag;
3368                                 ins_flag = 0;
3369                         /* fixme: dont see the problem why this does not work */
3370                                 //cfg->disable_aot = TRUE;
3371                         }
3372                         ip += 5;
3373                         break;
3374                 }
3375                 case CEE_STOBJ:
3376                         CHECK_STACK (2);
3377                         sp -= 2;
3378                         token = read32 (ip + 1);
3379                         if (method->wrapper_type != MONO_WRAPPER_NONE)
3380                                 klass = mono_method_get_wrapper_data (method, token);
3381                         else
3382                                 klass = mono_class_get (image, token);
3383                         mono_class_init (klass);
3384                         handle_stobj (cfg, bblock, sp [0], sp [1], ip, klass, FALSE, FALSE);
3385                         ip += 5;
3386                         inline_costs += 1;
3387                         break;
3388                 case CEE_BOX: {
3389                         MonoInst *iargs [2];
3390                         MonoInst *load, *vtoffset, *add, *val, *vstore;
3391                         int temp;
3392                         CHECK_STACK (1);
3393                         --sp;
3394                         val = *sp;
3395                         token = read32 (ip + 1);
3396                         if (method->wrapper_type != MONO_WRAPPER_NONE)
3397                                 klass = mono_method_get_wrapper_data (method, token);
3398                         else
3399                                 klass = mono_class_get (image, token);
3400                         mono_class_init (klass);
3401
3402                         /* much like NEWOBJ */
3403                         NEW_DOMAINCONST (cfg, iargs [0]);
3404                         NEW_CLASSCONST (cfg, iargs [1], klass);
3405                         
3406                         temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
3407                         NEW_TEMPLOAD (cfg, load, temp);
3408                         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
3409                         MONO_INST_NEW (cfg, add, CEE_ADD);
3410                         add->inst_left = load;
3411                         add->inst_right = vtoffset;
3412                         add->cil_code = ip;
3413                         add->klass = klass;
3414                         MONO_INST_NEW (cfg, vstore, CEE_STIND_I);
3415                         vstore->opcode = mono_type_to_stind (&klass->byval_arg);
3416                         vstore->cil_code = ip;
3417                         vstore->inst_left = add;
3418                         vstore->inst_right = val;
3419
3420                         if (vstore->opcode == CEE_STOBJ) {
3421                                 handle_stobj (cfg, bblock, add, val, ip, klass, FALSE, FALSE);
3422                         } else
3423                                 MONO_ADD_INS (bblock, vstore);
3424
3425                         NEW_TEMPLOAD (cfg, load, temp);
3426                         *sp++ = load;
3427                         ip += 5;
3428                         inline_costs += 1;
3429                         break;
3430                 }
3431                 case CEE_NEWARR:
3432                         CHECK_STACK (1);
3433                         MONO_INST_NEW (cfg, ins, *ip);
3434                         ins->cil_code = ip;
3435                         --sp;
3436
3437                         token = read32 (ip + 1);
3438
3439                         /* allocate the domainvar - becaus this is used in decompose_foreach */
3440                         if ((cfg->opt & MONO_OPT_SAHRED) || mono_compile_aot)
3441                                 mono_get_domainvar (cfg);
3442                         
3443                         if (method->wrapper_type != MONO_WRAPPER_NONE)
3444                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
3445                         else
3446                                 klass = mono_class_get (image, token);
3447
3448                         mono_class_init (klass);
3449                         ins->inst_newa_class = klass;
3450                         ins->inst_newa_len = *sp;
3451                         ins->type = STACK_OBJ;
3452                         ip += 5;
3453                         *sp++ = ins;
3454                         inline_costs += 1;
3455                         break;
3456                 case CEE_LDLEN:
3457                         CHECK_STACK (1);
3458                         MONO_INST_NEW (cfg, ins, *ip);
3459                         ins->cil_code = ip++;
3460                         --sp;
3461                         ins->inst_left = *sp;
3462                         ins->type = STACK_PTR;
3463                         *sp++ = ins;
3464                         break;
3465                 case CEE_LDELEMA:
3466                         CHECK_STACK (2);
3467                         sp -= 2;
3468                         klass = mono_class_get (image, read32 (ip + 1));
3469                         mono_class_init (klass);
3470                         NEW_LDELEMA (cfg, ins, sp, klass);
3471                         ins->cil_code = ip;
3472                         *sp++ = ins;
3473                         ip += 5;
3474                         break;
3475                 case CEE_LDELEM_I1:
3476                 case CEE_LDELEM_U1:
3477                 case CEE_LDELEM_I2:
3478                 case CEE_LDELEM_U2:
3479                 case CEE_LDELEM_I4:
3480                 case CEE_LDELEM_U4:
3481                 case CEE_LDELEM_I8:
3482                 case CEE_LDELEM_I:
3483                 case CEE_LDELEM_R4:
3484                 case CEE_LDELEM_R8:
3485                 case CEE_LDELEM_REF: {
3486                         MonoInst *load;
3487                         /*
3488                          * translate to:
3489                          * ldind.x (ldelema (array, index))
3490                          * ldelema does the bounds check
3491                          */
3492                         CHECK_STACK (2);
3493                         sp -= 2;
3494                         klass = array_access_to_klass (*ip);
3495                         NEW_LDELEMA (cfg, load, sp, klass);
3496                         load->cil_code = ip;
3497                         MONO_INST_NEW (cfg, ins, ldelem_to_ldind [*ip - CEE_LDELEM_I1]);
3498                         ins->cil_code = ip;
3499                         ins->inst_left = load;
3500                         *sp++ = ins;
3501                         ins->type = ldind_type [ins->opcode - CEE_LDIND_I1];
3502                         ++ip;
3503                         break;
3504                 }
3505                 case CEE_STELEM_I:
3506                 case CEE_STELEM_I1:
3507                 case CEE_STELEM_I2:
3508                 case CEE_STELEM_I4:
3509                 case CEE_STELEM_I8:
3510                 case CEE_STELEM_R4:
3511                 case CEE_STELEM_R8: {
3512                         MonoInst *load;
3513                         /*
3514                          * translate to:
3515                          * stind.x (ldelema (array, index), val)
3516                          * ldelema does the bounds check
3517                          */
3518                         CHECK_STACK (3);
3519                         sp -= 3;
3520                         klass = array_access_to_klass (*ip);
3521                         NEW_LDELEMA (cfg, load, sp, klass);
3522                         load->cil_code = ip;
3523                         MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
3524                         ins->cil_code = ip;
3525                         ins->inst_left = load;
3526                         ins->inst_right = sp [2];
3527                         ++ip;
3528                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3529                         MONO_ADD_INS (bblock, ins);
3530                         /* FIXME: add the implicit STELEM_REF castclass */
3531                         inline_costs += 1;
3532                         cfg->disable_ssa = TRUE;
3533                         break;
3534                 }
3535                 case CEE_STELEM_REF: {
3536                         MonoInst *iargs [3];
3537
3538                         CHECK_STACK (3);
3539                         sp -= 3;
3540
3541                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3542
3543                         iargs [2] = sp [2];
3544                         iargs [1] = sp [1];
3545                         iargs [0] = sp [0];
3546                         
3547                         mono_emit_jit_icall (cfg, bblock, helper_stelem_ref, iargs, ip);
3548
3549                         /*
3550                         MonoInst *group;
3551                         NEW_GROUP (cfg, group, sp [0], sp [1]);
3552                         MONO_INST_NEW (cfg, ins, CEE_STELEM_REF);
3553                         ins->cil_code = ip;
3554                         ins->inst_left = group;
3555                         ins->inst_right = sp [2];
3556                         MONO_ADD_INS (bblock, ins);
3557                         */
3558
3559                         ++ip;
3560                         inline_costs += 1;
3561                         cfg->disable_ssa = TRUE;
3562                         break;
3563                 }
3564                 case CEE_CKFINITE: {
3565                         MonoInst *store, *temp;
3566                         CHECK_STACK (1);
3567
3568                         /* this instr. can throw exceptions as side effect,
3569                          * so we cant eliminate dead code which contains CKFINITE opdodes.
3570                          * Spilling to memory makes sure that we always perform
3571                          * this check */
3572
3573                         
3574                         MONO_INST_NEW (cfg, ins, CEE_CKFINITE);
3575                         ins->cil_code = ip;
3576                         ins->inst_left = sp [-1];
3577                         temp = mono_compile_create_var (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL);
3578
3579                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
3580                         store->cil_code = ip;
3581                         MONO_ADD_INS (bblock, store);
3582
3583                         NEW_TEMPLOAD (cfg, sp [-1], temp->inst_c0);
3584                        
3585                         ++ip;
3586                         break;
3587                 }
3588                 case CEE_REFANYVAL:
3589                 case CEE_MKREFANY:
3590                         g_error ("opcode 0x%02x not handled", *ip);
3591                         break;
3592                 case CEE_LDTOKEN: {
3593                         gpointer handle;
3594                         MonoClass *handle_class;
3595
3596                         CHECK_STACK_OVF (1);
3597
3598                         n = read32 (ip + 1);
3599
3600                         handle = mono_ldtoken (image, n, &handle_class);
3601                         mono_class_init (handle_class);
3602
3603                         if (((cfg->opt & MONO_OPT_SAHRED) || mono_compile_aot)) {
3604                                 int temp;
3605                                 MonoInst *res, *store, *addr, *vtvar, *iargs [2];
3606
3607                                 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL); 
3608
3609                                 NEW_IMAGECONST (cfg, iargs [0], image);
3610                                 NEW_ICONST (cfg, iargs [1], n);
3611                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldtoken_wrapper, iargs, ip);
3612                                 NEW_TEMPLOAD (cfg, res, temp);
3613                                 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
3614                                 NEW_INDSTORE (cfg, store, addr, res, &mono_defaults.int_class->byval_arg);
3615                                 MONO_ADD_INS (bblock, store);
3616                                 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
3617                         } else {
3618                                 if ((ip [5] == CEE_CALL) && (cmethod = mono_get_method (image, read32 (ip + 6), NULL)) &&
3619                                                 (cmethod->klass == mono_defaults.monotype_class->parent) &&
3620                                                 (strcmp (cmethod->name, "GetTypeFromHandle") == 0)) {
3621                                         MonoClass *tclass = mono_class_from_mono_type (handle);
3622                                         mono_class_init (tclass);
3623                                         NEW_PCONST (cfg, ins, mono_type_get_object (cfg->domain, handle));
3624                                         ins->type = STACK_OBJ;
3625                                         ins->klass = cmethod->klass;
3626                                         ip += 5;
3627                                 } else {
3628                                         NEW_PCONST (cfg, ins, handle);
3629                                         ins->type = STACK_VTYPE;
3630                                         ins->klass = handle_class;
3631                                 }
3632                         }
3633
3634                         *sp++ = ins;
3635                         ip += 5;
3636                         break;
3637                 }
3638                 case CEE_CONV_U2:
3639                 case CEE_CONV_U1:
3640                 case CEE_CONV_I:
3641                         CHECK_STACK (1);
3642                         ADD_UNOP (*ip);
3643                         ip++;
3644                         break;
3645                 case CEE_ADD_OVF:
3646                 case CEE_ADD_OVF_UN:
3647                 case CEE_MUL_OVF:
3648                 case CEE_MUL_OVF_UN:
3649                 case CEE_SUB_OVF:
3650                 case CEE_SUB_OVF_UN:
3651                         CHECK_STACK (2);
3652                         ADD_BINOP (*ip);
3653                         ip++;
3654                         break;
3655                 case CEE_ENDFINALLY:
3656                         /* FIXME: check stack state */
3657                         MONO_INST_NEW (cfg, ins, *ip);
3658                         MONO_ADD_INS (bblock, ins);
3659                         ins->cil_code = ip++;
3660                         start_new_bblock = 1;
3661                         break;
3662                 case CEE_LEAVE:
3663                 case CEE_LEAVE_S:
3664                         if (*ip == CEE_LEAVE) {
3665                                 target = ip + 5 + (gint32)read32(ip + 1);
3666                         } else {
3667                                 target = ip + 2 + (signed char)(ip [1]);
3668                         }
3669
3670                         /* empty the stack */
3671                         while (sp != stack_start) {
3672                                 MONO_INST_NEW (cfg, ins, CEE_POP);
3673                                 ins->cil_code = ip;
3674                                 sp--;
3675                                 ins->inst_i0 = *sp;
3676                                 MONO_ADD_INS (bblock, ins);
3677                         }
3678
3679                         /* fixme: call fault handler ? */
3680
3681                         if ((tblock = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
3682                                 link_bblock (cfg, bblock, tblock);
3683                                 MONO_INST_NEW (cfg, ins, OP_HANDLER);
3684                                 ins->cil_code = ip;
3685                                 ins->inst_target_bb = tblock;
3686                                 MONO_ADD_INS (bblock, ins);
3687                         } 
3688
3689
3690                         MONO_INST_NEW (cfg, ins, CEE_BR);
3691                         ins->cil_code = ip;
3692                         MONO_ADD_INS (bblock, ins);
3693                         GET_BBLOCK (cfg, bbhash, tblock, target);
3694                         link_bblock (cfg, bblock, tblock);
3695                         CHECK_BBLOCK (target, ip, tblock);
3696                         ins->inst_target_bb = tblock;
3697                         start_new_bblock = 1;
3698
3699                         if (*ip == CEE_LEAVE)
3700                                 ip += 5;
3701                         else
3702                                 ip += 2;
3703
3704
3705                         break;
3706                 case CEE_STIND_I:
3707                         CHECK_STACK (2);
3708                         MONO_INST_NEW (cfg, ins, *ip);
3709                         sp -= 2;
3710                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3711                         MONO_ADD_INS (bblock, ins);
3712                         ins->cil_code = ip++;
3713                         ins->inst_i0 = sp [0];
3714                         ins->inst_i1 = sp [1];
3715                         inline_costs += 1;
3716                         break;
3717                 case CEE_CONV_U:
3718                         CHECK_STACK (1);
3719                         ADD_UNOP (*ip);
3720                         ip++;
3721                         break;
3722                 /* trampoline mono specific opcodes */
3723                 case MONO_CUSTOM_PREFIX: {
3724
3725                         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
3726
3727                         switch (ip [1]) {
3728
3729                         case CEE_MONO_FUNC1: {
3730                                 int temp;
3731                                 gpointer func = NULL;
3732                                 CHECK_STACK (1);
3733                                 sp--;
3734
3735                                 switch (ip [2]) {
3736                                 case MONO_MARSHAL_CONV_STR_LPWSTR:
3737                                         func = mono_string_to_utf16;
3738                                         break;
3739                                 case MONO_MARSHAL_CONV_LPWSTR_STR:
3740                                         func = mono_string_from_utf16;
3741                                         break;
3742                                 case MONO_MARSHAL_CONV_LPSTR_STR:
3743                                         func = mono_string_new_wrapper;
3744                                         break;
3745                                 case MONO_MARSHAL_CONV_STR_LPTSTR:
3746                                 case MONO_MARSHAL_CONV_STR_LPSTR:
3747                                         func = mono_string_to_utf8;
3748                                         break;
3749                                 case MONO_MARSHAL_CONV_STR_BSTR:
3750                                         func = mono_string_to_bstr;
3751                                         break;
3752                                 case MONO_MARSHAL_CONV_STR_TBSTR:
3753                                 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
3754                                         func = mono_string_to_ansibstr;
3755                                         break;
3756                                 case MONO_MARSHAL_CONV_SB_LPSTR:
3757                                         func = mono_string_builder_to_utf8;
3758                                         break;
3759                                 case MONO_MARSHAL_CONV_ARRAY_SAVEARRAY:
3760                                         func = mono_array_to_savearray;
3761                                         break;
3762                                 case MONO_MARSHAL_CONV_ARRAY_LPARRAY:
3763                                         func = mono_array_to_lparray;
3764                                         break;
3765                                 case MONO_MARSHAL_CONV_DEL_FTN:
3766                                         func = mono_delegate_to_ftnptr;
3767                                         break;
3768                                 case MONO_MARSHAL_CONV_STRARRAY_STRLPARRAY:
3769                                         func = mono_marshal_string_array;
3770                                         break;
3771                                 default:
3772                                         g_warning ("unknown conversion %d\n", ip [2]);
3773                                         g_assert_not_reached ();
3774                                 }
3775
3776                                 temp = mono_emit_jit_icall (cfg, bblock, func, sp, ip);
3777                                 NEW_TEMPLOAD (cfg, *sp, temp);
3778                                 sp++;
3779
3780                                 ip += 3;
3781                                 inline_costs += 10 * num_calls++;
3782                                 break;
3783                         }
3784                         case CEE_MONO_PROC2: {
3785                                 gpointer func = NULL;
3786                                 CHECK_STACK (2);
3787                                 sp -= 2;
3788
3789                                 switch (ip [2]) {
3790                                 case MONO_MARSHAL_CONV_LPSTR_SB:
3791                                         func = mono_string_utf8_to_builder;
3792                                         break;
3793                                 case MONO_MARSHAL_FREE_ARRAY:
3794                                         func = mono_marshal_free_array;
3795                                         break;
3796                                 default:
3797                                         g_assert_not_reached ();
3798                                 }
3799
3800                                 mono_emit_jit_icall (cfg, bblock, func, sp, ip);
3801                                 ip += 3;
3802                                 inline_costs += 10 * num_calls++;
3803                                 break;
3804                         }
3805                         case CEE_MONO_PROC3: {
3806                                 gpointer func = NULL;
3807                                 CHECK_STACK (3);
3808                                 sp -= 3;
3809
3810                                 switch (ip [2]) {
3811                                 case MONO_MARSHAL_CONV_STR_BYVALSTR:
3812                                         func = mono_string_to_byvalstr;
3813                                         break;
3814                                 case MONO_MARSHAL_CONV_STR_BYVALWSTR:
3815                                         func = mono_string_to_byvalwstr;
3816                                         break;
3817                                 default:
3818                                         g_assert_not_reached ();
3819                                 }
3820
3821                                 mono_emit_jit_icall (cfg, bblock, func, sp, ip);
3822                                 ip += 3;
3823                                 inline_costs += 10 * num_calls++;
3824                                 break;
3825                         }
3826                         case CEE_MONO_FREE:
3827                                 CHECK_STACK (1);
3828                                 sp -= 1;
3829                                 mono_emit_jit_icall (cfg, bblock, g_free, sp, ip);
3830                                 ip += 2;
3831                                 inline_costs += 10 * num_calls++;
3832                                 break;
3833                         case CEE_MONO_LDPTR:
3834                                 CHECK_STACK_OVF (1);
3835                                 token = read32 (ip + 2);
3836                                 NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
3837                                 ins->cil_code = ip;
3838                                 *sp++ = ins;
3839                                 ip += 6;
3840                                 inline_costs += 10 * num_calls++;
3841                                 break;
3842                         case CEE_MONO_VTADDR:
3843                                 CHECK_STACK (1);
3844                                 --sp;
3845                                 MONO_INST_NEW (cfg, ins, OP_VTADDR);
3846                                 ins->cil_code = ip;
3847                                 ins->type = STACK_MP;
3848                                 ins->inst_left = *sp;
3849                                 *sp++ = ins;
3850                                 ip += 2;
3851                                 break;
3852                         case CEE_MONO_NEWOBJ: {
3853                                 MonoInst *iargs [2];
3854                                 int temp;
3855                                 CHECK_STACK_OVF (1);
3856                                 token = read32 (ip + 2);
3857                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
3858                                 mono_class_init (klass);
3859                                 NEW_DOMAINCONST (cfg, iargs [0]);
3860                                 NEW_CLASSCONST (cfg, iargs [1], klass);
3861                                 temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
3862                                 NEW_TEMPLOAD (cfg, *sp, temp);
3863                                 sp++;
3864                                 ip += 6;
3865                                 inline_costs += 10 * num_calls++;
3866                                 break;
3867                         }
3868                         case CEE_MONO_OBJADDR:
3869                                 CHECK_STACK (1);
3870                                 --sp;
3871                                 MONO_INST_NEW (cfg, ins, OP_OBJADDR);
3872                                 ins->cil_code = ip;
3873                                 ins->type = STACK_MP;
3874                                 ins->inst_left = *sp;
3875                                 *sp++ = ins;
3876                                 ip += 2;
3877                                 break;
3878                         case CEE_MONO_LDNATIVEOBJ:
3879                                 CHECK_STACK (1);
3880                                 token = read32 (ip + 2);
3881                                 klass = mono_method_get_wrapper_data (method, token);
3882                                 g_assert (klass->valuetype);
3883                                 mono_class_init (klass);
3884                                 NEW_INDLOAD (cfg, ins, sp [-1], &klass->byval_arg);
3885                                 sp [-1] = ins;
3886                                 ip += 6;
3887                                 break;
3888                         case CEE_MONO_RETOBJ:
3889                                 g_assert (cfg->ret);
3890                                 g_assert (method->signature->pinvoke); 
3891                                 CHECK_STACK (1);
3892                                 --sp;
3893                                 
3894                                 token = read32 (ip + 2);    
3895                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
3896
3897                                 NEW_RETLOADA (cfg, ins);
3898                                 handle_stobj (cfg, bblock, ins, *sp, ip, klass, FALSE, TRUE);
3899                                 
3900                                 if (sp != stack_start)
3901                                         goto unverified;
3902                                 
3903                                 MONO_INST_NEW (cfg, ins, CEE_BR);
3904                                 ins->cil_code = ip;
3905                                 ins->inst_target_bb = end_bblock;
3906                                 MONO_ADD_INS (bblock, ins);
3907                                 link_bblock (cfg, bblock, end_bblock);
3908                                 start_new_bblock = 1;
3909                                 ip += 6;
3910                                 break;
3911                         default:
3912                                 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
3913                                 break;
3914                         }
3915                         break;
3916                 }
3917                 case CEE_PREFIX1: {
3918                         switch (ip [1]) {
3919                         case CEE_ARGLIST:
3920                                 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
3921                                 break;
3922                         case CEE_CEQ:
3923                         case CEE_CGT:
3924                         case CEE_CGT_UN:
3925                         case CEE_CLT:
3926                         case CEE_CLT_UN: {
3927                                 MonoInst *cmp;
3928                                 CHECK_STACK (2);
3929                                 MONO_INST_NEW (cfg, cmp, 256 + ip [1]);
3930                                 MONO_INST_NEW (cfg, ins, cmp->opcode);
3931                                 sp -= 2;
3932                                 cmp->inst_i0 = sp [0];
3933                                 cmp->inst_i1 = sp [1];
3934                                 cmp->cil_code = ip;
3935                                 type_from_op (cmp);
3936                                 CHECK_TYPE (cmp);
3937                                 cmp->opcode = OP_COMPARE;
3938                                 ins->cil_code = ip;
3939                                 ins->type = STACK_I4;
3940                                 ins->inst_i0 = cmp;
3941                                 *sp++ = ins;
3942                                 ip += 2;
3943                                 break;
3944                         }
3945                         case CEE_LDFTN: {
3946                                 MonoInst *argconst;
3947                                 int temp;
3948
3949                                 CHECK_STACK_OVF (1);
3950                                 n = read32 (ip + 2);
3951                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
3952                                         cmethod = mono_method_get_wrapper_data (method, n);
3953                                 else {
3954                                         cmethod = mono_get_method (image, n, NULL);
3955
3956                                         /*
3957                                          * We can't do this in mono_ldftn, since it is used in
3958                                          * the synchronized wrapper, leading to an infinite loop.
3959                                          */
3960                                         if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
3961                                                 cmethod = mono_marshal_get_synchronized_wrapper (cmethod);
3962                                 }
3963
3964                                 mono_class_init (cmethod->klass);
3965                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
3966
3967                                 NEW_METHODCONST (cfg, argconst, cmethod);
3968                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn, &argconst, ip);
3969                                 NEW_TEMPLOAD (cfg, *sp, temp);
3970                                 sp ++;
3971                                 
3972                                 ip += 6;
3973                                 inline_costs += 10 * num_calls++;
3974                                 break;
3975                         }
3976                         case CEE_LDVIRTFTN: {
3977                                 MonoInst *args [2];
3978                                 int temp;
3979
3980                                 CHECK_STACK (1);
3981                                 n = read32 (ip + 2);
3982                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
3983                                         cmethod = mono_method_get_wrapper_data (method, n);
3984                                 else
3985                                         cmethod = mono_get_method (image, n, NULL);
3986
3987                                 mono_class_init (cmethod->klass);
3988                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
3989
3990                                 --sp;
3991                                 args [0] = *sp;
3992                                 NEW_METHODCONST (cfg, args [1], cmethod);
3993                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldvirtfn, args, ip);
3994                                 NEW_TEMPLOAD (cfg, *sp, temp);
3995                                 sp ++;
3996
3997                                 ip += 6;
3998                                 inline_costs += 10 * num_calls++;
3999                                 break;
4000                         }
4001                         case CEE_LDARG:
4002                                 CHECK_STACK_OVF (1);
4003                                 NEW_ARGLOAD (cfg, ins, read16 (ip + 2));
4004                                 ins->cil_code = ip;
4005                                 *sp++ = ins;
4006                                 ip += 4;
4007                                 break;
4008                         case CEE_LDARGA:
4009                                 CHECK_STACK_OVF (1);
4010                                 NEW_ARGLOADA (cfg, ins, read16 (ip + 2));
4011                                 ins->cil_code = ip;
4012                                 *sp++ = ins;
4013                                 ip += 4;
4014                                 break;
4015                         case CEE_STARG:
4016                                 CHECK_STACK (1);
4017                                 --sp;
4018                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4019                                 n = read16 (ip + 2);
4020                                 NEW_ARGSTORE (cfg, ins, n, *sp);
4021                                 ins->cil_code = ip;
4022                                 if (ins->opcode == CEE_STOBJ) {
4023                                         NEW_ARGLOADA (cfg, ins, n);
4024                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
4025                                 } else
4026                                         MONO_ADD_INS (bblock, ins);
4027                                 ip += 4;
4028                                 break;
4029                         case CEE_LDLOC:
4030                                 CHECK_STACK_OVF (1);
4031                                 NEW_LOCLOAD (cfg, ins, read16 (ip + 2));
4032                                 ins->cil_code = ip;
4033                                 *sp++ = ins;
4034                                 ip += 4;
4035                                 break;
4036                         case CEE_LDLOCA:
4037                                 CHECK_STACK_OVF (1);
4038                                 NEW_LOCLOADA (cfg, ins, read16 (ip + 2));
4039                                 ins->cil_code = ip;
4040                                 *sp++ = ins;
4041                                 ip += 4;
4042                                 break;
4043                         case CEE_STLOC:
4044                                 CHECK_STACK (1);
4045                                 --sp;
4046                                 n = read16 (ip + 2);
4047                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4048                                 NEW_LOCSTORE (cfg, ins, n, *sp);
4049                                 ins->cil_code = ip;
4050                                 if (ins->opcode == CEE_STOBJ) {
4051                                         NEW_LOCLOADA (cfg, ins, n);
4052                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
4053                                 } else
4054                                         MONO_ADD_INS (bblock, ins);
4055                                 ip += 4;
4056                                 inline_costs += 1;
4057                                 break;
4058                         case CEE_LOCALLOC:
4059                                 CHECK_STACK (1);
4060                                 --sp;
4061                                 if (sp != stack_start) 
4062                                         goto unverified;
4063                                 MONO_INST_NEW (cfg, ins, 256 + ip [1]);
4064                                 ins->inst_left = *sp;
4065                                 ins->cil_code = ip;
4066
4067                                 if (header->init_locals)
4068                                         ins->flags |= MONO_INST_INIT;
4069
4070                                 *sp++ = ins;
4071                                 ip += 2;
4072                                 /* FIXME: set init flag if locals init is set in this method */
4073                                 break;
4074                         case CEE_ENDFILTER: {
4075                                 MonoExceptionClause *clause, *nearest;
4076                                 int cc, nearest_num;
4077
4078                                 CHECK_STACK (1);
4079                                 --sp;
4080                                 if ((sp != stack_start) || (sp [0]->type != STACK_I4)) 
4081                                         goto unverified;
4082                                 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
4083                                 ins->inst_left = *sp;
4084                                 ins->cil_code = ip;
4085                                 MONO_ADD_INS (bblock, ins);
4086                                 start_new_bblock = 1;
4087                                 ip += 2;
4088
4089                                 nearest = NULL;
4090                                 for (cc = 0; cc < header->num_clauses; ++cc) {
4091                                         clause = &header->clauses [cc];
4092                                         if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
4093                                             (!nearest || (clause->token_or_filter > nearest->token_or_filter))) {
4094                                                 nearest = clause;
4095                                                 nearest_num = cc;
4096                                         }
4097                                 }
4098                                 g_assert (nearest);
4099                                 filter_lengths [nearest_num] = (ip - header->code) -  nearest->token_or_filter;
4100
4101                                 break;
4102                         }
4103                         case CEE_UNALIGNED_:
4104                                 ins_flag |= MONO_INST_UNALIGNED;
4105                                 ip += 3;
4106                                 break;
4107                         case CEE_VOLATILE_:
4108                                 ins_flag |= MONO_INST_VOLATILE;
4109                                 ip += 2;
4110                                 break;
4111                         case CEE_TAIL_:
4112                                 ins_flag |= MONO_INST_TAILCALL;
4113                                 ip += 2;
4114                                 break;
4115                         case CEE_INITOBJ:
4116                                 CHECK_STACK (1);
4117                                 --sp;
4118                                 token = read32 (ip + 2);
4119                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
4120                                         klass = mono_method_get_wrapper_data (method, token);
4121                                 else
4122                                         klass = mono_class_get (image, token);
4123                                 handle_initobj (cfg, bblock, *sp, NULL, klass, stack_start, sp);
4124                                 ip += 6;
4125                                 inline_costs += 1;
4126                                 break;
4127                         case CEE_CPBLK:
4128                         case CEE_INITBLK: {
4129                                 MonoInst *iargs [3];
4130                                 CHECK_STACK (3);
4131                                 sp -= 3;
4132                                 iargs [0] = sp [0];
4133                                 iargs [1] = sp [1];
4134                                 iargs [2] = sp [2];
4135                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4136                                 if (ip [1] == CEE_CPBLK) {
4137                                         mono_emit_jit_icall (cfg, bblock, helper_memcpy, iargs, ip);
4138                                 } else {
4139                                         mono_emit_jit_icall (cfg, bblock, helper_memset, iargs, ip);
4140                                 }
4141                                 ip += 2;
4142                                 inline_costs += 1;
4143                                 break;
4144                         }
4145                         case CEE_RETHROW: {
4146                                 MonoInst *load;
4147                                 /* FIXME: check we are in a catch handler */
4148                                 NEW_TEMPLOAD (cfg, load, cfg->exvar->inst_c0);
4149                                 load->cil_code = ip;
4150                                 MONO_INST_NEW (cfg, ins, CEE_THROW);
4151                                 ins->inst_left = load;
4152                                 ins->cil_code = ip;
4153                                 MONO_ADD_INS (bblock, ins);
4154                                 sp = stack_start;
4155                                 start_new_bblock = 1;
4156                                 ip += 2;
4157                                 break;
4158                         }
4159                         case CEE_SIZEOF:
4160                                 CHECK_STACK_OVF (1);
4161                                 token = read32 (ip + 2);
4162                                 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC) {
4163                                         MonoType *type = mono_type_create_from_typespec (image, token);
4164                                         token = mono_type_size (type, &align);
4165                                         mono_metadata_free_type (type);
4166                                 } else {
4167                                         MonoClass *szclass = mono_class_get (image, token);
4168                                         mono_class_init (szclass);
4169                                         token = mono_class_value_size (szclass, &align);
4170                                 }
4171                                 NEW_ICONST (cfg, ins, token);
4172                                 ins->cil_code = ip;
4173                                 *sp++= ins;
4174                                 ip += 6;
4175                                 break;
4176                         case CEE_REFANYTYPE:
4177                                 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
4178                                 break;
4179                         default:
4180                                 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
4181                         }
4182                         break;
4183                 }
4184                 default:
4185                         g_error ("opcode 0x%02x not handled", *ip);
4186                 }
4187         }
4188         if (start_new_bblock != 1)
4189                 goto unverified;
4190
4191         bblock->cil_length = ip - bblock->cil_code;
4192         bblock->next_bb = end_bblock;
4193         link_bblock (cfg, bblock, end_bblock);
4194
4195         if (cfg->method == method && cfg->domainvar) {
4196                 MonoCallInst *call;
4197                 MonoInst *store;
4198
4199                 MONO_INST_NEW_CALL (cfg, call, CEE_CALL);
4200                 call->signature = helper_sig_domain_get;
4201                 call->inst.type = STACK_PTR;
4202                 call->fptr = mono_domain_get;
4203                 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, (MonoInst*)call);
4204                 
4205                 MONO_ADD_INS (init_localsbb, store);
4206         }
4207
4208         if (header->init_locals) {
4209                 MonoInst *store;
4210                 for (i = 0; i < header->num_locals; ++i) {
4211                         int t = header->locals [i]->type;
4212                         if (t == MONO_TYPE_VALUETYPE && header->locals [i]->data.klass->enumtype)
4213                                 t = header->locals [i]->data.klass->enum_basetype->type;
4214                         /* FIXME: use initobj for valuetypes, handle pointers, long, float. */
4215                         if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
4216                                 NEW_ICONST (cfg, ins, 0);
4217                                 NEW_LOCSTORE (cfg, store, i, ins);
4218                                 MONO_ADD_INS (init_localsbb, store);
4219                         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
4220                                 MONO_INST_NEW (cfg, ins, OP_I8CONST);
4221                                 ins->type = STACK_I8;
4222                                 ins->inst_l = 0;
4223                                 NEW_LOCSTORE (cfg, store, i, ins);
4224                                 MONO_ADD_INS (init_localsbb, store);
4225                         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
4226                                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
4227                                 ins->type = STACK_R8;
4228                                 ins->inst_p0 = (void*)&r8_0;
4229                                 NEW_LOCSTORE (cfg, store, i, ins);
4230                                 MONO_ADD_INS (init_localsbb, store);
4231                         } else if (t == MONO_TYPE_VALUETYPE) {
4232                                 NEW_LOCLOADA (cfg, ins, i);
4233                                 handle_initobj (cfg, init_localsbb, ins, NULL, mono_class_from_mono_type (header->locals [i]), NULL, NULL);
4234                                 break;
4235                         } else {
4236                                 NEW_PCONST (cfg, ins, NULL);
4237                                 NEW_LOCSTORE (cfg, store, i, ins);
4238                                 MONO_ADD_INS (init_localsbb, store);
4239                         }
4240                 }
4241         }
4242
4243         
4244         /* resolve backward branches in the middle of an existing basic block */
4245         for (tmp = bb_recheck; tmp; tmp = tmp->next) {
4246                 bblock = tmp->data;
4247                 /*g_print ("need recheck in %s at IL_%04x\n", method->name, bblock->cil_code - header->code);*/
4248                 tblock = find_previous (bbhash, start_bblock, bblock->cil_code);
4249                 if (tblock != start_bblock) {
4250                         int l;
4251                         split_bblock (cfg, tblock, bblock);
4252                         l = bblock->cil_code - header->code;
4253                         bblock->cil_length = tblock->cil_length - l;
4254                         tblock->cil_length = l;
4255                 } else {
4256                         g_print ("recheck failed.\n");
4257                 }
4258         }
4259
4260         /* we compute regions here, because the length of filter clauses is not known in advance.
4261         * It is computed in the CEE_ENDFILTER case in the above switch statement*/
4262         if (cfg->method == method) {
4263                 MonoBasicBlock *bb;
4264                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4265                         bb->region = mono_find_block_region (cfg, bb->real_offset, filter_lengths);
4266                         if (cfg->verbose_level > 2)
4267                                 g_print ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
4268                 }
4269         } else {
4270                 g_hash_table_destroy (bbhash);
4271         }
4272
4273         return inline_costs;
4274
4275  inline_failure:
4276         if (cfg->method != method) 
4277                 g_hash_table_destroy (bbhash);
4278         return -1;
4279
4280  unverified:
4281         if (cfg->method != method) 
4282                 g_hash_table_destroy (bbhash);
4283         g_error ("Invalid IL code at IL%04x in %s: %s\n", ip - header->code, 
4284                  mono_method_full_name (method, TRUE), mono_disasm_code_one (NULL, method, ip, NULL));
4285         return -1;
4286 }
4287
4288 void
4289 mono_print_tree (MonoInst *tree) {
4290         int arity;
4291
4292         if (!tree)
4293                 return;
4294
4295         arity = mono_burg_arity [tree->opcode];
4296
4297         printf (" %s%s", arity?"(":"",  mono_inst_name (tree->opcode));
4298
4299         switch (tree->opcode) {
4300         case OP_ICONST:
4301                 printf ("[%d]", tree->inst_c0);
4302                 break;
4303         case OP_I8CONST:
4304                 printf ("[%lld]", tree->inst_l);
4305                 break;
4306         case OP_R8CONST:
4307                 printf ("[%f]", *(double*)tree->inst_p0);
4308                 break;
4309         case OP_R4CONST:
4310                 printf ("[%f]", *(float*)tree->inst_p0);
4311                 break;
4312         case OP_ARG:
4313         case OP_LOCAL:
4314                 printf ("[%d]", tree->inst_c0);
4315                 break;
4316         case OP_REGOFFSET:
4317                 printf ("[0x%x(%s)]", tree->inst_offset, mono_arch_regname (tree->inst_basereg));
4318                 break;
4319         case OP_REGVAR:
4320                 printf ("[%s]", mono_arch_regname (tree->dreg));
4321                 break;
4322         case CEE_NEWARR:
4323                 printf ("[%s]",  tree->inst_newa_class->name);
4324                 mono_print_tree (tree->inst_newa_len);
4325                 break;
4326         case CEE_CALL:
4327         case CEE_CALLVIRT:
4328         case OP_FCALL:
4329         case OP_FCALLVIRT:
4330         case OP_LCALL:
4331         case OP_LCALLVIRT:
4332         case OP_VCALL:
4333         case OP_VCALLVIRT:
4334         case OP_VOIDCALL:
4335         case OP_VOIDCALLVIRT: {
4336                 MonoCallInst *call = (MonoCallInst*)tree;
4337                 if (call->method)
4338                         printf ("[%s]", call->method->name);
4339                 break;
4340         }
4341         case OP_PHI: {
4342                 int i;
4343                 printf ("[%d (", tree->inst_c0);
4344                 for (i = 0; i < tree->inst_phi_args [0]; i++) {
4345                         if (i)
4346                                 printf (", ");
4347                         printf ("%d", tree->inst_phi_args [i + 1]);
4348                 }
4349                 printf (")]");
4350                 break;
4351         }
4352         case OP_RENAME:
4353         case OP_RETARG:
4354         case CEE_NOP:
4355         case CEE_JMP:
4356         case CEE_BREAK:
4357                 break;
4358         case CEE_BR:
4359                 printf ("[B%d]", tree->inst_target_bb->block_num);
4360                 break;
4361         case CEE_SWITCH:
4362         case CEE_ISINST:
4363         case CEE_CASTCLASS:
4364         case OP_OUTARG:
4365         case OP_CALL_REG:
4366         case OP_FCALL_REG:
4367         case OP_LCALL_REG:
4368         case OP_VCALL_REG:
4369         case OP_VOIDCALL_REG:
4370                 mono_print_tree (tree->inst_left);
4371                 break;
4372         case CEE_BNE_UN:
4373         case CEE_BEQ:
4374         case CEE_BLT:
4375         case CEE_BLT_UN:
4376         case CEE_BGT:
4377         case CEE_BGT_UN:
4378         case CEE_BGE:
4379         case CEE_BGE_UN:
4380         case CEE_BLE:
4381         case CEE_BLE_UN:
4382                 printf ("[B%dB%d]", tree->inst_true_bb->block_num, tree->inst_false_bb->block_num);
4383                 mono_print_tree (tree->inst_left);
4384                 break;
4385         default:
4386                 if (arity) {
4387                         mono_print_tree (tree->inst_left);
4388                         if (arity > 1)
4389                                 mono_print_tree (tree->inst_right);
4390                 }
4391                 break;
4392         }
4393
4394         if (arity)
4395                 printf (")");
4396 }
4397
4398 static void
4399 create_helper_signature (void)
4400 {
4401         /* FIXME: set call conv */
4402         /* MonoArray * mono_array_new (MonoDomain *domain, MonoClass *klass, gint32 len) */
4403         helper_sig_newarr = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4404         helper_sig_newarr->params [0] = helper_sig_newarr->params [1] = &mono_defaults.int_class->byval_arg;
4405         helper_sig_newarr->ret = &mono_defaults.object_class->byval_arg;
4406         helper_sig_newarr->params [2] = &mono_defaults.int32_class->byval_arg;
4407         helper_sig_newarr->pinvoke = 1;
4408
4409         /* MonoObject * mono_object_new (MonoDomain *domain, MonoClass *klass) */
4410         helper_sig_object_new = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4411         helper_sig_object_new->params [0] = helper_sig_object_new->params [1] = &mono_defaults.int_class->byval_arg;
4412         helper_sig_object_new->ret = &mono_defaults.object_class->byval_arg;
4413         helper_sig_object_new->pinvoke = 1;
4414
4415         /* void* mono_method_compile (MonoMethod*) */
4416         helper_sig_compile = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4417         helper_sig_compile->params [0] = helper_sig_compile->ret = &mono_defaults.int_class->byval_arg;
4418         helper_sig_compile->pinvoke = 1;
4419
4420         /* void* mono_ldvirtfn (MonoObject *, MonoMethod*) */
4421         helper_sig_compile_virt = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4422         helper_sig_compile_virt->params [0] = &mono_defaults.object_class->byval_arg;
4423         helper_sig_compile_virt->params [1] = helper_sig_compile_virt->ret = &mono_defaults.int_class->byval_arg;
4424         helper_sig_compile_virt->pinvoke = 1;
4425
4426         /* MonoString* mono_ldstr (MonoDomain *domain, MonoImage *image, guint32 str_index) */
4427         helper_sig_ldstr = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4428         helper_sig_ldstr->params [0] = helper_sig_ldstr->params [1] = &mono_defaults.int_class->byval_arg;
4429         helper_sig_ldstr->params [2] = &mono_defaults.int32_class->byval_arg;
4430         helper_sig_ldstr->ret = &mono_defaults.object_class->byval_arg;
4431         helper_sig_ldstr->pinvoke = 1;
4432
4433         /* MonoDomain *mono_domain_get (void) */
4434         helper_sig_domain_get = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4435         helper_sig_domain_get->ret = &mono_defaults.int_class->byval_arg;
4436         helper_sig_domain_get->pinvoke = 1;
4437
4438         /* void* stelem_ref (MonoArray *, int index, MonoObject *) */
4439         helper_sig_stelem_ref = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4440         helper_sig_stelem_ref->params [0] = &mono_defaults.array_class->byval_arg;
4441         helper_sig_stelem_ref->params [1] = &mono_defaults.int32_class->byval_arg;
4442         helper_sig_stelem_ref->params [2] = &mono_defaults.object_class->byval_arg;
4443         helper_sig_stelem_ref->ret = &mono_defaults.void_class->byval_arg;
4444         helper_sig_stelem_ref->pinvoke = 1;
4445
4446         /* long amethod (long, long) */
4447         helper_sig_long_long_long = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4448         helper_sig_long_long_long->params [0] = helper_sig_long_long_long->params [1] = 
4449                 &mono_defaults.int64_class->byval_arg;
4450         helper_sig_long_long_long->ret = &mono_defaults.int64_class->byval_arg;
4451         helper_sig_long_long_long->pinvoke = 1;
4452
4453         /* object  amethod (intptr) */
4454         helper_sig_obj_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4455         helper_sig_obj_ptr->params [0] = &mono_defaults.int_class->byval_arg;
4456         helper_sig_obj_ptr->ret = &mono_defaults.object_class->byval_arg;
4457         helper_sig_obj_ptr->pinvoke = 1;
4458
4459         /* void amethod (intptr) */
4460         helper_sig_void_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4461         helper_sig_void_ptr->params [0] = &mono_defaults.int_class->byval_arg;
4462         helper_sig_void_ptr->ret = &mono_defaults.void_class->byval_arg;
4463         helper_sig_void_ptr->pinvoke = 1;
4464
4465         /* void amethod (MonoObject *obj) */
4466         helper_sig_void_obj = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4467         helper_sig_void_obj->params [0] = &mono_defaults.object_class->byval_arg;
4468         helper_sig_void_obj->ret = &mono_defaults.void_class->byval_arg;
4469         helper_sig_void_obj->pinvoke = 1;
4470
4471         /* intptr amethod (void) */
4472         helper_sig_ptr_void = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4473         helper_sig_ptr_void->ret = &mono_defaults.int_class->byval_arg;
4474         helper_sig_ptr_void->pinvoke = 1;
4475
4476         /* void  amethod (intptr, intptr) */
4477         helper_sig_void_ptr_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4478         helper_sig_void_ptr_ptr->params [0] = &mono_defaults.int_class->byval_arg;
4479         helper_sig_void_ptr_ptr->params [1] = &mono_defaults.int_class->byval_arg;
4480         helper_sig_void_ptr_ptr->ret = &mono_defaults.void_class->byval_arg;
4481         helper_sig_void_ptr_ptr->pinvoke = 1;
4482
4483         /* void  amethod (intptr, intptr, intptr) */
4484         helper_sig_void_ptr_ptr_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4485         helper_sig_void_ptr_ptr_ptr->params [0] = &mono_defaults.int_class->byval_arg;
4486         helper_sig_void_ptr_ptr_ptr->params [1] = &mono_defaults.int_class->byval_arg;
4487         helper_sig_void_ptr_ptr_ptr->params [2] = &mono_defaults.int_class->byval_arg;
4488         helper_sig_void_ptr_ptr_ptr->ret = &mono_defaults.void_class->byval_arg;
4489         helper_sig_void_ptr_ptr_ptr->pinvoke = 1;
4490
4491         /* intptr  amethod (intptr, intptr) */
4492         helper_sig_ptr_ptr_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4493         helper_sig_ptr_ptr_ptr->params [0] = &mono_defaults.int_class->byval_arg;
4494         helper_sig_ptr_ptr_ptr->params [1] = &mono_defaults.int_class->byval_arg;
4495         helper_sig_ptr_ptr_ptr->ret = &mono_defaults.int_class->byval_arg;
4496         helper_sig_ptr_ptr_ptr->pinvoke = 1;
4497
4498         /* IntPtr  amethod (object) */
4499         helper_sig_ptr_obj = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4500         helper_sig_ptr_obj->params [0] = &mono_defaults.object_class->byval_arg;
4501         helper_sig_ptr_obj->ret = &mono_defaults.int_class->byval_arg;
4502         helper_sig_ptr_obj->pinvoke = 1;
4503
4504         /* long amethod (long, guint32) */
4505         helper_sig_long_long_int = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4506         helper_sig_long_long_int->params [0] = &mono_defaults.int64_class->byval_arg;
4507         helper_sig_long_long_int->params [1] = &mono_defaults.int32_class->byval_arg;
4508         helper_sig_long_long_int->ret = &mono_defaults.int64_class->byval_arg;
4509         helper_sig_long_long_int->pinvoke = 1;
4510
4511         /* ulong amethod (double) */
4512         helper_sig_ulong_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4513         helper_sig_ulong_double->params [0] = &mono_defaults.double_class->byval_arg;
4514         helper_sig_ulong_double->ret = &mono_defaults.uint64_class->byval_arg;
4515         helper_sig_ulong_double->pinvoke = 1;
4516
4517         /* long amethod (double) */
4518         helper_sig_long_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4519         helper_sig_long_double->params [0] = &mono_defaults.double_class->byval_arg;
4520         helper_sig_long_double->ret = &mono_defaults.int64_class->byval_arg;
4521         helper_sig_long_double->pinvoke = 1;
4522
4523         /* uint amethod (double) */
4524         helper_sig_uint_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4525         helper_sig_uint_double->params [0] = &mono_defaults.double_class->byval_arg;
4526         helper_sig_uint_double->ret = &mono_defaults.uint32_class->byval_arg;
4527         helper_sig_uint_double->pinvoke = 1;
4528
4529         /* int amethod (double) */
4530         helper_sig_int_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4531         helper_sig_int_double->params [0] = &mono_defaults.double_class->byval_arg;
4532         helper_sig_int_double->ret = &mono_defaults.int32_class->byval_arg;
4533         helper_sig_int_double->pinvoke = 1;
4534
4535         /* void  initobj (intptr, int size) */
4536         helper_sig_initobj = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4537         helper_sig_initobj->params [0] = &mono_defaults.int_class->byval_arg;
4538         helper_sig_initobj->params [1] = &mono_defaults.int32_class->byval_arg;
4539         helper_sig_initobj->ret = &mono_defaults.void_class->byval_arg;
4540         helper_sig_initobj->pinvoke = 1;
4541
4542         /* void  memcpy (intptr, intptr, int size) */
4543         helper_sig_memcpy = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4544         helper_sig_memcpy->params [0] = &mono_defaults.int_class->byval_arg;
4545         helper_sig_memcpy->params [1] = &mono_defaults.int_class->byval_arg;
4546         helper_sig_memcpy->params [2] = &mono_defaults.int32_class->byval_arg;
4547         helper_sig_memcpy->ret = &mono_defaults.void_class->byval_arg;
4548         helper_sig_memcpy->pinvoke = 1;
4549
4550         /* void  memset (intptr, int val, int size) */
4551         helper_sig_memset = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4552         helper_sig_memset->params [0] = &mono_defaults.int_class->byval_arg;
4553         helper_sig_memset->params [1] = &mono_defaults.int32_class->byval_arg;
4554         helper_sig_memset->params [2] = &mono_defaults.int32_class->byval_arg;
4555         helper_sig_memset->ret = &mono_defaults.void_class->byval_arg;
4556         helper_sig_memset->pinvoke = 1;
4557 }
4558
4559 static GHashTable *jit_icall_hash_name = NULL;
4560 static GHashTable *jit_icall_hash_addr = NULL;
4561
4562 MonoJitICallInfo *
4563 mono_find_jit_icall_by_name (const char *name)
4564 {
4565         g_assert (jit_icall_hash_name);
4566
4567         //printf ("lookup addr %s %p\n", name, g_hash_table_lookup (jit_icall_hash_name, name));
4568         return g_hash_table_lookup (jit_icall_hash_name, name);
4569 }
4570
4571 MonoJitICallInfo *
4572 mono_find_jit_icall_by_addr (gconstpointer addr)
4573 {
4574         g_assert (jit_icall_hash_addr);
4575
4576         return g_hash_table_lookup (jit_icall_hash_addr, (gpointer)addr);
4577 }
4578
4579 MonoJitICallInfo *
4580 mono_register_jit_icall (gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean is_save)
4581 {
4582         MonoJitICallInfo *info;
4583         MonoMethod *wrapper;
4584         char *n;
4585         
4586         g_assert (func);
4587         g_assert (name);
4588
4589         if (!jit_icall_hash_name) {
4590                 jit_icall_hash_name = g_hash_table_new (g_str_hash, g_str_equal);
4591                 jit_icall_hash_addr = g_hash_table_new (NULL, NULL);
4592         }
4593
4594         if (g_hash_table_lookup (jit_icall_hash_name, name)) {
4595                 g_warning ("jit icall already defined \"%s\"\n", name);
4596                 g_assert_not_reached ();
4597         }
4598
4599         info = g_new (MonoJitICallInfo, 1);
4600         
4601         info->name = g_strdup (name);
4602         info->func = func;
4603         info->sig = sig;
4604                 
4605         if (is_save
4606 #ifdef MONO_USE_EXC_TABLES
4607             || mono_arch_has_unwind_info (func)
4608 #endif
4609             ) {
4610                 info->wrapper = func;
4611         } else {
4612                 g_assert (sig);
4613                 n = g_strdup_printf ("__icall_wrapper_%s", name);       
4614                 wrapper = mono_marshal_get_icall_wrapper (sig, n, func);
4615                 info->wrapper = mono_jit_compile_method (wrapper);
4616                 g_free (n);
4617         }
4618
4619         g_hash_table_insert (jit_icall_hash_name, info->name, info);
4620         g_hash_table_insert (jit_icall_hash_addr, (gpointer)func, info);
4621         if (func != info->wrapper)
4622                 g_hash_table_insert (jit_icall_hash_addr, (gpointer)info->wrapper, info);
4623
4624         return info;
4625 }
4626
4627 static GHashTable *emul_opcode_hash = NULL;
4628
4629 static MonoJitICallInfo *
4630 mono_find_jit_opcode_emulation (int opcode)
4631 {
4632         if  (emul_opcode_hash)
4633                 return g_hash_table_lookup (emul_opcode_hash, (gpointer)opcode);
4634         else
4635                 return NULL;
4636 }
4637
4638 void
4639 mono_register_opcode_emulation (int opcode, MonoMethodSignature *sig, gpointer func)
4640 {
4641         MonoJitICallInfo *info;
4642         char *name;
4643
4644         if (!emul_opcode_hash)
4645                 emul_opcode_hash = g_hash_table_new (NULL, NULL);
4646
4647         g_assert (!sig->hasthis);
4648         g_assert (sig->param_count < 3);
4649
4650         name = g_strdup_printf ("__emulate_%s",  mono_inst_name (opcode));
4651
4652         info = mono_register_jit_icall (func, name, sig, FALSE);
4653
4654         g_free (name);
4655
4656         g_hash_table_insert (emul_opcode_hash, (gpointer)opcode, info);
4657 }
4658
4659 static void
4660 decompose_foreach (MonoInst *tree, gpointer data) 
4661 {
4662         static MonoJitICallInfo *newarr_info = NULL;
4663
4664         switch (tree->opcode) {
4665         case CEE_NEWARR: {
4666                 MonoCompile *cfg = data;
4667                 MonoInst *iargs [3];
4668
4669                 NEW_DOMAINCONST (cfg, iargs [0]);
4670                 NEW_CLASSCONST (cfg, iargs [1], tree->inst_newa_class);
4671                 iargs [2] = tree->inst_newa_len;
4672
4673                 if (!newarr_info) {
4674                         newarr_info =  mono_find_jit_icall_by_addr (mono_array_new);
4675                         g_assert (newarr_info);
4676                 }
4677
4678                 mono_emulate_opcode (cfg, tree, iargs, newarr_info);
4679                 break;
4680         }
4681
4682         default:
4683                 break;
4684         }
4685 }
4686
4687 void
4688 mono_inst_foreach (MonoInst *tree, MonoInstFunc func, gpointer data) {
4689
4690         switch (mono_burg_arity [tree->opcode]) {
4691         case 0: break;
4692         case 1: 
4693                 mono_inst_foreach (tree->inst_left, func, data);
4694                 break;
4695         case 2: 
4696                 mono_inst_foreach (tree->inst_left, func, data);
4697                 mono_inst_foreach (tree->inst_right, func, data);
4698                 break;
4699         default:
4700                 g_assert_not_reached ();
4701         }
4702         func (tree, data);
4703 }
4704
4705 #if 0
4706 static void
4707 mono_print_bb_code (MonoBasicBlock *bb) {
4708         if (bb->code) {
4709                 MonoInst *c = bb->code;
4710                 while (c) {
4711                         mono_print_tree (c);
4712                         g_print ("\n");
4713                         c = c->next;
4714                 }
4715         }
4716 }
4717 #endif
4718
4719 static void
4720 print_dfn (MonoCompile *cfg) {
4721         int i, j;
4722         char *code;
4723         MonoBasicBlock *bb;
4724
4725         g_print ("IR code for method %s\n", mono_method_full_name (cfg->method, TRUE));
4726
4727         for (i = 0; i < cfg->num_bblocks; ++i) {
4728                 bb = cfg->bblocks [i];
4729                 if (bb->cil_code) {
4730                         char* code1, *code2;
4731                         code1 = mono_disasm_code_one (NULL, cfg->method, bb->cil_code, NULL);
4732                         if (bb->last_ins->cil_code)
4733                                 code2 = mono_disasm_code_one (NULL, cfg->method, bb->last_ins->cil_code, NULL);
4734                         else
4735                                 code2 = g_strdup ("");
4736
4737                         code1 [strlen (code1) - 1] = 0;
4738                         code = g_strdup_printf ("%s -> %s", code1, code2);
4739                         g_free (code1);
4740                         g_free (code2);
4741                 } else
4742                         code = g_strdup ("\n");
4743                 g_print ("\nBB%d DFN%d (len: %d): %s", bb->block_num, i, bb->cil_length, code);
4744                 if (bb->code) {
4745                         MonoInst *c = bb->code;
4746                         while (c) {
4747                                 mono_print_tree (c);
4748                                 g_print ("\n");
4749                                 c = c->next;
4750                         }
4751                 } else {
4752
4753                 }
4754
4755                 g_print ("\tprev:");
4756                 for (j = 0; j < bb->in_count; ++j) {
4757                         g_print (" BB%d", bb->in_bb [j]->block_num);
4758                 }
4759                 g_print ("\t\tsucc:");
4760                 for (j = 0; j < bb->out_count; ++j) {
4761                         g_print (" BB%d", bb->out_bb [j]->block_num);
4762                 }
4763                 g_print ("\n\tidom: BB%d\n", bb->idom? bb->idom->block_num: -1);
4764
4765                 if (bb->idom)
4766                         g_assert (mono_bitset_test_fast (bb->dominators, bb->idom->dfn));
4767
4768                 if (bb->dominators)
4769                         mono_blockset_print (cfg, bb->dominators, "\tdominators", bb->idom? bb->idom->dfn: -1);
4770                 if (bb->dfrontier)
4771                         mono_blockset_print (cfg, bb->dfrontier, "\tdfrontier", -1);
4772                 g_free (code);
4773         }
4774
4775         g_print ("\n");
4776 }
4777
4778 /*
4779  * returns the offset used by spillvar. It allocates a new
4780  * spill variable if necessary. 
4781  */
4782 int
4783 mono_spillvar_offset (MonoCompile *cfg, int spillvar)
4784 {
4785         MonoSpillInfo **si, *info;
4786         int i = 0;
4787
4788         si = &cfg->spill_info; 
4789         
4790         while (i <= spillvar) {
4791
4792                 if (!*si) {
4793                         *si = info = mono_mempool_alloc (cfg->mempool, sizeof (MonoSpillInfo));
4794                         info->next = NULL;
4795                         cfg->stack_offset -= sizeof (gpointer);
4796                         info->offset = cfg->stack_offset;
4797                 }
4798
4799                 if (i == spillvar)
4800                         return (*si)->offset;
4801
4802                 i++;
4803                 si = &(*si)->next;
4804         }
4805
4806         g_assert_not_reached ();
4807         return 0;
4808 }
4809
4810 void
4811 mono_bblock_add_inst (MonoBasicBlock *bb, MonoInst *inst)
4812 {
4813         inst->next = NULL;
4814         if (bb->last_ins) {
4815                 g_assert (bb->code);
4816                 bb->last_ins->next = inst;
4817                 bb->last_ins = inst;
4818         } else {
4819                 bb->last_ins = bb->code = inst;
4820         }
4821 }
4822
4823 void
4824 mono_destroy_compile (MonoCompile *cfg)
4825 {
4826         //mono_mempool_stats (cfg->mempool);
4827         g_hash_table_destroy (cfg->bb_hash);
4828         if (cfg->rs)
4829                 mono_regstate_free (cfg->rs);
4830         mono_mempool_destroy (cfg->mempool);
4831         g_list_free (cfg->ldstr_list);
4832
4833         g_free (cfg->varinfo);
4834         g_free (cfg->vars);
4835         g_free (cfg);
4836 }
4837
4838 gpointer 
4839 mono_get_lmf_addr (void)
4840 {
4841         MonoJitTlsData *jit_tls;        
4842
4843         if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
4844                 return &jit_tls->lmf;
4845
4846         g_assert_not_reached ();
4847         return NULL;
4848 }
4849
4850 /**
4851  * mono_thread_abort:
4852  * @obj: exception object
4853  *
4854  * abort the thread, print exception information and stack trace
4855  */
4856 static void
4857 mono_thread_abort (MonoObject *obj)
4858 {
4859         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
4860         
4861         g_free (jit_tls);
4862
4863         ExitThread (-1);
4864 }
4865
4866 static void
4867 mono_thread_start_cb (guint32 tid, gpointer stack_start, gpointer func)
4868 {
4869         MonoJitTlsData *jit_tls;
4870         MonoLMF *lmf;
4871
4872         jit_tls = g_new0 (MonoJitTlsData, 1);
4873
4874         TlsSetValue (mono_jit_tls_id, jit_tls);
4875
4876         jit_tls->abort_func = mono_thread_abort;
4877         jit_tls->end_of_stack = stack_start;
4878
4879         lmf = g_new0 (MonoLMF, 1);
4880         lmf->ebp = -1;
4881
4882         jit_tls->lmf = lmf;
4883 }
4884
4885 void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
4886
4887 static void
4888 mono_thread_abort_dummy (MonoObject *obj)
4889 {
4890   if (mono_thread_attach_aborted_cb)
4891     mono_thread_attach_aborted_cb (obj);
4892   else
4893     mono_thread_abort (obj);
4894 }
4895
4896 static void
4897 mono_thread_attach_cb (guint32 tid, gpointer stack_start)
4898 {
4899         MonoJitTlsData *jit_tls;
4900         MonoLMF *lmf;
4901
4902         jit_tls = g_new0 (MonoJitTlsData, 1);
4903
4904         TlsSetValue (mono_jit_tls_id, jit_tls);
4905
4906         jit_tls->abort_func = mono_thread_abort_dummy;
4907         jit_tls->end_of_stack = stack_start;
4908
4909         lmf = g_new0 (MonoLMF, 1);
4910         lmf->ebp = -1;
4911
4912         jit_tls->lmf = lmf;
4913 }
4914
4915 void
4916 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
4917 {
4918         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
4919
4920         ji->ip.i = ip;
4921         ji->type = type;
4922         ji->data.target = target;
4923         ji->next = cfg->patch_info;
4924
4925         cfg->patch_info = ji;
4926 }
4927
4928 void
4929 mono_remove_patch_info (MonoCompile *cfg, int ip)
4930 {
4931         MonoJumpInfo **ji = &cfg->patch_info;
4932
4933         while (*ji) {
4934                 if ((*ji)->ip.i == ip)
4935                         *ji = (*ji)->next;
4936                 else
4937                         ji = &((*ji)->next);
4938         }
4939 }
4940
4941 static void
4942 dec_foreach (MonoInst *tree, MonoCompile *cfg) {
4943         MonoJitICallInfo *info;
4944
4945         switch (mono_burg_arity [tree->opcode]) {
4946         case 0: break;
4947         case 1: 
4948                 dec_foreach (tree->inst_left, cfg);
4949
4950                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
4951                         MonoInst *iargs [2];
4952                 
4953                         iargs [0] = tree->inst_left;
4954
4955                         mono_emulate_opcode (cfg, tree, iargs, info);
4956                         return;
4957                 }
4958
4959                 break;
4960         case 2: 
4961                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
4962                         MonoInst *iargs [2];
4963                 
4964                         iargs [0] = tree->inst_i0;
4965                         iargs [1] = tree->inst_i1;
4966                 
4967                         mono_emulate_opcode (cfg, tree, iargs, info);
4968
4969                         dec_foreach (iargs [0], cfg);
4970                         dec_foreach (iargs [1], cfg);
4971                         return;
4972                 } else {
4973                         dec_foreach (tree->inst_left, cfg);
4974                         dec_foreach (tree->inst_right, cfg);
4975                 }
4976                 break;
4977         default:
4978                 g_assert_not_reached ();
4979         }
4980         decompose_foreach (tree, cfg);
4981 }
4982
4983 static void
4984 decompose_pass (MonoCompile *cfg) {
4985         MonoBasicBlock *bb;
4986
4987         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4988                 MonoInst *tree;
4989                 cfg->cbb = bb;
4990                 cfg->prev_ins = NULL;
4991                 for (tree = cfg->cbb->code; tree; tree = tree->next) {
4992                         dec_foreach (tree, cfg);
4993                         cfg->prev_ins = tree;
4994                 }
4995         }
4996 }
4997
4998 static void
4999 nullify_basic_block (MonoBasicBlock *bb) 
5000 {
5001         bb->in_count = 0;
5002         bb->out_count = 0;
5003         bb->in_bb = NULL;
5004         bb->out_bb = NULL;
5005         bb->next_bb = NULL;
5006         bb->code = bb->last_ins = NULL;
5007 }
5008
5009 static void 
5010 replace_basic_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
5011 {
5012         int i, j;
5013
5014         for (i = 0; i < bb->out_count; i++) {
5015                 MonoBasicBlock *ob = bb->out_bb [i];
5016                 for (j = 0; j < ob->in_count; j++) {
5017                         if (ob->in_bb [j] == orig)
5018                                 ob->in_bb [j] = repl;
5019                 }
5020         }
5021
5022 }
5023
5024 static void
5025 merge_basic_blocks (MonoBasicBlock *bb, MonoBasicBlock *bbn) 
5026 {
5027         bb->out_count = bbn->out_count;
5028         bb->out_bb = bbn->out_bb;
5029
5030         replace_basic_block (bb, bbn, bb);
5031
5032         if (bb->last_ins) {
5033                 if (bbn->code) {
5034                         bb->last_ins->next = bbn->code;
5035                         bb->last_ins = bbn->last_ins;
5036                 }
5037         } else {
5038                 bb->code = bbn->code;
5039                 bb->last_ins = bbn->last_ins;
5040         }
5041         bb->next_bb = bbn->next_bb;
5042         nullify_basic_block (bbn);
5043 }
5044
5045 static void
5046 optimize_branches (MonoCompile *cfg) {
5047         int changed = FALSE;
5048         MonoBasicBlock *bb, *bbn;
5049
5050         do {
5051                 changed = FALSE;
5052
5053                 /* we skip the entry block (exit is handled specially instead ) */
5054                 for (bb = cfg->bb_entry->next_bb; bb; bb = bb->next_bb) {
5055
5056                         if (bb->out_count == 1) {
5057                                 bbn = bb->out_bb [0];
5058
5059                                 if (bb->region == bbn->region && bb->next_bb == bbn) {
5060                                 /* the block are in sequence anyway ... */
5061
5062                                         /* 
5063                                          * miguel: I do not understand what the test below does, could we
5064                                          * use a macro, or a comment here?  opcode > CEE_BEQ && <= BLT_UN
5065                                          *
5066                                          * It could also test for bb->last_in only once, and the value
5067                                          * could be cached (last_ins->opcode)
5068                                          */
5069                                         if (bb->last_ins && (bb->last_ins->opcode == CEE_BR || (
5070                                                 (bb->last_ins && bb->last_ins->opcode >= CEE_BEQ && bb->last_ins->opcode <= CEE_BLT_UN)))) {
5071                                                 bb->last_ins->opcode = CEE_NOP;
5072                                                 changed = TRUE;
5073                                                 if (cfg->verbose_level > 2)
5074                                                         g_print ("br removal triggered %d -> %d\n", bb->block_num, bbn->block_num);
5075                                         }
5076                                         /* fixme: this causes problems with inlining */
5077                                         if (bbn->in_count == 1) {
5078
5079                                                 if (bbn != cfg->bb_exit) {
5080                                                         if (cfg->verbose_level > 2)
5081                                                                 g_print ("block merge triggered %d -> %d\n", bb->block_num, bbn->block_num);
5082                                                         merge_basic_blocks (bb, bbn);
5083                                                         changed = TRUE;
5084                                                 }
5085
5086                                                 //mono_print_bb_code (bb);
5087                                         }
5088                                 } else {
5089                                         if (bb->last_ins && bb->last_ins->opcode == CEE_BR) {
5090                                                 bbn = bb->last_ins->inst_target_bb;
5091                                                 if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR) {
5092                                                         /*
5093                                                         if (cfg->verbose_level > 2)
5094                                                                 g_print ("in %s branch to branch triggered %d -> %d\n", cfg->method->name, bb->block_num, bbn->block_num);
5095                                                         bb->out_bb [0] = bb->last_ins->inst_target_bb = bbn->code->inst_target_bb;
5096                                                         changed = TRUE;*/
5097                                                 }
5098                                         }
5099                                 }
5100                         } else if (bb->out_count == 2) {
5101                                 /* fixme: this does not correctly unlink the blocks, so we get serious problems in idom code */
5102                                 if (0 && bb->last_ins && bb->last_ins->opcode >= CEE_BEQ && bb->last_ins->opcode <= CEE_BLT_UN) {
5103                                         bbn = bb->last_ins->inst_true_bb;
5104                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR) {
5105                                                 if (cfg->verbose_level > 2)
5106                                                         g_print ("cbranch to branch triggered %d -> %d (0x%02x)\n", bb->block_num, 
5107                                                                  bbn->block_num, bbn->code->opcode);
5108                                                  
5109                                                 if (bb->out_bb [0] == bbn) {
5110                                                         bb->out_bb [0] = bbn->code->inst_target_bb;
5111                                                 } else if (bb->out_bb [1] == bbn) {
5112                                                         bb->out_bb [1] = bbn->code->inst_target_bb;
5113                                                 }
5114                                                 bb->last_ins->inst_true_bb = bbn->code->inst_target_bb;
5115                                                 changed = TRUE;
5116                                         }
5117                                 }
5118                         }
5119                 }
5120         } while (changed);
5121 }
5122
5123 static void
5124 mono_compile_create_vars (MonoCompile *cfg)
5125 {
5126         MonoMethodSignature *sig;
5127         MonoMethodHeader *header;
5128         int i;
5129
5130         header = ((MonoMethodNormal *)cfg->method)->header;
5131
5132         sig = cfg->method->signature;
5133         
5134         if (!MONO_TYPE_IS_VOID (sig->ret)) {
5135                 cfg->ret = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
5136                 cfg->ret->opcode = OP_RETARG;
5137                 cfg->ret->inst_vtype = sig->ret;
5138                 cfg->ret->klass = mono_class_from_mono_type (sig->ret);
5139         }
5140
5141         if (sig->hasthis)
5142                 mono_compile_create_var (cfg, &cfg->method->klass->this_arg, OP_ARG);
5143
5144         for (i = 0; i < sig->param_count; ++i)
5145                 mono_compile_create_var (cfg, sig->params [i], OP_ARG);
5146
5147         cfg->locals_start = cfg->num_varinfo;
5148
5149         for (i = 0; i < header->num_locals; ++i)
5150                 mono_compile_create_var (cfg, header->locals [i], OP_LOCAL);
5151 }
5152
5153 #if 0
5154 static void
5155 mono_print_code (MonoCompile *cfg)
5156 {
5157         MonoBasicBlock *bb;
5158         
5159         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5160                 MonoInst *tree = bb->code;      
5161
5162                 if (!tree)
5163                         continue;
5164                 
5165                 g_print ("CODE BLOCK %d (nesting %d):\n", bb->block_num, bb->nesting);
5166
5167                 for (; tree; tree = tree->next) {
5168                         mono_print_tree (tree);
5169                         g_print ("\n");
5170                 }
5171
5172                 if (bb->last_ins)
5173                         bb->last_ins->next = NULL;
5174         }
5175 }
5176 #endif
5177
5178 extern const char * const mono_burg_rule_string [];
5179
5180 static void
5181 emit_state (MonoCompile *cfg, MBState *state, int goal)
5182 {
5183         MBState *kids [10];
5184         int ern = mono_burg_rule (state, goal);
5185         const guint16 *nts = mono_burg_nts [ern];
5186         MBEmitFunc emit;
5187
5188         //g_print ("rule: %s\n", mono_burg_rule_string [ern]);
5189         switch (goal) {
5190         case MB_NTERM_reg:
5191                 //if (state->reg2)
5192                 //      state->reg1 = state->reg2; /* chain rule */
5193                 //else
5194                 state->reg1 = mono_regstate_next_int (cfg->rs);
5195                 //g_print ("alloc symbolic R%d (reg2: R%d) in block %d\n", state->reg1, state->reg2, cfg->cbb->block_num);
5196                 break;
5197         case MB_NTERM_lreg:
5198                 state->reg1 = mono_regstate_next_int (cfg->rs);
5199                 state->reg2 = mono_regstate_next_int (cfg->rs);
5200                 break;
5201         case MB_NTERM_freg:
5202                 state->reg1 = mono_regstate_next_float (cfg->rs);
5203                 break;
5204         default:
5205                 /* do nothing */
5206                 break;
5207         }
5208         if (nts [0]) {
5209                 mono_burg_kids (state, ern, kids);
5210
5211                 emit_state (cfg, kids [0], nts [0]);
5212                 if (nts [1]) {
5213                         emit_state (cfg, kids [1], nts [1]);
5214                         if (nts [2]) {
5215                                 g_assert (!nts [3]);
5216                                 emit_state (cfg, kids [2], nts [2]);
5217                         }
5218                 }
5219         }
5220
5221 //      g_print ("emit: %s (%p)\n", mono_burg_rule_string [ern], state);
5222         if ((emit = mono_burg_func [ern]))
5223                 emit (state, state->tree, cfg); 
5224 }
5225
5226 #define DEBUG_SELECTION
5227
5228 static void 
5229 mini_select_instructions (MonoCompile *cfg)
5230 {
5231         MonoBasicBlock *bb;
5232         
5233         cfg->state_pool = mono_mempool_new ();
5234         cfg->rs = mono_regstate_new ();
5235
5236 #ifdef DEBUG_SELECTION
5237         if (cfg->verbose_level >= 4) {
5238         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5239                 MonoInst *tree = bb->code;      
5240                 g_print ("DUMP BLOCK %d:\n", bb->block_num);
5241                 if (!tree)
5242                         continue;
5243                 for (; tree; tree = tree->next) {
5244                         mono_print_tree (tree);
5245                         g_print ("\n");
5246                 }
5247         }
5248         }
5249 #endif
5250
5251         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5252                 MonoInst *tree = bb->code, *next;       
5253                 MBState *mbstate;
5254
5255                 if (!tree)
5256                         continue;
5257                 bb->code = NULL;
5258                 bb->last_ins = NULL;
5259                 
5260                 cfg->cbb = bb;
5261                 mono_regstate_reset (cfg->rs);
5262
5263 #ifdef DEBUG_SELECTION
5264                 if (cfg->verbose_level >= 3)
5265                         g_print ("LABEL BLOCK %d:\n", bb->block_num);
5266 #endif
5267                 for (; tree; tree = next) {
5268                         next = tree->next;
5269 #ifdef DEBUG_SELECTION
5270                         if (cfg->verbose_level >= 3) {
5271                                 mono_print_tree (tree);
5272                                 g_print ("\n");
5273                         }
5274 #endif
5275
5276                         if (!(mbstate = mono_burg_label (tree, cfg))) {
5277                                 g_warning ("unabled to label tree %p", tree);
5278                                 mono_print_tree (tree);
5279                                 g_print ("\n");                         
5280                                 g_assert_not_reached ();
5281                         }
5282                         emit_state (cfg, mbstate, MB_NTERM_stmt);
5283                 }
5284                 bb->max_ireg = cfg->rs->next_vireg;
5285                 bb->max_freg = cfg->rs->next_vfreg;
5286
5287                 if (bb->last_ins)
5288                         bb->last_ins->next = NULL;
5289
5290                 mono_mempool_empty (cfg->state_pool); 
5291         }
5292         mono_mempool_destroy (cfg->state_pool); 
5293 }
5294
5295 void
5296 mono_codegen (MonoCompile *cfg)
5297 {
5298         MonoJumpInfo *patch_info;
5299         MonoBasicBlock *bb;
5300         int i, max_epilog_size;
5301         guint8 *code;
5302
5303         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5304                 cfg->spill_count = 0;
5305                 /* we reuse dfn here */
5306                 /* bb->dfn = bb_count++; */
5307                 mono_arch_local_regalloc (cfg, bb);
5308         }
5309
5310         if (mono_trace_coverage)
5311                 mono_allocate_coverage_info (cfg->method, cfg->num_bblocks);
5312
5313         code = mono_arch_emit_prolog (cfg);
5314
5315         if (mono_jit_profile)
5316                 code = mono_arch_instrument_prolog (cfg, mono_profiler_method_enter, code, FALSE);
5317
5318         cfg->code_len = code - cfg->native_code;
5319         cfg->prolog_end = cfg->code_len;
5320
5321         mono_debug_open_method (cfg);
5322              
5323         /* emit code all basic blocks */
5324         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5325                 bb->native_offset = cfg->code_len;
5326                 mono_arch_output_basic_block (cfg, bb);
5327         }
5328         cfg->bb_exit->native_offset = cfg->code_len;
5329
5330         code = cfg->native_code + cfg->code_len;
5331
5332         max_epilog_size = mono_arch_max_epilog_size (cfg);
5333
5334         /* we always allocate code in cfg->domain->code_mp to increase locality */
5335         cfg->code_size = cfg->code_len + max_epilog_size;
5336         /* fixme: align to MONO_ARCH_CODE_ALIGNMENT */
5337         code = mono_mempool_alloc (cfg->domain->code_mp, cfg->code_size);
5338         memcpy (code, cfg->native_code, cfg->code_len);
5339         g_free (cfg->native_code);
5340         cfg->native_code = code;
5341         code = cfg->native_code + cfg->code_len;
5342   
5343         /* g_assert (((int)cfg->native_code & (MONO_ARCH_CODE_ALIGNMENT - 1)) == 0); */
5344
5345         cfg->epilog_begin = cfg->code_len;
5346
5347         if (mono_jit_profile)
5348                 code = mono_arch_instrument_epilog (cfg, mono_profiler_method_leave, code, FALSE);
5349
5350         cfg->code_len = code - cfg->native_code;
5351
5352         mono_arch_emit_epilog (cfg);
5353
5354         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5355                 switch (patch_info->type) {
5356                 case MONO_PATCH_INFO_ABS: {
5357                         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (patch_info->data.target);
5358                         if (info) {
5359                                 //printf ("TEST %s %p\n", info->name, patch_info->data.target);
5360                                 patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
5361                                 patch_info->data.name = info->name;
5362                         }
5363                         break;
5364                 }
5365                 case MONO_PATCH_INFO_SWITCH: {
5366                         gpointer *table = g_new (gpointer, patch_info->table_size);
5367                         patch_info->ip.i = patch_info->ip.label->inst_c0;
5368                         for (i = 0; i < patch_info->table_size; i++) {
5369                                 table [i] = (gpointer)patch_info->data.table [i]->native_offset;
5370                         }
5371                         patch_info->data.target = table;
5372                         break;
5373                 }
5374                 default:
5375                         /* do nothing */
5376                         break;
5377                 }
5378         }
5379        
5380         if (cfg->verbose_level > 1)
5381                 g_print ("Method %s::%s emmitted at %p to %p\n", cfg->method->klass->name, 
5382                          cfg->method->name, cfg->native_code, cfg->native_code + cfg->code_len);
5383
5384         mono_arch_patch_code (cfg->method, cfg->domain, cfg->native_code, cfg->patch_info);
5385
5386         mono_debug_close_method (cfg);
5387 }
5388
5389 static void
5390 mono_cprop_copy_values (MonoCompile *cfg, MonoInst *tree, MonoInst **acp)
5391 {
5392         MonoInst *cp;
5393         int arity;
5394
5395         if (tree->ssa_op == MONO_SSA_LOAD && (tree->inst_i0->opcode == OP_LOCAL || tree->inst_i0->opcode == OP_ARG) && 
5396             (cp = acp [tree->inst_i0->inst_c0]) && !tree->inst_i0->flags) {
5397
5398                 if (cp->opcode == OP_ICONST) {
5399                         if (cfg->opt & MONO_OPT_CONSPROP) {
5400                                 //{ static int c = 0; printf ("CCOPY %d %d %s\n", c++, cp->inst_c0, mono_method_full_name (cfg->method, TRUE)); }
5401                                 *tree = *cp;
5402                         }
5403                 } else {
5404                         if (tree->inst_i0->inst_vtype->type == cp->inst_vtype->type) {
5405                                 if (cfg->opt & MONO_OPT_COPYPROP) {
5406                                         //{ static int c = 0; printf ("VCOPY %d\n", ++c); }
5407                                         tree->inst_i0 = cp;
5408                                 } 
5409                         }
5410                 } 
5411         } else {
5412                 arity = mono_burg_arity [tree->opcode];
5413
5414                 if (arity) {
5415                         mono_cprop_copy_values (cfg, tree->inst_i0, acp);
5416                         if (cfg->opt & MONO_OPT_CFOLD)
5417                                 mono_constant_fold_inst (tree, NULL); 
5418                         if (arity > 1) {
5419                                 mono_cprop_copy_values (cfg, tree->inst_i1, acp);
5420                                 if (cfg->opt & MONO_OPT_CFOLD)
5421                                         mono_constant_fold_inst (tree, NULL); 
5422                         }
5423                         mono_constant_fold_inst (tree, NULL); 
5424                 }
5425         }
5426 }
5427
5428 static void
5429 mono_cprop_invalidate_values (MonoInst *tree, MonoInst **acp, int acp_size)
5430 {
5431         int arity;
5432
5433         switch (tree->opcode) {
5434         case CEE_STIND_I:
5435         case CEE_STIND_I1:
5436         case CEE_STIND_I2:
5437         case CEE_STIND_I4:
5438         case CEE_STIND_REF:
5439         case CEE_STIND_I8:
5440         case CEE_STIND_R4:
5441         case CEE_STIND_R8:
5442         case CEE_STOBJ:
5443                 if (tree->ssa_op == MONO_SSA_NOP) {
5444                         memset (acp, 0, sizeof (MonoInst *) * acp_size);
5445                         return;
5446                 }
5447
5448                 break;
5449         case CEE_CALL:
5450         case OP_CALL_REG:
5451         case CEE_CALLVIRT:
5452         case OP_LCALL_REG:
5453         case OP_LCALLVIRT:
5454         case OP_LCALL:
5455         case OP_FCALL_REG:
5456         case OP_FCALLVIRT:
5457         case OP_FCALL:
5458         case OP_VCALL_REG:
5459         case OP_VCALLVIRT:
5460         case OP_VCALL:
5461         case OP_VOIDCALL_REG:
5462         case OP_VOIDCALLVIRT:
5463         case OP_VOIDCALL: {
5464                 MonoCallInst *call = (MonoCallInst *)tree;
5465                 MonoMethodSignature *sig = call->signature;
5466                 int i, byref = FALSE;
5467
5468                 for (i = 0; i < sig->param_count; i++) {
5469                         if (sig->params [i]->byref) {
5470                                 byref = TRUE;
5471                                 break;
5472                         }
5473                 }
5474
5475                 if (byref)
5476                         memset (acp, 0, sizeof (MonoInst *) * acp_size);
5477
5478                 return;
5479         }
5480         default:
5481                 break;
5482         }
5483
5484         arity = mono_burg_arity [tree->opcode];
5485
5486         switch (arity) {
5487         case 0:
5488                 break;
5489         case 1:
5490                 mono_cprop_invalidate_values (tree->inst_i0, acp, acp_size);
5491                 break;
5492         case 2:
5493                 mono_cprop_invalidate_values (tree->inst_i0, acp, acp_size);
5494                 mono_cprop_invalidate_values (tree->inst_i1, acp, acp_size);
5495                 break;
5496         default:
5497                 g_assert_not_reached ();
5498         }
5499 }
5500
5501 static void
5502 mono_local_cprop_bb (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst **acp, int acp_size)
5503 {
5504         MonoInst *tree = bb->code;      
5505         int i;
5506
5507         if (!tree)
5508                 return;
5509
5510         for (; tree; tree = tree->next) {
5511
5512                 mono_cprop_copy_values (cfg, tree, acp);
5513
5514                 mono_cprop_invalidate_values (tree, acp, acp_size);
5515
5516                 if (tree->ssa_op == MONO_SSA_STORE  && 
5517                     (tree->inst_i0->opcode == OP_LOCAL || tree->inst_i0->opcode == OP_ARG)) {
5518                         MonoInst *i1 = tree->inst_i1;
5519
5520                         acp [tree->inst_i0->inst_c0] = NULL;
5521
5522                         for (i = 0; i < acp_size; i++) {
5523                                 if (acp [i] && acp [i]->opcode != OP_ICONST && 
5524                                     acp [i]->inst_c0 == tree->inst_i0->inst_c0) {
5525                                         acp [i] = NULL;
5526                                 }
5527                         }
5528
5529                         if (i1->opcode == OP_ICONST) {
5530                                 acp [tree->inst_i0->inst_c0] = i1;
5531                                 //printf ("DEF1 BB%d %d\n", bb->block_num,tree->inst_i0->inst_c0);
5532                         }
5533                         if (i1->ssa_op == MONO_SSA_LOAD && 
5534                             (i1->inst_i0->opcode == OP_LOCAL || i1->inst_i0->opcode == OP_ARG) &&
5535                             (i1->inst_i0->inst_c0 != tree->inst_i0->inst_c0)) {
5536                                 acp [tree->inst_i0->inst_c0] = i1->inst_i0;
5537                                 //printf ("DEF2 BB%d %d %d\n", bb->block_num,tree->inst_i0->inst_c0,i1->inst_i0->inst_c0);
5538                         }
5539                 }
5540
5541                 /*
5542                   if (tree->opcode == CEE_BEQ) {
5543                   g_assert (tree->inst_i0->opcode == OP_COMPARE);
5544                   if (tree->inst_i0->inst_i0->opcode == OP_ICONST &&
5545                   tree->inst_i0->inst_i1->opcode == OP_ICONST) {
5546                   
5547                   tree->opcode = CEE_BR;
5548                   if (tree->inst_i0->inst_i0->opcode == tree->inst_i0->inst_i1->opcode) {
5549                   tree->inst_target_bb = tree->inst_true_bb;
5550                   } else {
5551                   tree->inst_target_bb = tree->inst_false_bb;
5552                   }
5553                   }
5554                   }
5555                 */
5556         }
5557 }
5558
5559 static void
5560 mono_local_cprop (MonoCompile *cfg)
5561 {
5562         MonoBasicBlock *bb;
5563         MonoInst **acp;
5564
5565         acp = alloca (sizeof (MonoInst *) * cfg->num_varinfo);
5566
5567         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5568                 memset (acp, 0, sizeof (MonoInst *) * cfg->num_varinfo);
5569                 mono_local_cprop_bb (cfg, bb, acp, cfg->num_varinfo);
5570         }
5571 }
5572
5573 MonoCompile*
5574 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, int parts)
5575 {
5576         MonoMethodHeader *header = ((MonoMethodNormal *)method)->header;
5577         guint8 *ip = (guint8 *)header->code;
5578         MonoCompile *cfg;
5579         MonoJitInfo *jinfo;
5580         int dfn = 0, i, code_size_ratio;
5581
5582         mono_jit_stats.methods_compiled++;
5583         if (mono_jit_profile)
5584                 mono_profiler_method_jit (method);
5585
5586         cfg = g_new0 (MonoCompile, 1);
5587         cfg->method = method;
5588         cfg->mempool = mono_mempool_new ();
5589         cfg->opt = opts;
5590         cfg->bb_hash = g_hash_table_new (g_direct_hash, NULL);
5591         cfg->domain = domain;
5592         cfg->verbose_level = mini_verbose;
5593
5594         /*
5595          * create MonoInst* which represents arguments and local variables
5596          */
5597         mono_compile_create_vars (cfg);
5598
5599         if (cfg->verbose_level > 2)
5600                 g_print ("converting method %s\n", mono_method_full_name (method, TRUE));
5601
5602         if ((i = mono_method_to_ir (cfg, method, NULL, NULL, cfg->locals_start, NULL, NULL, NULL, 0)) < 0) {
5603                 mono_destroy_compile (cfg);
5604                 if (mono_jit_profile)
5605                         mono_profiler_method_end_jit (method, MONO_PROFILE_FAILED);
5606                 return NULL;
5607         }
5608
5609         mono_jit_stats.basic_blocks += cfg->num_bblocks;
5610         mono_jit_stats.max_basic_blocks = MAX (cfg->num_bblocks, mono_jit_stats.max_basic_blocks);
5611
5612         /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/
5613
5614         /* Depth-first ordering on basic blocks */
5615         cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
5616
5617         if (cfg->opt & MONO_OPT_BRANCH)
5618                 optimize_branches (cfg);
5619
5620         df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
5621         if (cfg->num_bblocks != dfn + 1) {
5622                 if (cfg->verbose_level > 1)
5623                         g_print ("unreachable code?\n");
5624                 cfg->num_bblocks = dfn + 1;
5625         }
5626
5627         if (cfg->opt & MONO_OPT_LOOP) {
5628                 mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM);
5629                 mono_compute_natural_loops (cfg);
5630         }
5631
5632
5633         /* after method_to_ir */
5634         if (parts == 1)
5635                 return cfg;
5636
5637 //#define DEBUGSSA "logic_run"
5638 #define DEBUGSSA_CLASS "Tests"
5639 #ifdef DEBUGSSA
5640
5641
5642         if (!header->num_clauses && !cfg->disable_ssa) {
5643                 mono_local_cprop (cfg);
5644                 mono_ssa_compute (cfg);
5645         }
5646 #else 
5647
5648         /* fixme: add all optimizations which requires SSA */
5649         if (cfg->opt & (MONO_OPT_DEADCE)) {
5650                 if (!(cfg->comp_done & MONO_COMP_SSA) && !header->num_clauses && !cfg->disable_ssa) {
5651                         mono_local_cprop (cfg);
5652                         mono_ssa_compute (cfg);
5653
5654                         if (cfg->verbose_level >= 2) {
5655                                 print_dfn (cfg);
5656                         }
5657                 }
5658         }
5659 #endif
5660
5661         /* after SSA translation */
5662         if (parts == 2)
5663                 return cfg;
5664
5665         if ((cfg->opt & MONO_OPT_CONSPROP) ||  (cfg->opt & MONO_OPT_COPYPROP)) {
5666                 if (cfg->comp_done & MONO_COMP_SSA) {
5667                         mono_ssa_cprop (cfg);
5668                 } else {
5669                         mono_local_cprop (cfg);
5670                 }
5671         }
5672
5673         if (cfg->comp_done & MONO_COMP_SSA) {                   
5674                 mono_ssa_deadce (cfg);
5675
5676                 //mono_ssa_strength_reduction (cfg);
5677
5678                 mono_ssa_remove (cfg);
5679
5680                 if (cfg->opt & MONO_OPT_BRANCH)
5681                         optimize_branches (cfg);
5682         }
5683
5684         /* after SSA removal */
5685         if (parts == 3)
5686                 return cfg;
5687         
5688         decompose_pass (cfg);
5689
5690         if (cfg->opt & MONO_OPT_LINEARS) {
5691                 GList *vars, *regs;
5692
5693                 /* fixme: maybe we can avoid to compute livenesss here if already computed ? */
5694                 cfg->comp_done &= ~MONO_COMP_LIVENESS;
5695                 if (!(cfg->comp_done & MONO_COMP_LIVENESS))
5696                         mono_analyze_liveness (cfg);
5697                 
5698                 if ((vars = mono_arch_get_allocatable_int_vars (cfg))) {
5699                         regs = mono_arch_get_global_int_regs (cfg);
5700                         mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs);
5701                 }
5702         }
5703
5704         //mono_print_code (cfg);
5705         
5706         //print_dfn (cfg);
5707
5708         /* variables are allocated after decompose, since decompose could create temps */
5709         mono_arch_allocate_vars (cfg);
5710
5711         if (cfg->opt & MONO_OPT_CFOLD)
5712                 mono_constant_fold (cfg);
5713
5714         mini_select_instructions (cfg);
5715
5716         mono_codegen (cfg);
5717         if (cfg->verbose_level >= 2) {
5718                 char *id =  mono_method_full_name (cfg->method, FALSE);
5719                 mono_disassemble_code (cfg->native_code, cfg->code_len, id + 3);
5720                 g_free (id);
5721         }
5722         
5723         jinfo = mono_mempool_alloc0 (cfg->domain->mp, sizeof (MonoJitInfo));
5724
5725         jinfo = g_new0 (MonoJitInfo, 1);
5726         jinfo->method = method;
5727         jinfo->code_start = cfg->native_code;
5728         jinfo->code_size = cfg->code_len;
5729         jinfo->used_regs = cfg->used_int_regs;
5730
5731         if (header->num_clauses) {
5732                 int i;
5733
5734                 jinfo->exvar_offset = cfg->exvar? cfg->exvar->inst_offset: 0;
5735                 jinfo->num_clauses = header->num_clauses;
5736                 jinfo->clauses = mono_mempool_alloc0 (cfg->domain->mp, 
5737                         sizeof (MonoJitExceptionInfo) * header->num_clauses);
5738
5739                 for (i = 0; i < header->num_clauses; i++) {
5740                         MonoExceptionClause *ec = &header->clauses [i];
5741                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
5742                         MonoBasicBlock *tblock;
5743
5744                         ei->flags = ec->flags;
5745
5746                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
5747                                 tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->token_or_filter);
5748                                 g_assert (tblock);
5749                                 ei->data.filter = cfg->native_code + tblock->native_offset;
5750                         } else {
5751                                 ei->data.token = ec->token_or_filter;
5752                         }
5753
5754                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->try_offset);
5755                         g_assert (tblock);
5756                         ei->try_start = cfg->native_code + tblock->native_offset;
5757                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->try_offset + ec->try_len);
5758                         g_assert (tblock);
5759                         ei->try_end = cfg->native_code + tblock->native_offset;
5760                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->handler_offset);
5761                         g_assert (tblock);
5762                         ei->handler_start = cfg->native_code + tblock->native_offset;
5763
5764                 }
5765         }
5766
5767         mono_jit_info_table_add (cfg->domain, jinfo);
5768
5769         /* collect statistics */
5770         mono_jit_stats.allocated_code_size += cfg->code_len;
5771         code_size_ratio = cfg->code_len;
5772         if (code_size_ratio > mono_jit_stats.biggest_method_size) {
5773                         mono_jit_stats.biggest_method_size = code_size_ratio;
5774                         mono_jit_stats.biggest_method = method;
5775         }
5776         code_size_ratio = (code_size_ratio * 100) / ((MonoMethodNormal *)method)->header->code_size;
5777         if (code_size_ratio > mono_jit_stats.max_code_size_ratio) {
5778                 mono_jit_stats.max_code_size_ratio = code_size_ratio;
5779                 mono_jit_stats.max_ratio_method = method;
5780         }
5781         mono_jit_stats.native_code_size += cfg->code_len;
5782
5783         if (mono_jit_profile)
5784                 mono_profiler_method_end_jit (method, MONO_PROFILE_OK);
5785
5786         return cfg;
5787 }
5788
5789 static gpointer
5790 mono_jit_compile_method (MonoMethod *method)
5791 {
5792         /* FIXME: later copy the code from mono */
5793         MonoDomain *target_domain, *domain = mono_domain_get ();
5794         MonoCompile *cfg;
5795         GHashTable *jit_code_hash;
5796         gpointer code;
5797
5798         if (default_opt & MONO_OPT_SAHRED)
5799                 target_domain = mono_root_domain;
5800         else 
5801                 target_domain = domain;
5802
5803         jit_code_hash = target_domain->jit_code_hash;
5804
5805         if ((code = g_hash_table_lookup (jit_code_hash, method))) {
5806                 mono_jit_stats.methods_lookups++;
5807                 return code;
5808         }
5809
5810 #ifdef MONO_USE_AOT_COMPILER
5811         if (!mono_compile_aot) {
5812                 mono_class_init (method->klass);
5813                 if ((code = mono_aot_get_method (method))) {
5814                         g_hash_table_insert (jit_code_hash, method, code);
5815                         return code;
5816                 }
5817         }
5818 #endif
5819
5820         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
5821             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5822                 if (!method->info) {
5823                         MonoMethod *nm;
5824
5825                         if (!method->addr && (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5826                                 mono_lookup_pinvoke_call (method);
5827 #ifdef MONO_USE_EXC_TABLES
5828                         if (mono_method_blittable (method)) {
5829                                 method->info = method->addr;
5830                         } else {
5831 #endif
5832                                 nm = mono_marshal_get_native_wrapper (method);
5833                                 method->info = mono_compile_method (nm);
5834
5835                                 //if (mono_debug_format != MONO_DEBUG_FORMAT_NONE) 
5836                                 //mono_debug_add_wrapper (method, nm);
5837 #ifdef MONO_USE_EXC_TABLES
5838                         }
5839 #endif
5840                 }
5841                 return method->info;
5842         } else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
5843                 const char *name = method->name;
5844                 MonoMethod *nm;
5845
5846                 if (method->klass->parent == mono_defaults.multicastdelegate_class) {
5847                         if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
5848                                 /* FIXME: uhm, we need a wrapper to handle exceptions? */
5849                                 return (gpointer)mono_delegate_ctor;
5850                         } else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
5851                                 nm = mono_marshal_get_delegate_invoke (method);
5852                                 return mono_jit_compile_method (nm);
5853                         } else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
5854                                 nm = mono_marshal_get_delegate_begin_invoke (method);
5855                                 return mono_jit_compile_method (nm);
5856                         } else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
5857                                 nm = mono_marshal_get_delegate_end_invoke (method);
5858                                 return mono_jit_compile_method (nm);
5859                         }
5860                 }
5861                 return NULL;
5862         }
5863
5864         cfg = mini_method_compile (method, default_opt, target_domain, 0);
5865         code = cfg->native_code;
5866         mono_destroy_compile (cfg);
5867
5868         g_hash_table_insert (jit_code_hash, method, code);
5869
5870         /* make sure runtime_init is called */
5871         mono_class_vtable (target_domain, method->klass);
5872
5873         return code;
5874 }
5875
5876 /**
5877  * mono_jit_runtime_invoke:
5878  * @method: the method to invoke
5879  * @obj: this pointer
5880  * @params: array of parameter values.
5881  * @exc: used to catch exceptions objects
5882  */
5883 static MonoObject*
5884 mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
5885 {
5886         MonoMethod *invoke;
5887         MonoObject *(*runtime_invoke) (MonoObject *this, void **params, MonoObject **exc);
5888         invoke = mono_marshal_get_runtime_invoke (method);
5889         runtime_invoke = mono_jit_compile_method (invoke);      
5890         return runtime_invoke (obj, params, exc);
5891 }
5892
5893 #ifdef PLATFORM_WIN32
5894 #define GET_CONTEXT \
5895         struct sigcontext *ctx = (struct sigcontext*)_dummy;
5896 #else
5897 #define GET_CONTEXT \
5898         void **_p = (void **)&_dummy; \
5899         struct sigcontext *ctx = (struct sigcontext *)++_p;
5900 #endif
5901
5902 static void
5903 sigfpe_signal_handler (int _dummy)
5904 {
5905         MonoException *exc;
5906         GET_CONTEXT
5907
5908         exc = mono_get_exception_divide_by_zero ();
5909         
5910         mono_arch_handle_exception (ctx, exc, FALSE);
5911 }
5912
5913 static void
5914 sigill_signal_handler (int _dummy)
5915 {
5916         MonoException *exc;
5917         GET_CONTEXT
5918         exc = mono_get_exception_execution_engine ("SIGILL");
5919         
5920         mono_arch_handle_exception (ctx, exc, FALSE);
5921 }
5922
5923 static void
5924 sigsegv_signal_handler (int _dummy)
5925 {
5926         MonoException *exc;
5927         GET_CONTEXT
5928
5929         exc = mono_get_exception_null_reference ();
5930         
5931         mono_arch_handle_exception (ctx, exc, FALSE);
5932 }
5933
5934 static void
5935 sigusr1_signal_handler (int _dummy)
5936 {
5937         MonoThread *thread;
5938         GET_CONTEXT
5939         
5940         thread = mono_thread_current ();
5941         
5942         g_assert (thread->abort_exc);
5943
5944         mono_arch_handle_exception (ctx, thread->abort_exc, FALSE);
5945 }
5946
5947 static void
5948 mono_runtime_install_handlers (void)
5949 {
5950 #ifndef PLATFORM_WIN32
5951         struct sigaction sa;
5952 #endif
5953
5954 #ifdef PLATFORM_WIN32
5955         win32_seh_init();
5956         win32_seh_set_handler(SIGFPE, sigfpe_signal_handler);
5957         win32_seh_set_handler(SIGILL, sigill_signal_handler);
5958         win32_seh_set_handler(SIGSEGV, sigsegv_signal_handler);
5959 #else /* !PLATFORM_WIN32 */
5960
5961         /* libpthreads has its own implementation of sigaction(),
5962          * but it seems to work well with our current exception
5963          * handlers. If not we must call syscall directly instead 
5964          * of sigaction */
5965         
5966         /* catch SIGFPE */
5967         sa.sa_handler = sigfpe_signal_handler;
5968         sigemptyset (&sa.sa_mask);
5969         sa.sa_flags = 0;
5970         //g_assert (syscall (SYS_sigaction, SIGFPE, &sa, NULL) != -1);
5971         g_assert (sigaction (SIGFPE, &sa, NULL) != -1);
5972
5973         /* catch SIGILL */
5974         sa.sa_handler = sigill_signal_handler;
5975         sigemptyset (&sa.sa_mask);
5976         sa.sa_flags = 0;
5977         //g_assert (syscall (SYS_sigaction, SIGILL, &sa, NULL) != -1);
5978         g_assert (sigaction (SIGILL, &sa, NULL) != -1);
5979
5980         /* catch thread abort signal */
5981         sa.sa_handler = sigusr1_signal_handler;
5982         sigemptyset (&sa.sa_mask);
5983         sa.sa_flags = 0;
5984         //g_assert (syscall (SYS_sigaction, SIGILL, &sa, NULL) != -1);
5985         g_assert (sigaction (mono_thread_get_abort_signal (), &sa, NULL) != -1);
5986
5987 #if 1
5988         /* catch SIGSEGV */
5989         sa.sa_handler = sigsegv_signal_handler;
5990         sigemptyset (&sa.sa_mask);
5991         sa.sa_flags = 0;
5992         //g_assert (syscall (SYS_sigaction, SIGSEGV, &sa, NULL) != -1);
5993         g_assert (sigaction (SIGSEGV, &sa, NULL) != -1);
5994 #endif
5995 #endif /* PLATFORM_WIN32 */
5996 }
5997
5998 /* mono_jit_create_remoting_trampoline:
5999  * @method: pointer to the method info
6000  *
6001  * Creates a trampoline which calls the remoting functions. This
6002  * is used in the vtable of transparent proxies.
6003  * 
6004  * Returns: a pointer to the newly created code 
6005  */
6006 static gpointer
6007 mono_jit_create_remoting_trampoline (MonoMethod *method)
6008 {
6009         MonoMethod *nm;
6010         guint8 *addr = NULL;
6011
6012         if (method->signature->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
6013                 nm = mono_marshal_get_remoting_invoke (method);
6014                 addr = mono_compile_method (nm);
6015         } else {
6016                 addr = mono_compile_method (method);
6017         }
6018         return addr;
6019 }
6020
6021 static CRITICAL_SECTION ms;
6022
6023 MonoDomain *
6024 mini_init (const char *filename)
6025 {
6026         MonoDomain *domain;
6027         
6028         metadata_section = &ms;
6029         InitializeCriticalSection (metadata_section);
6030
6031         mono_jit_tls_id = TlsAlloc ();
6032         mono_thread_start_cb (GetCurrentThreadId (), (gpointer)-1, NULL);
6033
6034         mono_burg_init ();
6035
6036         mono_runtime_install_handlers ();
6037
6038         mono_install_compile_method (mono_jit_compile_method);
6039         mono_install_trampoline (mono_arch_create_jit_trampoline);
6040         mono_install_remoting_trampoline (mono_jit_create_remoting_trampoline);
6041         mono_install_runtime_invoke (mono_jit_runtime_invoke);
6042         mono_install_handler (mono_arch_get_throw_exception ());
6043         mono_install_stack_walk (mono_jit_walk_stack);
6044         mono_install_get_config_dir ();
6045
6046         domain = mono_init (filename);
6047         mono_init_icall ();
6048
6049         mono_add_internal_call ("System.Diagnostics.StackFrame::get_frame_info", 
6050                                 ves_icall_get_frame_info);
6051         mono_add_internal_call ("System.Diagnostics.StackTrace::get_trace", 
6052                                 ves_icall_get_trace);
6053         mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers", 
6054                                 mono_runtime_install_handlers);
6055
6056
6057         create_helper_signature ();
6058
6059         mono_arch_register_lowlevel_calls ();
6060         mono_register_jit_icall (mono_profiler_method_enter, "mono_profiler_method_enter", NULL, TRUE);
6061         mono_register_jit_icall (mono_profiler_method_leave, "mono_profiler_method_leave", NULL, TRUE);
6062
6063         mono_register_jit_icall (mono_get_lmf_addr, "mono_get_lmf_addr", helper_sig_ptr_void, TRUE);
6064         mono_register_jit_icall (mono_domain_get, "mono_domain_get", helper_sig_domain_get, TRUE);
6065
6066         /* fixme: we cant hanlde vararg methods this way, because the signature is not constant */
6067         //mono_register_jit_icall (ves_array_element_address, "ves_array_element_address", NULL);
6068         //mono_register_jit_icall (mono_array_new_va, "mono_array_new_va", NULL);
6069
6070         mono_register_jit_icall (mono_arch_get_throw_exception (), "mono_arch_throw_exception", helper_sig_void_obj, TRUE);
6071         mono_register_jit_icall (mono_arch_get_throw_exception_by_name (), "mono_arch_throw_exception_by_name", 
6072                                  helper_sig_void_ptr, TRUE);
6073
6074         /* 
6075          * NOTE, NOTE, NOTE, NOTE:
6076          * when adding emulation for some opcodes, remember to also add a dummy
6077          * rule to the burg files, because we need the arity information to be correct.
6078          */
6079         mono_register_opcode_emulation (OP_LMUL, helper_sig_long_long_long, mono_llmult);
6080         mono_register_opcode_emulation (OP_LMUL_OVF_UN, helper_sig_long_long_long, mono_llmult_ovf_un);
6081         mono_register_opcode_emulation (OP_LMUL_OVF, helper_sig_long_long_long, mono_llmult_ovf);
6082         mono_register_opcode_emulation (OP_LDIV, helper_sig_long_long_long, mono_lldiv);
6083         mono_register_opcode_emulation (OP_LDIV_UN, helper_sig_long_long_long, mono_lldiv_un);
6084         mono_register_opcode_emulation (OP_LREM, helper_sig_long_long_long, mono_llrem);
6085         mono_register_opcode_emulation (OP_LREM_UN, helper_sig_long_long_long, mono_llrem_un);
6086
6087         mono_register_opcode_emulation (OP_LSHL, helper_sig_long_long_int, mono_lshl);
6088         mono_register_opcode_emulation (OP_LSHR, helper_sig_long_long_int, mono_lshr);
6089         mono_register_opcode_emulation (OP_LSHR_UN, helper_sig_long_long_int, mono_lshr_un);
6090
6091         mono_register_opcode_emulation (OP_FCONV_TO_U8, helper_sig_ulong_double, mono_fconv_u8);
6092         mono_register_opcode_emulation (OP_FCONV_TO_U4, helper_sig_uint_double, mono_fconv_u4);
6093         mono_register_opcode_emulation (OP_FCONV_TO_OVF_I8, helper_sig_long_double, mono_fconv_ovf_i8);
6094         mono_register_opcode_emulation (OP_FCONV_TO_OVF_U8, helper_sig_ulong_double, mono_fconv_ovf_u8);
6095
6096 #if SIZEOF_VOID_P == 4
6097         mono_register_opcode_emulation (OP_FCONV_TO_U, helper_sig_uint_double, mono_fconv_u4);
6098 #else
6099 #warning "fixme: add opcode emulation"
6100 #endif
6101
6102         /* other jit icalls */
6103         mono_register_jit_icall (mono_class_static_field_address , "mono_class_static_field_address", 
6104                                  helper_sig_ptr_ptr_ptr, FALSE);
6105         mono_register_jit_icall (mono_ldtoken_wrapper, "mono_ldtoken_wrapper", helper_sig_ptr_ptr_ptr, FALSE);
6106         mono_register_jit_icall (mono_ldstr, "mono_ldstr", helper_sig_ldstr, FALSE);
6107         mono_register_jit_icall (helper_memcpy, "helper_memcpy", helper_sig_memcpy, FALSE);
6108         mono_register_jit_icall (helper_memset, "helper_memset", helper_sig_memset, FALSE);
6109         mono_register_jit_icall (helper_initobj, "helper_initobj", helper_sig_initobj, FALSE);
6110         mono_register_jit_icall (helper_stelem_ref, "helper_stelem_ref", helper_sig_stelem_ref, FALSE);
6111         mono_register_jit_icall (mono_object_new, "mono_object_new", helper_sig_object_new, FALSE);
6112         mono_register_jit_icall (mono_array_new, "mono_array_new", helper_sig_newarr, FALSE);
6113         mono_register_jit_icall (mono_string_to_utf16, "mono_string_to_utf16", helper_sig_ptr_obj, FALSE);
6114         mono_register_jit_icall (mono_string_from_utf16, "mono_string_from_utf16", helper_sig_obj_ptr, FALSE);
6115         mono_register_jit_icall (mono_string_new_wrapper, "mono_string_new_wrapper", helper_sig_obj_ptr, FALSE);
6116         mono_register_jit_icall (mono_string_to_utf8, "mono_string_to_utf8", helper_sig_ptr_obj, FALSE);
6117         mono_register_jit_icall (mono_string_to_bstr, "mono_string_to_bstr", helper_sig_ptr_obj, FALSE);
6118         mono_register_jit_icall (mono_string_to_ansibstr, "mono_string_to_ansibstr", helper_sig_ptr_obj, FALSE);
6119         mono_register_jit_icall (mono_string_builder_to_utf8, "mono_string_builder_to_utf8", helper_sig_ptr_obj, FALSE);
6120         mono_register_jit_icall (mono_array_to_savearray, "mono_array_to_savearray", helper_sig_ptr_obj, FALSE);
6121         mono_register_jit_icall (mono_array_to_lparray, "mono_array_to_lparray", helper_sig_ptr_obj, FALSE);
6122         mono_register_jit_icall (mono_delegate_to_ftnptr, "mono_delegate_to_ftnptr", helper_sig_ptr_obj, FALSE);
6123         mono_register_jit_icall (mono_marshal_string_array, "mono_marshal_string_array", helper_sig_ptr_obj, FALSE);
6124         mono_register_jit_icall (mono_string_utf8_to_builder, "mono_string_utf8_to_builder", helper_sig_void_ptr_ptr, FALSE);
6125         mono_register_jit_icall (mono_marshal_free_array, "mono_marshal_free_array", helper_sig_void_ptr_ptr, FALSE);
6126         mono_register_jit_icall (mono_string_to_byvalstr, "mono_string_to_byvalstr", helper_sig_void_ptr_ptr_ptr, FALSE);
6127         mono_register_jit_icall (mono_string_to_byvalwstr, "mono_string_to_byvalwstr", helper_sig_void_ptr_ptr_ptr, FALSE);
6128         mono_register_jit_icall (g_free, "g_free", helper_sig_void_ptr, FALSE);
6129         mono_register_jit_icall (mono_ldftn, "mono_ldftn", helper_sig_compile, FALSE);
6130         mono_register_jit_icall (mono_ldvirtfn, "mono_ldvirtfn", helper_sig_compile_virt, FALSE);
6131
6132         mono_runtime_init (domain, mono_thread_start_cb,
6133                            mono_thread_attach_cb);
6134
6135         //mono_thread_attach (domain);
6136         return domain;
6137 }
6138
6139 MonoJitStats mono_jit_stats = {0};
6140
6141 static void 
6142 print_jit_stats (void)
6143 {
6144         if (mono_jit_stats.enabled) {
6145                 g_print ("Mono Jit statistics\n");
6146                 g_print ("Compiled methods:       %ld\n", mono_jit_stats.methods_compiled);
6147                 g_print ("Methods from AOT:       %ld\n", mono_jit_stats.methods_aot);
6148                 g_print ("Methods cache lookup:   %ld\n", mono_jit_stats.methods_lookups);
6149                 g_print ("Method trampolines:     %ld\n", mono_jit_stats.method_trampolines);
6150                 g_print ("Basic blocks:           %ld\n", mono_jit_stats.basic_blocks);
6151                 g_print ("Max basic blocks:       %ld\n", mono_jit_stats.max_basic_blocks);
6152                 g_print ("Allocated vars:         %ld\n", mono_jit_stats.allocate_var);
6153                 g_print ("Analyze stack repeat:   %ld\n", mono_jit_stats.analyze_stack_repeat);
6154                 g_print ("Compiled CIL code size: %ld\n", mono_jit_stats.cil_code_size);
6155                 g_print ("Native code size:       %ld\n", mono_jit_stats.native_code_size);
6156                 g_print ("Max code size ratio:    %.2f (%s::%s)\n", mono_jit_stats.max_code_size_ratio/100.0,
6157                                 mono_jit_stats.max_ratio_method->klass->name, mono_jit_stats.max_ratio_method->name);
6158                 g_print ("Biggest method:         %ld (%s::%s)\n", mono_jit_stats.biggest_method_size,
6159                                 mono_jit_stats.biggest_method->klass->name, mono_jit_stats.biggest_method->name);
6160                 g_print ("Code reallocs:          %ld\n", mono_jit_stats.code_reallocs);
6161                 g_print ("Allocated code size:    %ld\n", mono_jit_stats.allocated_code_size);
6162                 g_print ("Inlineable methods:     %ld\n", mono_jit_stats.inlineable_methods);
6163                 g_print ("Inlined methods:        %ld\n", mono_jit_stats.inlined_methods);
6164                 
6165                 g_print ("\nCreated object count:   %ld\n", mono_stats.new_object_count);
6166                 g_print ("Initialized classes:    %ld\n", mono_stats.initialized_class_count);
6167                 g_print ("Used classes:           %ld\n", mono_stats.used_class_count);
6168                 g_print ("Static data size:       %ld\n", mono_stats.class_static_data_size);
6169                 g_print ("VTable data size:       %ld\n", mono_stats.class_vtable_size);
6170         }
6171 }
6172
6173 void
6174 mini_cleanup (MonoDomain *domain)
6175 {
6176         /* 
6177          * mono_runtime_cleanup() and mono_domain_finalize () need to
6178          * be called early since they need the execution engine still
6179          * fully working (mono_domain_finalize may invoke managed finalizers
6180          * and mono_runtime_cleanup will wait for other threads to finish).
6181          */
6182         mono_domain_finalize (domain);
6183
6184         mono_runtime_cleanup (domain);
6185
6186         mono_profiler_shutdown ();
6187
6188         mono_debug_cleanup ();
6189 #ifdef PLATFORM_WIN32
6190         win32_seh_cleanup();
6191 #endif
6192
6193         mono_domain_unload (domain, TRUE);
6194
6195         print_jit_stats ();
6196         DeleteCriticalSection (metadata_section);
6197 }
6198
6199 void
6200 mini_set_defaults (int verbose_level, guint32 opts)
6201 {
6202         mini_verbose = verbose_level;
6203         default_opt = opts;
6204 }
6205