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