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