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