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