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