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