Fri Jul 18 11:28:28 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                 if (n <= sizeof (gpointer) * 5) {
2024                         ins->opcode = OP_MEMSET;
2025                         ins->inst_imm = 0;
2026                         ins->unused = n;
2027                         MONO_ADD_INS (bblock, ins);
2028                         break;
2029                 }
2030                 handle_loaded_temps (cfg, bblock, stack_start, sp);
2031                 NEW_ICONST (cfg, ins, n);
2032                 iargs [0] = dest;
2033                 iargs [1] = ins;
2034                 mono_emit_jit_icall (cfg, bblock, helper_initobj, iargs, ip);
2035                 break;
2036         }
2037 }
2038
2039 #define CODE_IS_STLOC(ip) (((ip) [0] >= CEE_STLOC_0 && (ip) [0] <= CEE_STLOC_3) || ((ip) [0] == CEE_STLOC_S))
2040
2041 static gboolean 
2042 needs_cctor_run (MonoClass *klass, MonoMethod *caller)
2043 {
2044         int i;
2045         MonoMethod *method;
2046         
2047         for (i = 0; i < klass->method.count; ++i) {
2048                 method = klass->methods [i];
2049                 if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) && 
2050                     (strcmp (".cctor", method->name) == 0)) {
2051                         if (caller == method)
2052                                 return FALSE;
2053                         return TRUE;
2054                 }
2055         }
2056         return FALSE;
2057 }
2058
2059 static gboolean
2060 mono_method_check_inlining (MonoCompile *cfg, MonoMethod *method)
2061 {
2062         MonoMethodHeader *header = ((MonoMethodNormal *)method)->header;
2063         MonoMethodSignature *signature = method->signature;
2064         MonoVTable *vtable;
2065         int i;
2066
2067         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2068             (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
2069             (method->iflags & METHOD_IMPL_ATTRIBUTE_NOINLINING) ||
2070             (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) ||
2071             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2072             (method->klass->marshalbyref) ||
2073             !header || header->num_clauses ||
2074             /* fixme: why cant we inline valuetype returns? */
2075             MONO_TYPE_ISSTRUCT (signature->ret))
2076                 return FALSE;
2077
2078         /* its not worth to inline methods with valuetype arguments?? */
2079         for (i = 0; i < signature->param_count; i++) {
2080                 if (MONO_TYPE_ISSTRUCT (signature->params [i])) {
2081                         return FALSE;
2082                 }
2083         }
2084
2085         /* 
2086          * if we can initialize the class of the method right away, we do,
2087          * otherwise we don't allow inlining if the class needs initialization,
2088          * since it would mean inserting a call to mono_runtime_class_init()
2089          * inside the inlined code
2090          */
2091         if (!(cfg->opt & MONO_OPT_SHARED)) {
2092                 vtable = mono_class_vtable (cfg->domain, method->klass);
2093                 if (method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)
2094                         mono_runtime_class_init (vtable);
2095                 else if (!vtable->initialized && needs_cctor_run (method->klass, NULL))
2096                         return FALSE;
2097         } else {
2098                 /* 
2099                  * If we're compiling for shared code
2100                  * the cctor will need to be run at aot method load time, for example,
2101                  * or at the end of the compilation of the inlining method.
2102                  */
2103                 if (needs_cctor_run (method->klass, NULL) && !((method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
2104                         return FALSE;
2105         }
2106         //if (!MONO_TYPE_IS_VOID (signature->ret)) return FALSE;
2107
2108         /* also consider num_locals? */
2109         if (header->code_size < 20)
2110                 return TRUE;
2111
2112         return FALSE;
2113 }
2114
2115 static MonoInst*
2116 mini_get_ldelema_ins (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *cmethod, MonoInst **sp, unsigned char *ip, gboolean is_set)
2117 {
2118         int temp, rank;
2119         MonoInst *addr;
2120         MonoMethodSignature *esig;
2121
2122         rank = cmethod->signature->param_count - (is_set? 1: 0);
2123         /* 
2124          * FIXME: handle TypeMismatch for set or use the slow path
2125          * for that.
2126          */
2127         if (rank == 2 && (cfg->opt & MONO_OPT_INTRINS)) {
2128                 MonoInst *indexes;
2129                 NEW_GROUP (cfg, indexes, sp [1], sp [2]);
2130                 MONO_INST_NEW (cfg, addr, OP_LDELEMA2D);
2131                 addr->inst_left = sp [0];
2132                 addr->inst_right = indexes;
2133                 addr->cil_code = ip;
2134                 addr->type = STACK_MP;
2135                 addr->klass = cmethod->klass;
2136                 return addr;
2137         }
2138         esig = mono_get_element_address_signature (rank);
2139         temp = mono_emit_native_call (cfg, bblock, ves_array_element_address, esig, sp, ip, FALSE);
2140         NEW_TEMPLOAD (cfg, addr, temp);
2141         return addr;
2142 }
2143
2144 static MonoInst*
2145 mini_get_opcode_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
2146 {
2147         int pc, op;
2148         MonoInst *ins;
2149
2150         if (cmethod->klass == mono_defaults.string_class) {
2151                 if (cmethod->name [0] != 'g' || strcmp (cmethod->name, "get_Chars"))
2152                         return NULL;
2153                 op = OP_GETCHR;
2154         } else if (cmethod->klass == mono_defaults.math_class) {
2155                 if (strcmp (cmethod->name, "Sin") == 0)
2156                         op = OP_SIN;
2157                 else if (strcmp (cmethod->name, "Cos") == 0)
2158                         op = OP_COS;
2159                 else if (strcmp (cmethod->name, "Tan") == 0)
2160                         op = OP_TAN;
2161                 else if (strcmp (cmethod->name, "Atan") == 0)
2162                         op = OP_ATAN;
2163                 else if (strcmp (cmethod->name, "Sqrt") == 0)
2164                         op = OP_SQRT;
2165                 else if (strcmp (cmethod->name, "Abs") == 0 && fsig->params [0]->type == MONO_TYPE_R8)
2166                         op = OP_ABS;
2167 #if 0
2168                 /* OP_FREM is not IEEE compatible */
2169                 else if (strcmp (cmethod->name, "IEEERemainder") == 0)
2170                         op = OP_FREM;
2171 #endif
2172                 else
2173                         return NULL;
2174         } else if (cmethod->klass == mono_defaults.array_class) {
2175                 if (strcmp (cmethod->name, "get_Rank") == 0)
2176                         op = OP_ARRAY_RANK;
2177                 else if (strcmp (cmethod->name, "get_Length") == 0)
2178                         op = CEE_LDLEN;
2179                 else
2180                         return NULL;
2181         } else {
2182                 return NULL;
2183         }
2184         pc = fsig->param_count + fsig->hasthis;
2185         MONO_INST_NEW (cfg, ins, op);
2186
2187         if (pc > 0) {
2188                 ins->inst_i0 = args [0];
2189                 if (pc > 1)
2190                         ins->inst_i1 = args [1];
2191         }
2192
2193         return ins;
2194 }
2195
2196 static void
2197 mono_save_args (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, MonoInst **sp, MonoInst **args)
2198 {
2199         MonoInst *store, *temp;
2200         int i;
2201
2202         g_assert (!MONO_TYPE_ISSTRUCT (sig->ret));
2203
2204         if (!sig->hasthis && sig->param_count == 0) 
2205                 return;
2206
2207         if (sig->hasthis) {
2208                 if (sp [0]->opcode == OP_ICONST) {
2209                         *args++ = sp [0];
2210                 } else {
2211                         temp = mono_compile_create_var (cfg, type_from_stack_type (*sp), OP_LOCAL);
2212                         *args++ = temp;
2213                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
2214                         store->cil_code = sp [0]->cil_code;
2215                         MONO_ADD_INS (bblock, store);
2216                 }
2217                 sp++;
2218         }
2219
2220         for (i = 0; i < sig->param_count; ++i) {
2221                 if (sp [0]->opcode == OP_ICONST) {
2222                         *args++ = sp [0];
2223                 } else {
2224                         temp = mono_compile_create_var (cfg, sig->params [i], OP_LOCAL);
2225                         *args++ = temp;
2226                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
2227                         store->cil_code = sp [0]->cil_code;
2228                         if (store->opcode == CEE_STOBJ) {
2229                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
2230                                 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, temp->klass, FALSE, FALSE);
2231                         } else {
2232                                 MONO_ADD_INS (bblock, store);
2233                         } 
2234                 }
2235                 sp++;
2236         }
2237 }
2238
2239 static int
2240 inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoBasicBlock *bblock, MonoInst **sp,
2241                 guchar *ip, guint real_offset, GList *dont_inline, MonoBasicBlock **last_b)
2242 {
2243         MonoInst *ins, *rvar = NULL;
2244         MonoMethodHeader *cheader;
2245         MonoBasicBlock *ebblock, *sbblock;
2246         int i, costs, new_locals_offset;
2247
2248         if (cfg->verbose_level > 2)
2249                 g_print ("INLINE START %p %s\n", cmethod,  mono_method_full_name (cmethod, TRUE));
2250
2251         cheader = ((MonoMethodNormal *)cmethod)->header;
2252
2253         if (!cmethod->inline_info) {
2254                 mono_jit_stats.inlineable_methods++;
2255                 cmethod->inline_info = 1;
2256         }
2257         /* allocate space to store the return value */
2258         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
2259                 rvar =  mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
2260         }
2261
2262         /* allocate local variables */
2263         new_locals_offset = cfg->num_varinfo;
2264         for (i = 0; i < cheader->num_locals; ++i)
2265                 mono_compile_create_var (cfg, cheader->locals [i], OP_LOCAL);
2266         
2267         /* allocate starte and end blocks */
2268         sbblock = NEW_BBLOCK (cfg);
2269         sbblock->block_num = cfg->num_bblocks++;
2270         sbblock->real_offset = real_offset;
2271
2272         ebblock = NEW_BBLOCK (cfg);
2273         ebblock->block_num = cfg->num_bblocks++;
2274         ebblock->real_offset = real_offset;
2275         
2276         costs = mono_method_to_ir (cfg, cmethod, sbblock, ebblock, new_locals_offset, rvar, dont_inline, sp, real_offset, *ip == CEE_CALLVIRT);
2277         
2278         if (costs >= 0 && costs < 60) {
2279                 if (cfg->verbose_level > 2)
2280                         g_print ("INLINE END %s\n", mono_method_full_name (cmethod, TRUE));
2281                 
2282                 mono_jit_stats.inlined_methods++;
2283
2284                 /* always add some code to avoid block split failures */
2285                 MONO_INST_NEW (cfg, ins, CEE_NOP);
2286                 MONO_ADD_INS (bblock, ins);
2287                 ins->cil_code = ip;
2288
2289                 bblock->next_bb = sbblock;
2290                 link_bblock (cfg, bblock, sbblock);
2291
2292                 if (rvar) {
2293                         NEW_TEMPLOAD (cfg, ins, rvar->inst_c0);
2294                         *sp++ = ins;
2295                 }
2296                 *last_b = ebblock;
2297                 return costs + 1;
2298         } else {
2299                 if (cfg->verbose_level > 2)
2300                         g_print ("INLINE ABORTED %s\n", mono_method_full_name (cmethod, TRUE));
2301         }
2302         return 0;
2303 }
2304
2305 /*
2306  * Some of these comments may well be out-of-date.
2307  * Design decisions: we do a single pass over the IL code (and we do bblock 
2308  * splitting/merging in the few cases when it's required: a back jump to an IL
2309  * address that was not already seen as bblock starting point).
2310  * Code is validated as we go (full verification is still better left to metadata/verify.c).
2311  * Complex operations are decomposed in simpler ones right away. We need to let the 
2312  * arch-specific code peek and poke inside this process somehow (except when the 
2313  * optimizations can take advantage of the full semantic info of coarse opcodes).
2314  * All the opcodes of the form opcode.s are 'normalized' to opcode.
2315  * MonoInst->opcode initially is the IL opcode or some simplification of that 
2316  * (OP_LOAD, OP_STORE). The arch-specific code may rearrange it to an arch-specific 
2317  * opcode with value bigger than OP_LAST.
2318  * At this point the IR can be handed over to an interpreter, a dumb code generator
2319  * or to the optimizing code generator that will translate it to SSA form.
2320  *
2321  * Profiling directed optimizations.
2322  * We may compile by default with few or no optimizations and instrument the code
2323  * or the user may indicate what methods to optimize the most either in a config file
2324  * or through repeated runs where the compiler applies offline the optimizations to 
2325  * each method and then decides if it was worth it.
2326  *
2327  * TODO:
2328  * * consider using an array instead of an hash table (bb_hash)
2329  */
2330
2331 #define CHECK_TYPE(ins) if (!(ins)->type) goto unverified
2332 #define CHECK_STACK(num) if ((sp - stack_start) < (num)) goto unverified
2333 #define CHECK_STACK_OVF(num) if (((sp - stack_start) + (num)) > header->max_stack) goto unverified
2334
2335 /* offset from br.s -> br like opcodes */
2336 #define BIG_BRANCH_OFFSET 13
2337
2338 static int
2339 get_basic_blocks (MonoCompile *cfg, GHashTable *bbhash, MonoMethodHeader* header, guint real_offset, unsigned char *start, unsigned char *end)
2340 {
2341         unsigned char *ip = start;
2342         unsigned char *target;
2343         int i;
2344         guint cli_addr;
2345         MonoBasicBlock *bblock;
2346         const MonoOpcode *opcode;
2347
2348         while (ip < end) {
2349                 cli_addr = ip - start;
2350                 i = mono_opcode_value ((const guint8 **)&ip);
2351                 opcode = &mono_opcodes [i];
2352                 switch (opcode->argument) {
2353                 case MonoInlineNone:
2354                         ip++; 
2355                         break;
2356                 case MonoInlineString:
2357                 case MonoInlineType:
2358                 case MonoInlineField:
2359                 case MonoInlineMethod:
2360                 case MonoInlineTok:
2361                 case MonoInlineSig:
2362                 case MonoShortInlineR:
2363                 case MonoInlineI:
2364                         ip += 5;
2365                         break;
2366                 case MonoInlineVar:
2367                         ip += 3;
2368                         break;
2369                 case MonoShortInlineVar:
2370                 case MonoShortInlineI:
2371                         ip += 2;
2372                         break;
2373                 case MonoShortInlineBrTarget:
2374                         target = start + cli_addr + 2 + (signed char)ip [1];
2375                         GET_BBLOCK (cfg, bbhash, bblock, target);
2376                         ip += 2;
2377                         break;
2378                 case MonoInlineBrTarget:
2379                         target = start + cli_addr + 5 + (gint32)read32 (ip + 1);
2380                         GET_BBLOCK (cfg, bbhash, bblock, target);
2381                         ip += 5;
2382                         break;
2383                 case MonoInlineSwitch: {
2384                         guint32 n = read32 (ip + 1);
2385                         guint32 j;
2386                         ip += 5;
2387                         cli_addr += 5 + 4 * n;
2388                         target = start + cli_addr;
2389                         GET_BBLOCK (cfg, bbhash, bblock, target);
2390                         
2391                         for (j = 0; j < n; ++j) {
2392                                 target = start + cli_addr + (gint32)read32 (ip);
2393                                 GET_BBLOCK (cfg, bbhash, bblock, target);
2394                                 ip += 4;
2395                         }
2396                         break;
2397                 }
2398                 case MonoInlineR:
2399                 case MonoInlineI8:
2400                         ip += 9;
2401                         break;
2402                 default:
2403                         g_assert_not_reached ();
2404                 }
2405         }
2406         return 0;
2407 unverified:
2408         return 1;
2409 }
2410
2411 /*
2412  * mono_method_to_ir: translates IL into basic blocks containing trees
2413  */
2414 static int
2415 mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
2416                    int locals_offset, MonoInst *return_var, GList *dont_inline, MonoInst **inline_args, 
2417                    guint inline_offset, gboolean is_virtual_call)
2418 {
2419         MonoInst *zero_int32, *zero_int64, *zero_ptr, *zero_obj, *zero_r8;
2420         MonoInst *ins, **sp, **stack_start;
2421         MonoBasicBlock *bblock, *tblock = NULL, *init_localsbb = NULL;
2422         GHashTable *bbhash;
2423         MonoMethod *cmethod;
2424         MonoInst **arg_array;
2425         MonoMethodHeader *header;
2426         MonoImage *image;
2427         guint32 token, ins_flag;
2428         MonoClass *klass;
2429         unsigned char *ip, *end, *target;
2430         static double r8_0 = 0.0;
2431         MonoMethodSignature *sig;
2432         MonoType **param_types;
2433         GList *bb_recheck = NULL, *tmp;
2434         int i, n, start_new_bblock, align;
2435         int num_calls = 0, inline_costs = 0;
2436         int *filter_lengths = NULL;
2437         int breakpoint_id = 0;
2438         guint real_offset;
2439
2440         image = method->klass->image;
2441         header = ((MonoMethodNormal *)method)->header;
2442         sig = method->signature;
2443         ip = (unsigned char*)header->code;
2444         end = ip + header->code_size;
2445         mono_jit_stats.cil_code_size += header->code_size;
2446
2447         if (cfg->method == method) {
2448                 real_offset = 0;
2449                 bbhash = cfg->bb_hash;
2450         } else {
2451                 real_offset = inline_offset;
2452                 bbhash = g_hash_table_new (g_direct_hash, NULL);
2453         }
2454
2455         if (cfg->prof_options & MONO_PROFILE_INS_COVERAGE)
2456                 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, header->code_size);
2457
2458         dont_inline = g_list_prepend (dont_inline, method);
2459         if (cfg->method == method) {
2460
2461                 /* ENTRY BLOCK */
2462                 cfg->bb_entry = start_bblock = NEW_BBLOCK (cfg);
2463                 start_bblock->cil_code = NULL;
2464                 start_bblock->cil_length = 0;
2465                 start_bblock->block_num = cfg->num_bblocks++;
2466
2467                 /* EXIT BLOCK */
2468                 cfg->bb_exit = end_bblock = NEW_BBLOCK (cfg);
2469                 end_bblock->cil_code = NULL;
2470                 end_bblock->cil_length = 0;
2471                 end_bblock->block_num = cfg->num_bblocks++;
2472                 g_assert (cfg->num_bblocks == 2);
2473
2474                 arg_array = alloca (sizeof (MonoInst *) * (sig->hasthis + sig->param_count));
2475                 for (i = sig->hasthis + sig->param_count - 1; i >= 0; i--)
2476                         arg_array [i] = cfg->varinfo [i];
2477
2478                 if (mono_compile_aot) 
2479                         cfg->opt |= MONO_OPT_SHARED;
2480
2481                 if (header->num_clauses) {
2482                         int size = sizeof (int) * header->num_clauses;
2483                         filter_lengths = alloca (size);
2484                         memset (filter_lengths, 0, size);
2485
2486                         cfg->spvar = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
2487                         /* prevent it from being register allocated */
2488                         cfg->spvar->flags |= MONO_INST_INDIRECT;
2489                 }
2490                 /* handle exception clauses */
2491                 for (i = 0; i < header->num_clauses; ++i) {
2492                         //unsigned char *p = ip;
2493                         MonoExceptionClause *clause = &header->clauses [i];
2494                         GET_BBLOCK (cfg, bbhash, tblock, ip + clause->try_offset);
2495                         tblock->real_offset = clause->try_offset;
2496                         GET_BBLOCK (cfg, bbhash, tblock, ip + clause->handler_offset);
2497                         tblock->real_offset = clause->handler_offset;
2498
2499                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY ||
2500                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
2501                                 MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
2502                                 MONO_ADD_INS (tblock, ins);
2503                         }
2504
2505                         /*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);
2506                           while (p < end) {
2507                           g_print ("%s", mono_disasm_code_one (NULL, method, p, &p));
2508                           }*/
2509                         /* catch and filter blocks get the exception object on the stack */
2510                         if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE ||
2511                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
2512                                 /* mostly like handle_stack_args (), but just sets the input args */
2513                                 /* g_print ("handling clause at IL_%04x\n", clause->handler_offset); */
2514                                 if (!cfg->exvar) {
2515                                         cfg->exvar = mono_compile_create_var (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL);
2516                                         /* prevent it from being register allocated */
2517                                         cfg->exvar->flags |= MONO_INST_INDIRECT;
2518                                 }
2519                                 tblock->in_scount = 1;
2520                                 tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
2521                                 tblock->in_stack [0] = cfg->exvar;
2522                                 
2523                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
2524                                         GET_BBLOCK (cfg, bbhash, tblock, ip + clause->token_or_filter);
2525                                         tblock->real_offset = clause->token_or_filter;
2526                                         tblock->in_scount = 1;
2527                                         tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
2528                                         tblock->in_stack [0] = cfg->exvar;
2529                                         MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
2530                                         MONO_ADD_INS (tblock, ins);
2531                                 }
2532                         }
2533                 }
2534
2535         } else {
2536                 arg_array = alloca (sizeof (MonoInst *) * (sig->hasthis + sig->param_count));
2537                 mono_save_args (cfg, start_bblock, sig, inline_args, arg_array);
2538         }
2539
2540         /* FIRST CODE BLOCK */
2541         bblock = NEW_BBLOCK (cfg);
2542         bblock->cil_code = ip;
2543
2544         ADD_BBLOCK (cfg, bbhash, bblock);
2545
2546         if (cfg->method == method) {
2547                 breakpoint_id = mono_debugger_method_has_breakpoint (method);
2548                 if (breakpoint_id && (mono_debug_format != MONO_DEBUG_FORMAT_DEBUGGER)) {
2549                         MONO_INST_NEW (cfg, ins, CEE_BREAK);
2550                         MONO_ADD_INS (bblock, ins);
2551                 }
2552         }
2553         
2554         if ((header->init_locals || (cfg->method == method && (cfg->opt & MONO_OPT_SHARED)))) {
2555                 /* we use a separate basic block for the initialization code */
2556                 cfg->bb_init = init_localsbb = NEW_BBLOCK (cfg);
2557                 init_localsbb->real_offset = real_offset;
2558                 start_bblock->next_bb = init_localsbb;
2559                 init_localsbb->next_bb = bblock;
2560                 link_bblock (cfg, start_bblock, init_localsbb);
2561                 link_bblock (cfg, init_localsbb, bblock);
2562                 init_localsbb->block_num = cfg->num_bblocks++;
2563         } else {
2564                 start_bblock->next_bb = bblock;
2565                 link_bblock (cfg, start_bblock, bblock);
2566         }
2567
2568         if (get_basic_blocks (cfg, bbhash, header, real_offset, ip, end))
2569                 goto unverified;
2570
2571         mono_debug_init_method (cfg, bblock, breakpoint_id);
2572
2573         param_types = mono_mempool_alloc (cfg->mempool, sizeof (MonoType*) * (sig->hasthis + sig->param_count));
2574         if (sig->hasthis)
2575                 param_types [0] = method->klass->valuetype?&method->klass->this_arg:&method->klass->byval_arg;
2576         for (n = 0; n < sig->param_count; ++n)
2577                 param_types [n + sig->hasthis] = sig->params [n];
2578
2579         /* do this somewhere outside - not here */
2580         NEW_ICONST (cfg, zero_int32, 0);
2581         NEW_ICONST (cfg, zero_int64, 0);
2582         zero_int64->type = STACK_I8;
2583         NEW_PCONST (cfg, zero_ptr, 0);
2584         NEW_PCONST (cfg, zero_obj, 0);
2585         zero_obj->type = STACK_OBJ;
2586
2587         MONO_INST_NEW (cfg, zero_r8, OP_R8CONST);
2588         zero_r8->type = STACK_R8;
2589         zero_r8->inst_p0 = &r8_0;
2590
2591         /* add a check for this != NULL to inlined methods */
2592         if (is_virtual_call) {
2593                 MONO_INST_NEW (cfg, ins, OP_CHECK_THIS);
2594                 NEW_ARGLOAD (cfg, ins->inst_left, 0);
2595                 ins->cil_code = ip;
2596                 MONO_ADD_INS (bblock, ins);
2597         }
2598
2599         /* we use a spare stack slot in SWITCH and NEWOBJ and others */
2600         stack_start = sp = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (header->max_stack + 1));
2601
2602         ins_flag = 0;
2603         start_new_bblock = 0;
2604         while (ip < end) {
2605
2606                 if (cfg->method == method)
2607                         real_offset = ip - header->code;
2608                 else
2609                         real_offset = inline_offset;
2610
2611                 if (start_new_bblock) {
2612                         bblock->cil_length = ip - bblock->cil_code;
2613                         if (start_new_bblock == 2) {
2614                                 g_assert (ip == tblock->cil_code);
2615                         } else {
2616                                 GET_BBLOCK (cfg, bbhash, tblock, ip);
2617                         }
2618                         bblock->next_bb = tblock;
2619                         bblock = tblock;
2620                         start_new_bblock = 0;
2621                         for (i = 0; i < bblock->in_scount; ++i) {
2622                                 NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
2623                                 *sp++ = ins;
2624                         }
2625                 } else {
2626                         if ((tblock = g_hash_table_lookup (bbhash, ip)) && (tblock != bblock)) {
2627                                 link_bblock (cfg, bblock, tblock);
2628                                 if (sp != stack_start) {
2629                                         handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
2630                                         sp = stack_start;
2631                                 }
2632                                 bblock->next_bb = tblock;
2633                                 bblock = tblock;
2634                                 for (i = 0; i < bblock->in_scount; ++i) {
2635                                         NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
2636                                         *sp++ = ins;
2637                                 }
2638                         }
2639                 }
2640
2641                 if (cfg->coverage_info) {
2642                         MonoInst *store, *one;
2643                         guint32 cil_offset = ip - header->code;
2644                         cfg->coverage_info->data [cil_offset].cil_code = ip;
2645
2646                         /* TODO: Use an increment here */
2647                         NEW_ICONST (cfg, one, 1);
2648                         one->cil_code = ip;
2649
2650                         NEW_PCONST (cfg, ins, &(cfg->coverage_info->data [cil_offset].count));
2651                         ins->cil_code = ip;
2652
2653                         MONO_INST_NEW (cfg, store, CEE_STIND_I);
2654                         store->cil_code = ip;
2655                         store->inst_left = ins;
2656                         store->inst_right = one;
2657
2658                         MONO_ADD_INS (bblock, store);
2659                 }
2660
2661                 if (cfg->verbose_level > 3)
2662                         g_print ("converting (in B%d: stack: %d) %s", bblock->block_num, sp-stack_start, mono_disasm_code_one (NULL, method, ip, NULL));
2663
2664                 switch (*ip) {
2665                 case CEE_NOP:
2666                         ++ip;
2667                         break;
2668                 case CEE_BREAK:
2669                         MONO_INST_NEW (cfg, ins, CEE_BREAK);
2670                         ins->cil_code = ip++;
2671                         MONO_ADD_INS (bblock, ins);
2672                         break;
2673                 case CEE_LDARG_0:
2674                 case CEE_LDARG_1:
2675                 case CEE_LDARG_2:
2676                 case CEE_LDARG_3:
2677                         CHECK_STACK_OVF (1);
2678                         n = (*ip)-CEE_LDARG_0;
2679                         NEW_ARGLOAD (cfg, ins, n);
2680                         ins->cil_code = ip++;
2681                         *sp++ = ins;
2682                         break;
2683                 case CEE_LDLOC_0:
2684                 case CEE_LDLOC_1:
2685                 case CEE_LDLOC_2:
2686                 case CEE_LDLOC_3:
2687                         CHECK_STACK_OVF (1);
2688                         n = (*ip)-CEE_LDLOC_0;
2689                         NEW_LOCLOAD (cfg, ins, n);
2690                         ins->cil_code = ip++;
2691                         *sp++ = ins;
2692                         break;
2693                 case CEE_STLOC_0:
2694                 case CEE_STLOC_1:
2695                 case CEE_STLOC_2:
2696                 case CEE_STLOC_3:
2697                         CHECK_STACK (1);
2698                         n = (*ip)-CEE_STLOC_0;
2699                         --sp;
2700                         handle_loaded_temps (cfg, bblock, stack_start, sp);
2701                         NEW_LOCSTORE (cfg, ins, n, *sp);
2702                         ins->cil_code = ip;
2703                         if (ins->opcode == CEE_STOBJ) {
2704                                 NEW_LOCLOADA (cfg, ins, n);
2705                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
2706                         } else
2707                                 MONO_ADD_INS (bblock, ins);
2708                         ++ip;
2709                         inline_costs += 1;
2710                         break;
2711                 case CEE_LDARG_S:
2712                         CHECK_STACK_OVF (1);
2713                         NEW_ARGLOAD (cfg, ins, ip [1]);
2714                         ins->cil_code = ip;
2715                         *sp++ = ins;
2716                         ip += 2;
2717                         break;
2718                 case CEE_LDARGA_S:
2719                         CHECK_STACK_OVF (1);
2720                         NEW_ARGLOADA (cfg, ins, ip [1]);
2721                         ins->cil_code = ip;
2722                         *sp++ = ins;
2723                         ip += 2;
2724                         break;
2725                 case CEE_STARG_S:
2726                         CHECK_STACK (1);
2727                         --sp;
2728                         NEW_ARGSTORE (cfg, ins, ip [1], *sp);
2729                         handle_loaded_temps (cfg, bblock, stack_start, sp);
2730                         ins->cil_code = ip;
2731                         if (ins->opcode == CEE_STOBJ) {
2732                                 NEW_ARGLOADA (cfg, ins, ip [1]);
2733                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
2734                         } else
2735                                 MONO_ADD_INS (bblock, ins);
2736                         ip += 2;
2737                         break;
2738                 case CEE_LDLOC_S:
2739                         CHECK_STACK_OVF (1);
2740                         NEW_LOCLOAD (cfg, ins, ip [1]);
2741                         ins->cil_code = ip;
2742                         *sp++ = ins;
2743                         ip += 2;
2744                         break;
2745                 case CEE_LDLOCA_S:
2746                         CHECK_STACK_OVF (1);
2747                         NEW_LOCLOADA (cfg, ins, ip [1]);
2748                         ins->cil_code = ip;
2749                         *sp++ = ins;
2750                         ip += 2;
2751                         break;
2752                 case CEE_STLOC_S:
2753                         CHECK_STACK (1);
2754                         --sp;
2755                         handle_loaded_temps (cfg, bblock, stack_start, sp);
2756                         NEW_LOCSTORE (cfg, ins, ip [1], *sp);
2757                         ins->cil_code = ip;
2758                         if (ins->opcode == CEE_STOBJ) {
2759                                 NEW_LOCLOADA (cfg, ins, ip [1]);
2760                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
2761                         } else
2762                                 MONO_ADD_INS (bblock, ins);
2763                         ip += 2;
2764                         inline_costs += 1;
2765                         break;
2766                 case CEE_LDNULL:
2767                         CHECK_STACK_OVF (1);
2768                         NEW_PCONST (cfg, ins, NULL);
2769                         ins->cil_code = ip;
2770                         ins->type = STACK_OBJ;
2771                         ++ip;
2772                         *sp++ = ins;
2773                         break;
2774                 case CEE_LDC_I4_M1:
2775                         CHECK_STACK_OVF (1);
2776                         NEW_ICONST (cfg, ins, -1);
2777                         ins->cil_code = ip;
2778                         ++ip;
2779                         *sp++ = ins;
2780                         break;
2781                 case CEE_LDC_I4_0:
2782                 case CEE_LDC_I4_1:
2783                 case CEE_LDC_I4_2:
2784                 case CEE_LDC_I4_3:
2785                 case CEE_LDC_I4_4:
2786                 case CEE_LDC_I4_5:
2787                 case CEE_LDC_I4_6:
2788                 case CEE_LDC_I4_7:
2789                 case CEE_LDC_I4_8:
2790                         CHECK_STACK_OVF (1);
2791                         NEW_ICONST (cfg, ins, (*ip) - CEE_LDC_I4_0);
2792                         ins->cil_code = ip;
2793                         ++ip;
2794                         *sp++ = ins;
2795                         break;
2796                 case CEE_LDC_I4_S:
2797                         CHECK_STACK_OVF (1);
2798                         ++ip;
2799                         NEW_ICONST (cfg, ins, *((signed char*)ip));
2800                         ins->cil_code = ip;
2801                         ++ip;
2802                         *sp++ = ins;
2803                         break;
2804                 case CEE_LDC_I4:
2805                         CHECK_STACK_OVF (1);
2806                         NEW_ICONST (cfg, ins, (gint32)read32 (ip + 1));
2807                         ins->cil_code = ip;
2808                         ip += 5;
2809                         *sp++ = ins;
2810                         break;
2811                 case CEE_LDC_I8:
2812                         CHECK_STACK_OVF (1);
2813                         MONO_INST_NEW (cfg, ins, OP_I8CONST);
2814                         ins->cil_code = ip;
2815                         ins->type = STACK_I8;
2816                         ++ip;
2817                         ins->inst_l = (gint64)read64 (ip);
2818                         ip += 8;
2819                         *sp++ = ins;
2820                         break;
2821                 case CEE_LDC_R4: {
2822                         float *f = g_malloc (sizeof (float));
2823                         CHECK_STACK_OVF (1);
2824                         MONO_INST_NEW (cfg, ins, OP_R4CONST);
2825                         ins->type = STACK_R8;
2826                         ++ip;
2827                         readr4 (ip, f);
2828                         ins->inst_p0 = f;
2829                         ip += 4;
2830                         *sp++ = ins;                    
2831                         break;
2832                 }
2833                 case CEE_LDC_R8: {
2834                         double *d = g_malloc (sizeof (double));
2835                         CHECK_STACK_OVF (1);
2836                         MONO_INST_NEW (cfg, ins, OP_R8CONST);
2837                         ins->type = STACK_R8;
2838                         ++ip;
2839                         readr8 (ip, d);
2840                         ins->inst_p0 = d;
2841                         ip += 8;
2842                         *sp++ = ins;                    
2843                         break;
2844                 }
2845                 case CEE_DUP: {
2846                         MonoInst *temp, *store;
2847                         CHECK_STACK (1);
2848                         CHECK_STACK_OVF (1);
2849                         sp--;
2850                         ins = *sp;
2851                 
2852                         /* 
2853                          * small optimization: if the loaded value was from a local already,
2854                          * just load it twice.
2855                          */
2856                         if (ins->ssa_op == MONO_SSA_LOAD && 
2857                             (ins->inst_i0->opcode == OP_LOCAL || ins->inst_i0->opcode == OP_ARG)) {
2858                                 sp++;
2859                                 MONO_INST_NEW (cfg, temp, 0);
2860                                 *temp = *ins;
2861                                 temp->cil_code = ip;
2862                                 *sp++ = temp;
2863                         } else {
2864                                 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
2865                                 temp->cil_code = ip;
2866                                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2867                                 store->cil_code = ip;
2868                                 MONO_ADD_INS (bblock, store);
2869                                 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
2870                                 *sp++ = ins;
2871                                 ins->cil_code = ip;
2872                                 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
2873                                 *sp++ = ins;
2874                                 ins->cil_code = ip;
2875                         }
2876                         ++ip;
2877                         inline_costs += 2;
2878                         break;
2879                 }
2880                 case CEE_POP:
2881                         CHECK_STACK (1);
2882                         MONO_INST_NEW (cfg, ins, CEE_POP);
2883                         MONO_ADD_INS (bblock, ins);
2884                         ins->cil_code = ip++;
2885                         --sp;
2886                         ins->inst_i0 = *sp;
2887                         break;
2888                 case CEE_JMP:
2889                         if (stack_start != sp)
2890                                 goto unverified;
2891                         MONO_INST_NEW (cfg, ins, CEE_JMP);
2892                         token = read32 (ip + 1);
2893                         /* FIXME: check the signature matches */
2894                         cmethod = mono_get_method (image, token, NULL);
2895                         ins->inst_p0 = cmethod;
2896                         MONO_ADD_INS (bblock, ins);
2897                         ip += 5;
2898                         start_new_bblock = 1;
2899                         break;
2900                 case CEE_CALLI:
2901                 case CEE_CALL:
2902                 case CEE_CALLVIRT: {
2903                         MonoInst *addr = NULL;
2904                         MonoMethodSignature *fsig = NULL;
2905                         int temp, array_rank = 0;
2906                         int virtual = *ip == CEE_CALLVIRT;
2907
2908                         token = read32 (ip + 1);
2909
2910                         if (*ip == CEE_CALLI) {
2911                                 cmethod = NULL;
2912                                 CHECK_STACK (1);
2913                                 --sp;
2914                                 addr = *sp;
2915                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
2916                                         fsig = (MonoMethodSignature *)mono_method_get_wrapper_data (method, token);
2917                                 else
2918                                         fsig = mono_metadata_parse_signature (image, token);
2919
2920                                 n = fsig->param_count + fsig->hasthis;
2921
2922                         } else {
2923                                 if (method->wrapper_type != MONO_WRAPPER_NONE) {
2924                                         cmethod =  (MonoMethod *)mono_method_get_wrapper_data (method, token);
2925                                 } else {
2926                                         cmethod = mono_get_method (image, token, NULL);
2927                                 }
2928
2929                                 if (!cmethod->klass->inited)
2930                                         mono_class_init (cmethod->klass);
2931
2932                                 if (cmethod->signature->pinvoke) {
2933 #ifdef MONO_USE_EXC_TABLES
2934                                         if (mono_method_blittable (cmethod)) {
2935                                                 fsig = cmethod->signature;
2936                                         } else {
2937 #endif
2938                                                 MonoMethod *wrapper = mono_marshal_get_native_wrapper (cmethod);
2939                                                 fsig = wrapper->signature;
2940 #ifdef MONO_USE_EXC_TABLES
2941                                         }
2942 #endif
2943                                 } else {
2944                                         fsig = mono_method_get_signature (cmethod, image, token);
2945                                 }
2946
2947                                 n = fsig->param_count + fsig->hasthis;
2948
2949                                 if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL &&
2950                                     cmethod->klass->parent == mono_defaults.array_class) {
2951                                         array_rank = cmethod->klass->rank;
2952                                 }
2953
2954                                 if (cmethod->string_ctor)
2955                                         g_assert_not_reached ();
2956
2957                         }
2958
2959                         CHECK_STACK (n);
2960
2961                         //g_assert (!virtual || fsig->hasthis);
2962
2963                         sp -= n;
2964
2965                         if (*ip != CEE_CALLI && check_call_signature (cfg, fsig, sp))
2966                                 goto unverified;
2967
2968                         if ((ins_flag & MONO_INST_TAILCALL) && cmethod && (*ip == CEE_CALL)) {
2969                                 int i;
2970                                 for (i = 0; i < n; ++i) {
2971                                         NEW_ARGSTORE (cfg, ins, i, sp [i]);
2972                                         ins->cil_code = ip;
2973                                         MONO_ADD_INS (bblock, ins);
2974                                 }
2975                                 MONO_INST_NEW (cfg, ins, CEE_JMP);
2976                                 ins->cil_code = ip;
2977                                 ins->inst_p0 = cmethod;
2978                                 MONO_ADD_INS (bblock, ins);
2979                                 start_new_bblock = 1;
2980                                 /* skip CEE_RET as well */
2981                                 ip += 6;
2982                                 ins_flag = 0;
2983                                 break;
2984                         }
2985                         if (cmethod && (cfg->opt & MONO_OPT_INTRINS) && (ins = mini_get_opcode_for_method (cfg, cmethod, fsig, sp))) {
2986                                 ins->cil_code = ip;
2987
2988                                 if (MONO_TYPE_IS_VOID (fsig->ret)) {
2989                                         MONO_ADD_INS (bblock, ins);
2990                                 } else {
2991                                         type_to_eval_stack_type (fsig->ret, ins);
2992                                         *sp = ins;
2993                                         sp++;
2994                                 }
2995
2996                                 ip += 5;
2997                                 break;
2998                         }
2999
3000                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3001
3002                         if ((cfg->opt & MONO_OPT_INLINE) && cmethod &&
3003                             (!virtual || !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) || (cmethod->flags & METHOD_ATTRIBUTE_FINAL)) && 
3004                             mono_method_check_inlining (cfg, cmethod) &&
3005                             !g_list_find (dont_inline, cmethod)) {
3006                                 int costs;
3007                                 MonoBasicBlock *ebblock;
3008                                 
3009                                 if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock))) {
3010                                         ip += 5;
3011                                         real_offset += 5;
3012
3013                                         GET_BBLOCK (cfg, bbhash, bblock, ip);
3014                                         ebblock->next_bb = bblock;
3015                                         link_bblock (cfg, ebblock, bblock);
3016
3017                                         if (!MONO_TYPE_IS_VOID (fsig->ret))
3018                                                 sp++;
3019
3020                                         /* indicates start of a new block, and triggers a load of all 
3021                                            stack arguments at bb boundarie */
3022                                         bblock = ebblock;
3023
3024                                         inline_costs += costs;
3025                                         break;
3026                                 }
3027                         }
3028                         
3029                         inline_costs += 10 * num_calls++;
3030
3031                         /* tail recursion elimination */
3032                         if ((cfg->opt & MONO_OPT_TAILC) && *ip == CEE_CALL && cmethod == cfg->method && ip [5] == CEE_RET) {
3033                                 gboolean has_vtargs = FALSE;
3034                                 int i;
3035                                 
3036                                 /* keep it simple */
3037                                 for (i =  fsig->param_count - 1; i >= 0; i--) {
3038                                         if (MONO_TYPE_ISSTRUCT (cmethod->signature->params [i])) 
3039                                                 has_vtargs = TRUE;
3040                                 }
3041
3042                                 if (!has_vtargs) {
3043                                         for (i = 0; i < n; ++i) {
3044                                                 NEW_ARGSTORE (cfg, ins, i, sp [i]);
3045                                                 ins->cil_code = ip;
3046                                                 MONO_ADD_INS (bblock, ins);
3047                                         }
3048                                         MONO_INST_NEW (cfg, ins, CEE_BR);
3049                                         ins->cil_code = ip;
3050                                         MONO_ADD_INS (bblock, ins);
3051                                         tblock = start_bblock->out_bb [0];
3052                                         link_bblock (cfg, bblock, tblock);
3053                                         ins->inst_target_bb = tblock;
3054                                         start_new_bblock = 1;
3055                                         ip += 5;
3056                                         
3057                                         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
3058                                                 /* just create a dummy - the value is never used */
3059                                                 ins = mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
3060                                                 NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
3061                                                 sp++;
3062                                         }
3063
3064                                         break;
3065                                 }
3066                         }
3067
3068                         if (*ip == CEE_CALLI) {
3069
3070                                 if ((temp = mono_emit_calli (cfg, bblock, fsig, sp, addr, ip)) != -1) {
3071                                         NEW_TEMPLOAD (cfg, *sp, temp);
3072                                         sp++;
3073                                 }
3074                                         
3075                         } else if (array_rank) {
3076                                 MonoInst *addr;
3077
3078                                 if (strcmp (cmethod->name, "Set") == 0) { /* array Set */ 
3079                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, TRUE);
3080                                         NEW_INDSTORE (cfg, ins, addr, sp [fsig->param_count], fsig->params [fsig->param_count - 1]);
3081                                         ins->cil_code = ip;
3082                                         if (ins->opcode == CEE_STOBJ) {
3083                                                 handle_stobj (cfg, bblock, addr, sp [fsig->param_count], ip, mono_class_from_mono_type (fsig->params [fsig->param_count-1]), FALSE, FALSE);
3084                                         } else {
3085                                                 MONO_ADD_INS (bblock, ins);
3086                                         }
3087
3088                                 } else if (strcmp (cmethod->name, "Get") == 0) { /* array Get */
3089                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
3090                                         NEW_INDLOAD (cfg, ins, addr, fsig->ret);
3091                                         ins->cil_code = ip;
3092
3093                                         *sp++ = ins;
3094                                 } else if (strcmp (cmethod->name, "Address") == 0) { /* array Address */
3095                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
3096                                         *sp++ = addr;
3097                                 } else {
3098                                         g_assert_not_reached ();
3099                                 }
3100
3101                         } else {
3102                                 if (0 && CODE_IS_STLOC (ip + 5) && (!MONO_TYPE_ISSTRUCT (fsig->ret)) && (!MONO_TYPE_IS_VOID (fsig->ret) || cmethod->string_ctor)) {
3103                                         /* no need to spill */
3104                                         ins = (MonoInst*)mono_emit_method_call (cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL);
3105                                         *sp++ = ins;
3106                                 } else {
3107                                         if ((temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL)) != -1) {
3108                                                 NEW_TEMPLOAD (cfg, *sp, temp);
3109                                                 sp++;
3110                                         }
3111                                 }
3112                         }
3113
3114                         ip += 5;
3115                         break;
3116                 }
3117                 case CEE_RET:
3118                         if (cfg->method != method) {
3119                                 /* return from inlined methode */
3120                                 if (return_var) {
3121                                         MonoInst *store;
3122                                         CHECK_STACK (1);
3123                                         --sp;
3124                                         //g_assert (returnvar != -1);
3125                                         NEW_TEMPSTORE (cfg, store, return_var->inst_c0, *sp);
3126                                         store->cil_code = sp [0]->cil_code;
3127                                         if (store->opcode == CEE_STOBJ) {
3128                                                 g_assert_not_reached ();
3129                                                 NEW_TEMPLOADA (cfg, store, return_var->inst_c0);
3130                                                 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, return_var->klass, FALSE, FALSE);
3131                                         } else
3132                                                 MONO_ADD_INS (bblock, store);
3133                                 } 
3134                         } else {
3135                                 if (cfg->ret) {
3136                                         g_assert (!return_var);
3137                                         CHECK_STACK (1);
3138                                         --sp;
3139                                         MONO_INST_NEW (cfg, ins, CEE_NOP);
3140                                         ins->opcode = mono_type_to_stind (method->signature->ret);
3141                                         if (ins->opcode == CEE_STOBJ) {
3142                                                 NEW_RETLOADA (cfg, ins);
3143                                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
3144                                         } else {
3145                                                 ins->opcode = OP_SETRET;
3146                                                 ins->cil_code = ip;
3147                                                 ins->inst_i0 = *sp;;
3148                                                 ins->inst_i1 = NULL;
3149                                                 MONO_ADD_INS (bblock, ins);
3150                                         }
3151                                 }
3152                         }
3153                         if (sp != stack_start)
3154                                 goto unverified;
3155                         MONO_INST_NEW (cfg, ins, CEE_BR);
3156                         ins->cil_code = ip++;
3157                         ins->inst_target_bb = end_bblock;
3158                         MONO_ADD_INS (bblock, ins);
3159                         link_bblock (cfg, bblock, end_bblock);
3160                         start_new_bblock = 1;
3161                         break;
3162                 case CEE_BR_S:
3163                         MONO_INST_NEW (cfg, ins, CEE_BR);
3164                         ins->cil_code = ip++;
3165                         MONO_ADD_INS (bblock, ins);
3166                         target = ip + 1 + (signed char)(*ip);
3167                         ++ip;
3168                         GET_BBLOCK (cfg, bbhash, tblock, target);
3169                         link_bblock (cfg, bblock, tblock);
3170                         CHECK_BBLOCK (target, ip, tblock);
3171                         ins->inst_target_bb = tblock;
3172                         if (sp != stack_start) {
3173                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3174                                 sp = stack_start;
3175                         }
3176                         start_new_bblock = 1;
3177                         inline_costs += 10;
3178                         break;
3179                 case CEE_BRFALSE_S:
3180                 case CEE_BRTRUE_S:
3181                         CHECK_STACK (1);
3182                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
3183                         ins->cil_code = ip++;
3184                         target = ip + 1 + *(signed char*)ip;
3185                         ip++;
3186                         ADD_UNCOND (ins->opcode == CEE_BRTRUE);
3187                         if (sp != stack_start) {
3188                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3189                                 sp = stack_start;
3190                         }
3191                         inline_costs += 10;
3192                         break;
3193                 case CEE_BEQ_S:
3194                 case CEE_BGE_S:
3195                 case CEE_BGT_S:
3196                 case CEE_BLE_S:
3197                 case CEE_BLT_S:
3198                 case CEE_BNE_UN_S:
3199                 case CEE_BGE_UN_S:
3200                 case CEE_BGT_UN_S:
3201                 case CEE_BLE_UN_S:
3202                 case CEE_BLT_UN_S:
3203                         CHECK_STACK (2);
3204                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
3205                         ins->cil_code = ip++;
3206                         target = ip + 1 + *(signed char*)ip;
3207                         ip++;
3208                         ADD_BINCOND (NULL);
3209                         if (sp != stack_start) {
3210                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3211                                 sp = stack_start;
3212                         }
3213                         inline_costs += 10;
3214                         break;
3215                 case CEE_BR:
3216                         MONO_INST_NEW (cfg, ins, CEE_BR);
3217                         ins->cil_code = ip++;
3218                         MONO_ADD_INS (bblock, ins);
3219                         target = ip + 4 + (gint32)read32(ip);
3220                         ip += 4;
3221                         GET_BBLOCK (cfg, bbhash, tblock, target);
3222                         link_bblock (cfg, bblock, tblock);
3223                         CHECK_BBLOCK (target, ip, tblock);
3224                         ins->inst_target_bb = tblock;
3225                         if (sp != stack_start) {
3226                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3227                                 sp = stack_start;
3228                         }
3229                         start_new_bblock = 1;
3230                         inline_costs += 10;
3231                         break;
3232                 case CEE_BRFALSE:
3233                 case CEE_BRTRUE:
3234                         CHECK_STACK (1);
3235                         MONO_INST_NEW (cfg, ins, *ip);
3236                         ins->cil_code = ip++;
3237                         target = ip + 4 + (gint32)read32(ip);
3238                         ip += 4;
3239                         ADD_UNCOND(ins->opcode == CEE_BRTRUE);
3240                         if (sp != stack_start) {
3241                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3242                                 sp = stack_start;
3243                         }
3244                         inline_costs += 10;
3245                         break;
3246                 case CEE_BEQ:
3247                 case CEE_BGE:
3248                 case CEE_BGT:
3249                 case CEE_BLE:
3250                 case CEE_BLT:
3251                 case CEE_BNE_UN:
3252                 case CEE_BGE_UN:
3253                 case CEE_BGT_UN:
3254                 case CEE_BLE_UN:
3255                 case CEE_BLT_UN:
3256                         CHECK_STACK (2);
3257                         MONO_INST_NEW (cfg, ins, *ip);
3258                         ins->cil_code = ip++;
3259                         target = ip + 4 + (gint32)read32(ip);
3260                         ip += 4;
3261                         ADD_BINCOND(NULL);
3262                         if (sp != stack_start) {
3263                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3264                                 sp = stack_start;
3265                         }
3266                         inline_costs += 10;
3267                         break;
3268                 case CEE_SWITCH:
3269                         CHECK_STACK (1);
3270                         n = read32 (ip + 1);
3271                         MONO_INST_NEW (cfg, ins, *ip);
3272                         --sp;
3273                         ins->inst_left = *sp;
3274                         if (ins->inst_left->type != STACK_I4) goto unverified;
3275                         ins->cil_code = ip;
3276                         ip += 5;
3277                         target = ip + n * sizeof (guint32);
3278                         MONO_ADD_INS (bblock, ins);
3279                         GET_BBLOCK (cfg, bbhash, tblock, target);
3280                         link_bblock (cfg, bblock, tblock);
3281                         ins->klass = GUINT_TO_POINTER (n);
3282                         ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (n + 1));
3283                         ins->inst_many_bb [n] = tblock;
3284
3285                         for (i = 0; i < n; ++i) {
3286                                 GET_BBLOCK (cfg, bbhash, tblock, target + (gint32)read32(ip));
3287                                 link_bblock (cfg, bblock, tblock);
3288                                 ins->inst_many_bb [i] = tblock;
3289                                 ip += 4;
3290                         }
3291                         /* FIXME: handle stack args */
3292                         inline_costs += 20;
3293                         break;
3294                 case CEE_LDIND_I1:
3295                 case CEE_LDIND_U1:
3296                 case CEE_LDIND_I2:
3297                 case CEE_LDIND_U2:
3298                 case CEE_LDIND_I4:
3299                 case CEE_LDIND_U4:
3300                 case CEE_LDIND_I8:
3301                 case CEE_LDIND_I:
3302                 case CEE_LDIND_R4:
3303                 case CEE_LDIND_R8:
3304                 case CEE_LDIND_REF:
3305                         CHECK_STACK (1);
3306                         MONO_INST_NEW (cfg, ins, *ip);
3307                         ins->cil_code = ip;
3308                         --sp;
3309                         ins->inst_i0 = *sp;
3310                         *sp++ = ins;
3311                         ins->type = ldind_type [*ip - CEE_LDIND_I1];
3312                         ins->flags |= ins_flag;
3313                         ins_flag = 0;
3314                         ++ip;
3315                         break;
3316                 case CEE_STIND_REF:
3317                 case CEE_STIND_I1:
3318                 case CEE_STIND_I2:
3319                 case CEE_STIND_I4:
3320                 case CEE_STIND_I8:
3321                 case CEE_STIND_R4:
3322                 case CEE_STIND_R8:
3323                         CHECK_STACK (2);
3324                         MONO_INST_NEW (cfg, ins, *ip);
3325                         ins->cil_code = ip++;
3326                         sp -= 2;
3327                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3328                         MONO_ADD_INS (bblock, ins);
3329                         ins->inst_i0 = sp [0];
3330                         ins->inst_i1 = sp [1];
3331                         ins->flags |= ins_flag;
3332                         ins_flag = 0;
3333                         inline_costs += 1;
3334                         break;
3335                 case CEE_ADD:
3336                 case CEE_SUB:
3337                 case CEE_MUL:
3338                 case CEE_DIV:
3339                 case CEE_DIV_UN:
3340                 case CEE_REM:
3341                 case CEE_REM_UN:
3342                 case CEE_AND:
3343                 case CEE_OR:
3344                 case CEE_XOR:
3345                 case CEE_SHL:
3346                 case CEE_SHR:
3347                 case CEE_SHR_UN:
3348                         CHECK_STACK (2);
3349                         ADD_BINOP (*ip);
3350                         ip++;
3351                         break;
3352                 case CEE_NEG:
3353                 case CEE_NOT:
3354                 case CEE_CONV_I1:
3355                 case CEE_CONV_I2:
3356                 case CEE_CONV_I4:
3357                 case CEE_CONV_R4:
3358                 case CEE_CONV_R8:
3359                 case CEE_CONV_U4:
3360                 case CEE_CONV_I8:
3361                 case CEE_CONV_U8:
3362                 case CEE_CONV_OVF_I8:
3363                 case CEE_CONV_OVF_U8:
3364                 case CEE_CONV_R_UN:
3365                         CHECK_STACK (1);
3366                         ADD_UNOP (*ip);
3367                         ip++;                   
3368                         break;
3369                 case CEE_CONV_OVF_I4:
3370                 case CEE_CONV_OVF_I1:
3371                 case CEE_CONV_OVF_I2:
3372                 case CEE_CONV_OVF_I:
3373                 case CEE_CONV_OVF_U:
3374                         CHECK_STACK (1);
3375
3376                         if (sp [-1]->type == STACK_R8) {
3377                                 ADD_UNOP (CEE_CONV_OVF_I8);
3378                                 ADD_UNOP (*ip);
3379                         } else {
3380                                 ADD_UNOP (*ip);
3381                         }
3382
3383                         ip++;
3384                         break;
3385                 case CEE_CONV_OVF_U1:
3386                 case CEE_CONV_OVF_U2:
3387                 case CEE_CONV_OVF_U4:
3388                         CHECK_STACK (1);
3389
3390                         if (sp [-1]->type == STACK_R8) {
3391                                 ADD_UNOP (CEE_CONV_OVF_U8);
3392                                 ADD_UNOP (*ip);
3393                         } else {
3394                                 ADD_UNOP (*ip);
3395                         }
3396
3397                         ip++;
3398                         break;
3399                 case CEE_CONV_OVF_I1_UN:
3400                 case CEE_CONV_OVF_I2_UN:
3401                 case CEE_CONV_OVF_I4_UN:
3402                 case CEE_CONV_OVF_I8_UN:
3403                 case CEE_CONV_OVF_U1_UN:
3404                 case CEE_CONV_OVF_U2_UN:
3405                 case CEE_CONV_OVF_U4_UN:
3406                 case CEE_CONV_OVF_U8_UN:
3407                 case CEE_CONV_OVF_I_UN:
3408                 case CEE_CONV_OVF_U_UN:
3409                         CHECK_STACK (1);
3410                         ADD_UNOP (*ip);
3411                         ip++;
3412                         break;
3413                 case CEE_CPOBJ:
3414                         g_error ("opcode 0x%02x not handled", *ip);
3415                         break;
3416                 case CEE_LDOBJ: {
3417                         MonoInst *iargs [3];
3418                         CHECK_STACK (1);
3419                         --sp;
3420                         token = read32 (ip + 1);
3421                         if (method->wrapper_type != MONO_WRAPPER_NONE)
3422                                 klass = mono_method_get_wrapper_data (method, token);
3423                         else
3424                                 klass = mono_class_get (image, token);
3425
3426                         mono_class_init (klass);
3427                         n = mono_class_value_size (klass, NULL);
3428                         ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
3429                         NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
3430                         if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
3431                                 MonoInst *copy;
3432                                 MONO_INST_NEW (cfg, copy, OP_MEMCPY);
3433                                 copy->inst_left = iargs [0];
3434                                 copy->inst_right = *sp;
3435                                 copy->cil_code = ip;
3436                                 copy->unused = n;
3437                                 MONO_ADD_INS (bblock, copy);
3438                         } else {
3439                                 iargs [1] = *sp;
3440                                 NEW_ICONST (cfg, iargs [2], n);
3441                                 iargs [2]->cil_code = ip;
3442
3443                                 mono_emit_jit_icall (cfg, bblock, helper_memcpy, iargs, ip);
3444                         }
3445                         NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
3446                         ++sp;
3447                         ip += 5;
3448                         inline_costs += 1;
3449                         break;
3450                 }
3451                 case CEE_LDSTR:
3452                         CHECK_STACK_OVF (1);
3453                         n = read32 (ip + 1);
3454
3455                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
3456                                 int temp;
3457                                 MonoInst *iargs [1];
3458
3459                                 NEW_PCONST (cfg, iargs [0], mono_method_get_wrapper_data (method, n));                          
3460                                 temp = mono_emit_jit_icall (cfg, bblock, mono_string_new_wrapper, iargs, ip);
3461                                 NEW_TEMPLOAD (cfg, *sp, temp);
3462
3463                         } else {
3464
3465                                 if (mono_compile_aot) {
3466                                         cfg->ldstr_list = g_list_prepend (cfg->ldstr_list, (gpointer)n);
3467                                 }
3468
3469                                 if ((cfg->opt & MONO_OPT_SHARED) || mono_compile_aot) {
3470                                         int temp;
3471                                         MonoInst *iargs [3];
3472                                         NEW_TEMPLOAD (cfg, iargs [0], mono_get_domainvar (cfg)->inst_c0);
3473                                         NEW_IMAGECONST (cfg, iargs [1], image);
3474                                         NEW_ICONST (cfg, iargs [2], mono_metadata_token_index (n));
3475                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldstr, iargs, ip);
3476                                         NEW_TEMPLOAD (cfg, *sp, temp);
3477                                         mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
3478                                 } else {
3479                                         NEW_PCONST (cfg, ins, NULL);
3480                                         ins->cil_code = ip;
3481                                         ins->type = STACK_OBJ;
3482                                         ins->inst_p0 = mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
3483                                         *sp = ins;
3484                                 }
3485                         }
3486
3487                         sp++;
3488                         ip += 5;
3489                         break;
3490                 case CEE_NEWOBJ: {
3491                         MonoInst *iargs [2];
3492                         MonoMethodSignature *fsig;
3493                         int temp;
3494
3495                         token = read32 (ip + 1);
3496                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
3497                                 cmethod = mono_method_get_wrapper_data (method, token);
3498                         } else
3499                                 cmethod = mono_get_method (image, token, NULL);
3500                         fsig = mono_method_get_signature (cmethod, image, token);
3501
3502                         mono_class_init (cmethod->klass);
3503
3504                         n = fsig->param_count;
3505                         CHECK_STACK (n);
3506
3507                         /* move the args to allow room for 'this' in the first position */
3508                         while (n--) {
3509                                 --sp;
3510                                 sp [1] = sp [0];
3511                         }
3512
3513                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3514                         
3515
3516                         if (cmethod->klass->parent == mono_defaults.array_class) {
3517                                 NEW_METHODCONST (cfg, *sp, cmethod);
3518                                 temp = mono_emit_native_call (cfg, bblock, mono_array_new_va, fsig, sp, ip, FALSE);
3519
3520                         } else if (cmethod->string_ctor) {
3521                                 /* we simply pass a null pointer */
3522                                 NEW_PCONST (cfg, *sp, NULL); 
3523                                 /* now call the string ctor */
3524                                 temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, NULL);
3525                         } else {
3526                                 if (cmethod->klass->valuetype) {
3527                                         iargs [0] = mono_compile_create_var (cfg, &cmethod->klass->byval_arg, OP_LOCAL);
3528                                         temp = iargs [0]->inst_c0;
3529                                         NEW_TEMPLOADA (cfg, *sp, temp);
3530                                 } else {
3531                                         if ((cfg->opt & MONO_OPT_SHARED) || mono_compile_aot) {
3532                                                 NEW_DOMAINCONST (cfg, iargs [0]);
3533                                                 NEW_CLASSCONST (cfg, iargs [1], cmethod->klass);
3534
3535                                                 temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
3536                                         } else {
3537                                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
3538                                                 NEW_PCONST (cfg, iargs [0], vtable);
3539                                                 if (cmethod->klass->has_finalize || cmethod->klass->marshalbyref || (cfg->prof_options & MONO_PROFILE_ALLOCATIONS))
3540                                                         temp = mono_emit_jit_icall (cfg, bblock, mono_object_new_specific, iargs, ip);
3541                                                 else
3542                                                         temp = mono_emit_jit_icall (cfg, bblock, mono_object_new_fast, iargs, ip);
3543                                         }
3544                                         NEW_TEMPLOAD (cfg, *sp, temp);
3545                                 }
3546
3547                                 if ((cfg->opt & MONO_OPT_INLINE) && cmethod &&
3548                                     mono_method_check_inlining (cfg, cmethod) &&
3549                                     !mono_class_is_subclass_of (cmethod->klass, mono_defaults.exception_class, FALSE) &&
3550                                     !g_list_find (dont_inline, cmethod)) {
3551                                         int costs;
3552                                         MonoBasicBlock *ebblock;
3553                                         if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock))) {
3554
3555                                                 ip += 5;
3556                                                 real_offset += 5;
3557                                                 
3558                                                 GET_BBLOCK (cfg, bbhash, bblock, ip);
3559                                                 ebblock->next_bb = bblock;
3560                                                 link_bblock (cfg, ebblock, bblock);
3561
3562                                                 NEW_TEMPLOAD (cfg, *sp, temp);
3563                                                 sp++;
3564
3565                                                 /* indicates start of a new block, and triggers a load 
3566                                                    of all stack arguments at bb boundarie */
3567                                                 bblock = ebblock;
3568
3569                                                 inline_costs += costs;
3570                                                 break;
3571                                                 
3572                                         } else {
3573                                                 mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, sp[0]);
3574                                         }
3575                                 } else {
3576                                         /* now call the actual ctor */
3577                                         mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, sp[0]);
3578                                 }
3579                         }
3580
3581                         NEW_TEMPLOAD (cfg, *sp, temp);
3582                         sp++;
3583                         
3584                         ip += 5;
3585                         inline_costs += 5;
3586                         break;
3587                 }
3588                 case CEE_ISINST:
3589                         CHECK_STACK (1);
3590                         MONO_INST_NEW (cfg, ins, *ip);
3591                         --sp;
3592                         klass = mono_class_get (image, read32 (ip + 1));
3593                         mono_class_init (klass);
3594                         ins->type = STACK_OBJ;
3595                         ins->inst_left = *sp;
3596                         ins->inst_newa_class = klass;
3597                         ins->cil_code = ip;
3598                         ip += 5;
3599                         *sp++ = ins;
3600                         break;
3601                 case CEE_UNBOX: {
3602                         MonoInst *add, *vtoffset;
3603
3604                         CHECK_STACK (1);
3605                         --sp;
3606                         token = read32 (ip + 1);
3607                         if (method->wrapper_type != MONO_WRAPPER_NONE)
3608                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
3609                         else 
3610                                 klass = mono_class_get (image, token);
3611                         mono_class_init (klass);
3612
3613
3614                         MONO_INST_NEW (cfg, ins, OP_UNBOXCAST);
3615                         ins->type = STACK_OBJ;
3616                         ins->inst_left = *sp;
3617                         ins->klass = klass;
3618                         ins->inst_newa_class = klass;
3619                         ins->cil_code = ip;
3620
3621                         MONO_INST_NEW (cfg, add, CEE_ADD);
3622                         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
3623                         add->inst_left = ins;
3624                         add->inst_right = vtoffset;
3625                         add->type = STACK_MP;
3626                         *sp++ = add;
3627                         ip += 5;
3628                         inline_costs += 2;
3629                         break;
3630                 }
3631                 case CEE_CASTCLASS:
3632                         CHECK_STACK (1);
3633                         MONO_INST_NEW (cfg, ins, *ip);
3634                         --sp;
3635                         klass = mono_class_get (image, read32 (ip + 1));
3636                         mono_class_init (klass);
3637                         ins->type = STACK_OBJ;
3638                         ins->inst_left = *sp;
3639                         ins->klass = klass;
3640                         ins->inst_newa_class = klass;
3641                         ins->cil_code = ip;
3642                         ip += 5;
3643                         *sp++ = ins;
3644                         break;
3645                 case CEE_THROW:
3646                         CHECK_STACK (1);
3647                         MONO_INST_NEW (cfg, ins, *ip);
3648                         --sp;
3649                         ins->inst_left = *sp;
3650                         ins->cil_code = ip++;
3651                         MONO_ADD_INS (bblock, ins);
3652                         sp = stack_start;
3653                         start_new_bblock = 1;
3654                         break;
3655                 case CEE_LDFLD:
3656                 case CEE_LDFLDA:
3657                 case CEE_STFLD: {
3658                         MonoInst *offset_ins;
3659                         MonoClassField *field;
3660                         MonoBasicBlock *ebblock;
3661                         int costs;
3662                         guint foffset;
3663
3664                         if (*ip == CEE_STFLD) {
3665                                 CHECK_STACK (2);
3666                                 sp -= 2;
3667                         } else {
3668                                 CHECK_STACK (1);
3669                                 --sp;
3670                         }
3671                         // FIXME: enable this test later.
3672                         //if (sp [0]->type != STACK_OBJ && sp [0]->type != STACK_MP)
3673                         //      goto unverified;
3674                         token = read32 (ip + 1);
3675                         field = mono_field_from_token (image, token, &klass);
3676                         mono_class_init (klass);
3677
3678                         foffset = klass->valuetype? field->offset - sizeof (MonoObject): field->offset;
3679                         /* FIXME: mark instructions for use in SSA */
3680                         if (*ip == CEE_STFLD) {
3681                                 if (klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) {
3682                                         MonoMethod *stfld_wrapper = mono_marshal_get_stfld_wrapper (field->type); 
3683                                         MonoInst *iargs [5];
3684
3685                                         iargs [0] = sp [0];
3686                                         NEW_CLASSCONST (cfg, iargs [1], klass);
3687                                         NEW_FIELDCONST (cfg, iargs [2], field);
3688                                         NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : 
3689                                                     field->offset);
3690                                         iargs [4] = sp [1];
3691
3692                                         if (cfg->opt & MONO_OPT_INLINE) {
3693                                                 costs = inline_method (cfg, stfld_wrapper, stfld_wrapper->signature, bblock, 
3694                                                                        iargs, ip, real_offset, dont_inline, &ebblock);
3695                                                 g_assert (costs > 0);
3696                                                       
3697                                                 ip += 5;
3698                                                 real_offset += 5;
3699
3700                                                 GET_BBLOCK (cfg, bbhash, bblock, ip);
3701                                                 ebblock->next_bb = bblock;
3702                                                 link_bblock (cfg, ebblock, bblock);
3703
3704                                                 /* indicates start of a new block, and triggers a load 
3705                                                    of all stack arguments at bb boundarie */
3706                                                 bblock = ebblock;
3707
3708                                                 inline_costs += costs;
3709                                                 break;
3710                                         } else {
3711                                                 mono_emit_method_call_spilled (cfg, bblock, stfld_wrapper, stfld_wrapper->signature, iargs, ip, NULL);
3712                                         }
3713                                 } else {
3714                                         MonoInst *store;
3715                                         NEW_ICONST (cfg, offset_ins, foffset);
3716                                         MONO_INST_NEW (cfg, ins, CEE_ADD);
3717                                         ins->cil_code = ip;
3718                                         ins->inst_left = *sp;
3719                                         ins->inst_right = offset_ins;
3720                                         ins->type = STACK_MP;
3721
3722                                         MONO_INST_NEW (cfg, store, mono_type_to_stind (field->type));
3723                                         store->cil_code = ip;
3724                                         store->inst_left = ins;
3725                                         store->inst_right = sp [1];
3726                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3727                                         store->flags |= ins_flag;
3728                                         ins_flag = 0;
3729                                         if (store->opcode == CEE_STOBJ) {
3730                                                 handle_stobj (cfg, bblock, ins, sp [1], ip, 
3731                                                               mono_class_from_mono_type (field->type), FALSE, FALSE);
3732                                         } else
3733                                                 MONO_ADD_INS (bblock, store);
3734                                 }
3735                         } else {
3736                                 if (klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) {
3737                                         /* fixme: we need to inline that call somehow */
3738                                         MonoMethod *ldfld_wrapper = mono_marshal_get_ldfld_wrapper (field->type); 
3739                                         MonoInst *iargs [4];
3740                                         int temp;
3741                                         
3742                                         iargs [0] = sp [0];
3743                                         NEW_CLASSCONST (cfg, iargs [1], klass);
3744                                         NEW_FIELDCONST (cfg, iargs [2], field);
3745                                         NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
3746                                         if (cfg->opt & MONO_OPT_INLINE) {
3747                                                 costs = inline_method (cfg, ldfld_wrapper, ldfld_wrapper->signature, bblock, 
3748                                                                        iargs, ip, real_offset, dont_inline, &ebblock);
3749                                                 g_assert (costs > 0);
3750                                                       
3751                                                 ip += 5;
3752                                                 real_offset += 5;
3753
3754                                                 GET_BBLOCK (cfg, bbhash, bblock, ip);
3755                                                 ebblock->next_bb = bblock;
3756                                                 link_bblock (cfg, ebblock, bblock);
3757
3758                                                 temp = iargs [0]->inst_i0->inst_c0;
3759
3760                                                 if (*ip == CEE_LDFLDA) {
3761                                                         /* not sure howto handle this */
3762                                                         NEW_TEMPLOADA (cfg, *sp, temp);
3763                                                 } else {
3764                                                         NEW_TEMPLOAD (cfg, *sp, temp);
3765                                                 }
3766                                                 sp++;
3767
3768                                                 /* indicates start of a new block, and triggers a load of
3769                                                    all stack arguments at bb boundarie */
3770                                                 bblock = ebblock;
3771                                                 
3772                                                 inline_costs += costs;
3773                                                 break;
3774                                         } else {
3775                                                 temp = mono_emit_method_call_spilled (cfg, bblock, ldfld_wrapper, ldfld_wrapper->signature, iargs, ip, NULL);
3776                                                 if (*ip == CEE_LDFLDA) {
3777                                                         /* not sure howto handle this */
3778                                                         NEW_TEMPLOADA (cfg, *sp, temp);
3779                                                 } else {
3780                                                         NEW_TEMPLOAD (cfg, *sp, temp);
3781                                                 }
3782                                                 sp++;
3783                                         }
3784                                 } else {
3785                                         NEW_ICONST (cfg, offset_ins, foffset);
3786                                         MONO_INST_NEW (cfg, ins, CEE_ADD);
3787                                         ins->cil_code = ip;
3788                                         ins->inst_left = *sp;
3789                                         ins->inst_right = offset_ins;
3790                                         ins->type = STACK_MP;
3791
3792                                         if (*ip == CEE_LDFLDA) {
3793                                                 *sp++ = ins;
3794                                         } else {
3795                                                 MonoInst *load;
3796                                                 MONO_INST_NEW (cfg, load, mono_type_to_ldind (field->type));
3797                                                 type_to_eval_stack_type (field->type, load);
3798                                                 load->cil_code = ip;
3799                                                 load->inst_left = ins;
3800                                                 load->flags |= ins_flag;
3801                                                 ins_flag = 0;
3802                                                 *sp++ = load;
3803                                         }
3804                                 }
3805                         }
3806                         ip += 5;
3807                         break;
3808                 }
3809                 case CEE_LDSFLD:
3810                 case CEE_LDSFLDA:
3811                 case CEE_STSFLD: {
3812                         MonoClassField *field;
3813
3814                         token = read32 (ip + 1);
3815
3816                         field = mono_field_from_token (image, token, &klass);
3817                         mono_class_init (klass);
3818
3819                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3820                                 
3821                         if (((cfg->opt & MONO_OPT_SHARED) || mono_compile_aot)) {
3822                                 int temp;
3823                                 MonoInst *iargs [2];
3824                                 g_assert (field->parent);
3825                                 NEW_TEMPLOAD (cfg, iargs [0], mono_get_domainvar (cfg)->inst_c0);
3826                                 NEW_FIELDCONST (cfg, iargs [1], field);
3827                                 temp = mono_emit_jit_icall (cfg, bblock, mono_class_static_field_address, iargs, ip);
3828                                 NEW_TEMPLOAD (cfg, ins, temp);
3829                         } else {
3830                                 gpointer addr;
3831                                 MonoVTable *vtable;
3832                                 vtable = mono_class_vtable (cfg->domain, klass);
3833                                 if (!cfg->domain->thread_static_fields || !(addr = g_hash_table_lookup (cfg->domain->thread_static_fields, field))) {
3834                                         if (!vtable->initialized && !(klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) && needs_cctor_run (klass, method)) {
3835                                                 MonoInst *iargs [1];
3836                                                 NEW_PCONST (cfg, iargs [0], vtable);
3837                                                 mono_emit_jit_icall (cfg, bblock, mono_runtime_class_init, iargs, ip);
3838                                                 if (cfg->verbose_level > 2)
3839                                                         g_print ("class %s.%s needs init call for %s\n", klass->name_space, klass->name, field->name);
3840                                         } else {
3841                                                 mono_runtime_class_init (vtable);
3842                                         }
3843                                         addr = (char*)vtable->data + field->offset;
3844                                         NEW_PCONST (cfg, ins, addr);
3845                                         ins->cil_code = ip;
3846                                 } else {
3847                                         /* 
3848                                          * insert call to mono_threads_get_static_data (GPOINTER_TO_UINT (addr)) 
3849                                          * This could be later optimized to do just a couple of
3850                                          * memory dereferences with constant offsets.
3851                                          */
3852                                         int temp;
3853                                         MonoInst *iargs [1];
3854                                         NEW_ICONST (cfg, iargs [0], GPOINTER_TO_UINT (addr));
3855                                         temp = mono_emit_jit_icall (cfg, bblock, mono_threads_get_static_data, iargs, ip);
3856                                         NEW_TEMPLOAD (cfg, ins, temp);
3857                                 }
3858                         }
3859
3860                         /* FIXME: mark instructions for use in SSA */
3861                         if (*ip == CEE_LDSFLDA) {
3862                                 *sp++ = ins;
3863                         } else if (*ip == CEE_STSFLD) {
3864                                 MonoInst *store;
3865                                 CHECK_STACK (1);
3866                                 sp--;
3867                                 MONO_INST_NEW (cfg, store, mono_type_to_stind (field->type));
3868                                 store->cil_code = ip;
3869                                 store->inst_left = ins;
3870                                 store->inst_right = sp [0];
3871                                 store->flags |= ins_flag;
3872                                 ins_flag = 0;
3873
3874                                 if (store->opcode == CEE_STOBJ) {
3875                                         handle_stobj (cfg, bblock, ins, sp [0], ip, mono_class_from_mono_type (field->type), FALSE, FALSE);
3876                                 } else
3877                                         MONO_ADD_INS (bblock, store);
3878                         } else {
3879                                 gboolean is_const = FALSE;
3880                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
3881                                 if (!((cfg->opt & MONO_OPT_SHARED) || mono_compile_aot) && 
3882                                     vtable->initialized && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY)) {
3883                                         gpointer addr = (char*)vtable->data + field->offset;
3884                                         /* g_print ("RO-FIELD %s.%s:%s\n", klass->name_space, klass->name, field->name);*/
3885                                         is_const = TRUE;
3886                                         switch (field->type->type) {
3887                                         case MONO_TYPE_BOOLEAN:
3888                                         case MONO_TYPE_U1:
3889                                                 NEW_ICONST (cfg, *sp, *((guint8 *)addr));
3890                                                 sp++;
3891                                                 break;
3892                                         case MONO_TYPE_I1:
3893                                                 NEW_ICONST (cfg, *sp, *((gint8 *)addr));
3894                                                 sp++;
3895                                                 break;                                          
3896                                         case MONO_TYPE_CHAR:
3897                                         case MONO_TYPE_U2:
3898                                                 NEW_ICONST (cfg, *sp, *((guint16 *)addr));
3899                                                 sp++;
3900                                                 break;
3901                                         case MONO_TYPE_I2:
3902                                                 NEW_ICONST (cfg, *sp, *((gint16 *)addr));
3903                                                 sp++;
3904                                                 break;
3905                                                 break;
3906                                         case MONO_TYPE_I4:
3907                                                 NEW_ICONST (cfg, *sp, *((gint32 *)addr));
3908                                                 sp++;
3909                                                 break;                                          
3910                                         case MONO_TYPE_U4:
3911                                                 NEW_ICONST (cfg, *sp, *((guint32 *)addr));
3912                                                 sp++;
3913                                                 break;
3914                                         case MONO_TYPE_I:
3915                                         case MONO_TYPE_U:
3916                                         case MONO_TYPE_STRING:
3917                                         case MONO_TYPE_OBJECT:
3918                                         case MONO_TYPE_CLASS:
3919                                         case MONO_TYPE_SZARRAY:
3920                                         case MONO_TYPE_PTR:
3921                                         case MONO_TYPE_FNPTR:
3922                                         case MONO_TYPE_ARRAY:
3923                                                 NEW_PCONST (cfg, *sp, *((gpointer *)addr));
3924                                                 type_to_eval_stack_type (field->type, *sp);
3925                                                 sp++;
3926                                                 break;
3927                                         case MONO_TYPE_I8:
3928                                         case MONO_TYPE_U8:
3929                                                 MONO_INST_NEW (cfg, *sp, OP_I8CONST);
3930                                                 sp [0]->type = STACK_I8;
3931                                                 sp [0]->inst_l = *((gint64 *)addr);
3932                                                 sp++;
3933                                                 break;
3934                                         case MONO_TYPE_R4:
3935                                         case MONO_TYPE_R8:
3936                                         case MONO_TYPE_VALUETYPE:
3937                                         default:
3938                                                 is_const = FALSE;
3939                                                 break;
3940                                         }
3941                                 }
3942
3943                                 if (!is_const) {
3944                                         MonoInst *load;
3945                                         CHECK_STACK_OVF (1);
3946                                         MONO_INST_NEW (cfg, load, mono_type_to_ldind (field->type));
3947                                         type_to_eval_stack_type (field->type, load);
3948                                         load->cil_code = ip;
3949                                         load->inst_left = ins;
3950                                         *sp++ = load;
3951                                         load->flags |= ins_flag;
3952                                         ins_flag = 0;
3953                                         /* fixme: dont see the problem why this does not work */
3954                                         //cfg->disable_aot = TRUE;
3955                                 }
3956                         }
3957                         ip += 5;
3958                         break;
3959                 }
3960                 case CEE_STOBJ:
3961                         CHECK_STACK (2);
3962                         sp -= 2;
3963                         token = read32 (ip + 1);
3964                         if (method->wrapper_type != MONO_WRAPPER_NONE)
3965                                 klass = mono_method_get_wrapper_data (method, token);
3966                         else
3967                                 klass = mono_class_get (image, token);
3968                         mono_class_init (klass);
3969                         n = mono_type_to_stind (&klass->byval_arg);
3970                         if (n == CEE_STOBJ) {
3971                                 handle_stobj (cfg, bblock, sp [0], sp [1], ip, klass, FALSE, FALSE);
3972                         } else {
3973                                 /* FIXME: should check item at sp [1] is compatible with the type of the store. */
3974                                 MonoInst *store;
3975                                 MONO_INST_NEW (cfg, store, n);
3976                                 store->cil_code = ip;
3977                                 store->inst_left = sp [0];
3978                                 store->inst_right = sp [1];
3979                                 store->flags |= ins_flag;
3980                                 MONO_ADD_INS (bblock, store);
3981                         }
3982                         ins_flag = 0;
3983                         ip += 5;
3984                         inline_costs += 1;
3985                         break;
3986                 case CEE_BOX: {
3987                         MonoInst *iargs [2];
3988                         MonoInst *load, *vtoffset, *add, *val, *vstore;
3989                         int temp;
3990                         CHECK_STACK (1);
3991                         --sp;
3992                         val = *sp;
3993                         token = read32 (ip + 1);
3994                         if (method->wrapper_type != MONO_WRAPPER_NONE)
3995                                 klass = mono_method_get_wrapper_data (method, token);
3996                         else
3997                                 klass = mono_class_get (image, token);
3998                         mono_class_init (klass);
3999
4000                         /* much like NEWOBJ */
4001                         if ((cfg->opt & MONO_OPT_SHARED) || mono_compile_aot) {
4002                                 NEW_DOMAINCONST (cfg, iargs [0]);
4003                                 NEW_CLASSCONST (cfg, iargs [1], klass);
4004
4005                                 temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
4006                         } else {
4007                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
4008                                 NEW_PCONST (cfg, iargs [0], vtable);
4009                                 if (1 || klass->has_finalize || (cfg->prof_options & MONO_PROFILE_ALLOCATIONS))
4010                                         temp = mono_emit_jit_icall (cfg, bblock, mono_object_new_specific, iargs, ip);
4011                                 else
4012                                         temp = mono_emit_jit_icall (cfg, bblock, mono_object_new_fast, iargs, ip);
4013                         }
4014                         NEW_TEMPLOAD (cfg, load, temp);
4015                         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
4016                         MONO_INST_NEW (cfg, add, CEE_ADD);
4017                         add->inst_left = load;
4018                         add->inst_right = vtoffset;
4019                         add->cil_code = ip;
4020                         add->klass = klass;
4021                         MONO_INST_NEW (cfg, vstore, CEE_STIND_I);
4022                         vstore->opcode = mono_type_to_stind (&klass->byval_arg);
4023                         vstore->cil_code = ip;
4024                         vstore->inst_left = add;
4025                         vstore->inst_right = val;
4026
4027                         if (vstore->opcode == CEE_STOBJ) {
4028                                 handle_stobj (cfg, bblock, add, val, ip, klass, FALSE, FALSE);
4029                         } else
4030                                 MONO_ADD_INS (bblock, vstore);
4031
4032                         NEW_TEMPLOAD (cfg, load, temp);
4033                         *sp++ = load;
4034                         ip += 5;
4035                         inline_costs += 1;
4036                         break;
4037                 }
4038                 case CEE_NEWARR:
4039                         CHECK_STACK (1);
4040                         MONO_INST_NEW (cfg, ins, *ip);
4041                         ins->cil_code = ip;
4042                         --sp;
4043
4044                         token = read32 (ip + 1);
4045
4046                         /* allocate the domainvar - becaus this is used in decompose_foreach */
4047                         if ((cfg->opt & MONO_OPT_SHARED) || mono_compile_aot)
4048                                 mono_get_domainvar (cfg);
4049                         
4050                         if (method->wrapper_type != MONO_WRAPPER_NONE)
4051                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
4052                         else
4053                                 klass = mono_class_get (image, token);
4054
4055                         mono_class_init (klass);
4056                         ins->inst_newa_class = klass;
4057                         ins->inst_newa_len = *sp;
4058                         ins->type = STACK_OBJ;
4059                         ip += 5;
4060                         *sp++ = ins;
4061                         inline_costs += 1;
4062                         break;
4063                 case CEE_LDLEN:
4064                         CHECK_STACK (1);
4065                         MONO_INST_NEW (cfg, ins, *ip);
4066                         ins->cil_code = ip++;
4067                         --sp;
4068                         ins->inst_left = *sp;
4069                         ins->type = STACK_PTR;
4070                         *sp++ = ins;
4071                         break;
4072                 case CEE_LDELEMA:
4073                         CHECK_STACK (2);
4074                         sp -= 2;
4075                         klass = mono_class_get (image, read32 (ip + 1));
4076                         mono_class_init (klass);
4077                         NEW_LDELEMA (cfg, ins, sp, klass);
4078                         ins->cil_code = ip;
4079                         *sp++ = ins;
4080                         ip += 5;
4081                         break;
4082                 case CEE_LDELEM_I1:
4083                 case CEE_LDELEM_U1:
4084                 case CEE_LDELEM_I2:
4085                 case CEE_LDELEM_U2:
4086                 case CEE_LDELEM_I4:
4087                 case CEE_LDELEM_U4:
4088                 case CEE_LDELEM_I8:
4089                 case CEE_LDELEM_I:
4090                 case CEE_LDELEM_R4:
4091                 case CEE_LDELEM_R8:
4092                 case CEE_LDELEM_REF: {
4093                         MonoInst *load;
4094                         /*
4095                          * translate to:
4096                          * ldind.x (ldelema (array, index))
4097                          * ldelema does the bounds check
4098                          */
4099                         CHECK_STACK (2);
4100                         sp -= 2;
4101                         klass = array_access_to_klass (*ip);
4102                         NEW_LDELEMA (cfg, load, sp, klass);
4103                         load->cil_code = ip;
4104                         MONO_INST_NEW (cfg, ins, ldelem_to_ldind [*ip - CEE_LDELEM_I1]);
4105                         ins->cil_code = ip;
4106                         ins->inst_left = load;
4107                         *sp++ = ins;
4108                         ins->type = ldind_type [ins->opcode - CEE_LDIND_I1];
4109                         ++ip;
4110                         break;
4111                 }
4112                 case CEE_STELEM_I:
4113                 case CEE_STELEM_I1:
4114                 case CEE_STELEM_I2:
4115                 case CEE_STELEM_I4:
4116                 case CEE_STELEM_I8:
4117                 case CEE_STELEM_R4:
4118                 case CEE_STELEM_R8: {
4119                         MonoInst *load;
4120                         /*
4121                          * translate to:
4122                          * stind.x (ldelema (array, index), val)
4123                          * ldelema does the bounds check
4124                          */
4125                         CHECK_STACK (3);
4126                         sp -= 3;
4127                         klass = array_access_to_klass (*ip);
4128                         NEW_LDELEMA (cfg, load, sp, klass);
4129                         load->cil_code = ip;
4130                         MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
4131                         ins->cil_code = ip;
4132                         ins->inst_left = load;
4133                         ins->inst_right = sp [2];
4134                         ++ip;
4135                         handle_loaded_temps (cfg, bblock, stack_start, sp);
4136                         MONO_ADD_INS (bblock, ins);
4137                         /* FIXME: add the implicit STELEM_REF castclass */
4138                         inline_costs += 1;
4139                         cfg->disable_ssa = TRUE;
4140                         break;
4141                 }
4142                 case CEE_STELEM_REF: {
4143                         MonoInst *iargs [3];
4144
4145                         CHECK_STACK (3);
4146                         sp -= 3;
4147
4148                         handle_loaded_temps (cfg, bblock, stack_start, sp);
4149
4150                         iargs [2] = sp [2];
4151                         iargs [1] = sp [1];
4152                         iargs [0] = sp [0];
4153                         
4154                         mono_emit_jit_icall (cfg, bblock, helper_stelem_ref, iargs, ip);
4155
4156                         /*
4157                         MonoInst *group;
4158                         NEW_GROUP (cfg, group, sp [0], sp [1]);
4159                         MONO_INST_NEW (cfg, ins, CEE_STELEM_REF);
4160                         ins->cil_code = ip;
4161                         ins->inst_left = group;
4162                         ins->inst_right = sp [2];
4163                         MONO_ADD_INS (bblock, ins);
4164                         */
4165
4166                         ++ip;
4167                         inline_costs += 1;
4168                         cfg->disable_ssa = TRUE;
4169                         break;
4170                 }
4171                 case CEE_CKFINITE: {
4172                         MonoInst *store, *temp;
4173                         CHECK_STACK (1);
4174
4175                         /* this instr. can throw exceptions as side effect,
4176                          * so we cant eliminate dead code which contains CKFINITE opdodes.
4177                          * Spilling to memory makes sure that we always perform
4178                          * this check */
4179
4180                         
4181                         MONO_INST_NEW (cfg, ins, CEE_CKFINITE);
4182                         ins->cil_code = ip;
4183                         ins->inst_left = sp [-1];
4184                         temp = mono_compile_create_var (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL);
4185
4186                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
4187                         store->cil_code = ip;
4188                         MONO_ADD_INS (bblock, store);
4189
4190                         NEW_TEMPLOAD (cfg, sp [-1], temp->inst_c0);
4191                        
4192                         ++ip;
4193                         break;
4194                 }
4195                 case CEE_REFANYVAL:
4196                 case CEE_MKREFANY:
4197                         g_error ("opcode 0x%02x not handled", *ip);
4198                         break;
4199                 case CEE_LDTOKEN: {
4200                         gpointer handle;
4201                         MonoClass *handle_class;
4202
4203                         CHECK_STACK_OVF (1);
4204
4205                         n = read32 (ip + 1);
4206
4207                         handle = mono_ldtoken (image, n, &handle_class);
4208                         mono_class_init (handle_class);
4209
4210                         if (((cfg->opt & MONO_OPT_SHARED) || mono_compile_aot)) {
4211                                 int temp;
4212                                 MonoInst *res, *store, *addr, *vtvar, *iargs [2];
4213
4214                                 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL); 
4215
4216                                 NEW_IMAGECONST (cfg, iargs [0], image);
4217                                 NEW_ICONST (cfg, iargs [1], n);
4218                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldtoken_wrapper, iargs, ip);
4219                                 NEW_TEMPLOAD (cfg, res, temp);
4220                                 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
4221                                 NEW_INDSTORE (cfg, store, addr, res, &mono_defaults.int_class->byval_arg);
4222                                 MONO_ADD_INS (bblock, store);
4223                                 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
4224                         } else {
4225                                 if ((ip [5] == CEE_CALL) && (cmethod = mono_get_method (image, read32 (ip + 6), NULL)) &&
4226                                                 (cmethod->klass == mono_defaults.monotype_class->parent) &&
4227                                                 (strcmp (cmethod->name, "GetTypeFromHandle") == 0)) {
4228                                         MonoClass *tclass = mono_class_from_mono_type (handle);
4229                                         mono_class_init (tclass);
4230                                         NEW_PCONST (cfg, ins, mono_type_get_object (cfg->domain, handle));
4231                                         ins->type = STACK_OBJ;
4232                                         ins->klass = cmethod->klass;
4233                                         ip += 5;
4234                                 } else {
4235                                         NEW_PCONST (cfg, ins, handle);
4236                                         ins->type = STACK_VTYPE;
4237                                         ins->klass = handle_class;
4238                                 }
4239                         }
4240
4241                         *sp++ = ins;
4242                         ip += 5;
4243                         break;
4244                 }
4245                 case CEE_CONV_U2:
4246                 case CEE_CONV_U1:
4247                 case CEE_CONV_I:
4248                         CHECK_STACK (1);
4249                         ADD_UNOP (*ip);
4250                         ip++;
4251                         break;
4252                 case CEE_ADD_OVF:
4253                 case CEE_ADD_OVF_UN:
4254                 case CEE_MUL_OVF:
4255                 case CEE_MUL_OVF_UN:
4256                 case CEE_SUB_OVF:
4257                 case CEE_SUB_OVF_UN:
4258                         CHECK_STACK (2);
4259                         ADD_BINOP (*ip);
4260                         ip++;
4261                         break;
4262                 case CEE_ENDFINALLY:
4263                         /* FIXME: check stack state */
4264                         MONO_INST_NEW (cfg, ins, *ip);
4265                         MONO_ADD_INS (bblock, ins);
4266                         ins->cil_code = ip++;
4267                         start_new_bblock = 1;
4268                         break;
4269                 case CEE_LEAVE:
4270                 case CEE_LEAVE_S: {
4271                         GList *handlers;
4272                         if (*ip == CEE_LEAVE) {
4273                                 target = ip + 5 + (gint32)read32(ip + 1);
4274                         } else {
4275                                 target = ip + 2 + (signed char)(ip [1]);
4276                         }
4277
4278                         /* empty the stack */
4279                         while (sp != stack_start) {
4280                                 MONO_INST_NEW (cfg, ins, CEE_POP);
4281                                 ins->cil_code = ip;
4282                                 sp--;
4283                                 ins->inst_i0 = *sp;
4284                                 MONO_ADD_INS (bblock, ins);
4285                         }
4286
4287                         /* fixme: call fault handler ? */
4288
4289                         if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
4290                                 GList *tmp;
4291                                 for (tmp = handlers; tmp; tmp = tmp->next) {
4292                                         tblock = tmp->data;
4293                                         link_bblock (cfg, bblock, tblock);
4294                                         MONO_INST_NEW (cfg, ins, OP_CALL_HANDLER);
4295                                         ins->cil_code = ip;
4296                                         ins->inst_target_bb = tblock;
4297                                         MONO_ADD_INS (bblock, ins);
4298                                 }
4299                                 g_list_free (handlers);
4300                         } 
4301
4302                         MONO_INST_NEW (cfg, ins, CEE_BR);
4303                         ins->cil_code = ip;
4304                         MONO_ADD_INS (bblock, ins);
4305                         GET_BBLOCK (cfg, bbhash, tblock, target);
4306                         link_bblock (cfg, bblock, tblock);
4307                         CHECK_BBLOCK (target, ip, tblock);
4308                         ins->inst_target_bb = tblock;
4309                         start_new_bblock = 1;
4310
4311                         if (*ip == CEE_LEAVE)
4312                                 ip += 5;
4313                         else
4314                                 ip += 2;
4315
4316                         break;
4317                 }
4318                 case CEE_STIND_I:
4319                         CHECK_STACK (2);
4320                         MONO_INST_NEW (cfg, ins, *ip);
4321                         sp -= 2;
4322                         handle_loaded_temps (cfg, bblock, stack_start, sp);
4323                         MONO_ADD_INS (bblock, ins);
4324                         ins->cil_code = ip++;
4325                         ins->inst_i0 = sp [0];
4326                         ins->inst_i1 = sp [1];
4327                         inline_costs += 1;
4328                         break;
4329                 case CEE_CONV_U:
4330                         CHECK_STACK (1);
4331                         ADD_UNOP (*ip);
4332                         ip++;
4333                         break;
4334                 /* trampoline mono specific opcodes */
4335                 case MONO_CUSTOM_PREFIX: {
4336
4337                         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
4338
4339                         switch (ip [1]) {
4340
4341                         case CEE_MONO_FUNC1: {
4342                                 int temp;
4343                                 gpointer func = NULL;
4344                                 CHECK_STACK (1);
4345                                 sp--;
4346
4347                                 switch (ip [2]) {
4348                                 case MONO_MARSHAL_CONV_STR_LPWSTR:
4349                                         func = mono_string_to_utf16;
4350                                         break;
4351                                 case MONO_MARSHAL_CONV_LPWSTR_STR:
4352                                         func = mono_string_from_utf16;
4353                                         break;
4354                                 case MONO_MARSHAL_CONV_LPSTR_STR:
4355                                         func = mono_string_new_wrapper;
4356                                         break;
4357                                 case MONO_MARSHAL_CONV_STR_LPTSTR:
4358                                 case MONO_MARSHAL_CONV_STR_LPSTR:
4359                                         func = mono_string_to_utf8;
4360                                         break;
4361                                 case MONO_MARSHAL_CONV_STR_BSTR:
4362                                         func = mono_string_to_bstr;
4363                                         break;
4364                                 case MONO_MARSHAL_CONV_STR_TBSTR:
4365                                 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
4366                                         func = mono_string_to_ansibstr;
4367                                         break;
4368                                 case MONO_MARSHAL_CONV_SB_LPSTR:
4369                                         func = mono_string_builder_to_utf8;
4370                                         break;
4371                                 case MONO_MARSHAL_CONV_ARRAY_SAVEARRAY:
4372                                         func = mono_array_to_savearray;
4373                                         break;
4374                                 case MONO_MARSHAL_CONV_ARRAY_LPARRAY:
4375                                         func = mono_array_to_lparray;
4376                                         break;
4377                                 case MONO_MARSHAL_CONV_DEL_FTN:
4378                                         func = mono_delegate_to_ftnptr;
4379                                         break;
4380                                 case MONO_MARSHAL_CONV_STRARRAY_STRLPARRAY:
4381                                         func = mono_marshal_string_array;
4382                                         break;
4383                                 default:
4384                                         g_warning ("unknown conversion %d\n", ip [2]);
4385                                         g_assert_not_reached ();
4386                                 }
4387
4388                                 temp = mono_emit_jit_icall (cfg, bblock, func, sp, ip);
4389                                 NEW_TEMPLOAD (cfg, *sp, temp);
4390                                 sp++;
4391
4392                                 ip += 3;
4393                                 inline_costs += 10 * num_calls++;
4394                                 break;
4395                         }
4396                         case CEE_MONO_PROC2: {
4397                                 gpointer func = NULL;
4398                                 CHECK_STACK (2);
4399                                 sp -= 2;
4400
4401                                 switch (ip [2]) {
4402                                 case MONO_MARSHAL_CONV_LPSTR_SB:
4403                                         func = mono_string_utf8_to_builder;
4404                                         break;
4405                                 case MONO_MARSHAL_FREE_ARRAY:
4406                                         func = mono_marshal_free_array;
4407                                         break;
4408                                 default:
4409                                         g_assert_not_reached ();
4410                                 }
4411
4412                                 mono_emit_jit_icall (cfg, bblock, func, sp, ip);
4413                                 ip += 3;
4414                                 inline_costs += 10 * num_calls++;
4415                                 break;
4416                         }
4417                         case CEE_MONO_PROC3: {
4418                                 gpointer func = NULL;
4419                                 CHECK_STACK (3);
4420                                 sp -= 3;
4421
4422                                 switch (ip [2]) {
4423                                 case MONO_MARSHAL_CONV_STR_BYVALSTR:
4424                                         func = mono_string_to_byvalstr;
4425                                         break;
4426                                 case MONO_MARSHAL_CONV_STR_BYVALWSTR:
4427                                         func = mono_string_to_byvalwstr;
4428                                         break;
4429                                 default:
4430                                         g_assert_not_reached ();
4431                                 }
4432
4433                                 mono_emit_jit_icall (cfg, bblock, func, sp, ip);
4434                                 ip += 3;
4435                                 inline_costs += 10 * num_calls++;
4436                                 break;
4437                         }
4438                         case CEE_MONO_FREE:
4439                                 CHECK_STACK (1);
4440                                 sp -= 1;
4441                                 mono_emit_jit_icall (cfg, bblock, g_free, sp, ip);
4442                                 ip += 2;
4443                                 inline_costs += 10 * num_calls++;
4444                                 break;
4445                         case CEE_MONO_LDPTR:
4446                                 CHECK_STACK_OVF (1);
4447                                 token = read32 (ip + 2);
4448                                 NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
4449                                 ins->cil_code = ip;
4450                                 *sp++ = ins;
4451                                 ip += 6;
4452                                 inline_costs += 10 * num_calls++;
4453                                 break;
4454                         case CEE_MONO_VTADDR:
4455                                 CHECK_STACK (1);
4456                                 --sp;
4457                                 MONO_INST_NEW (cfg, ins, OP_VTADDR);
4458                                 ins->cil_code = ip;
4459                                 ins->type = STACK_MP;
4460                                 ins->inst_left = *sp;
4461                                 *sp++ = ins;
4462                                 ip += 2;
4463                                 break;
4464                         case CEE_MONO_NEWOBJ: {
4465                                 MonoInst *iargs [2];
4466                                 int temp;
4467                                 CHECK_STACK_OVF (1);
4468                                 token = read32 (ip + 2);
4469                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
4470                                 mono_class_init (klass);
4471                                 NEW_DOMAINCONST (cfg, iargs [0]);
4472                                 NEW_CLASSCONST (cfg, iargs [1], klass);
4473                                 temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
4474                                 NEW_TEMPLOAD (cfg, *sp, temp);
4475                                 sp++;
4476                                 ip += 6;
4477                                 inline_costs += 10 * num_calls++;
4478                                 break;
4479                         }
4480                         case CEE_MONO_OBJADDR:
4481                                 CHECK_STACK (1);
4482                                 --sp;
4483                                 MONO_INST_NEW (cfg, ins, OP_OBJADDR);
4484                                 ins->cil_code = ip;
4485                                 ins->type = STACK_MP;
4486                                 ins->inst_left = *sp;
4487                                 *sp++ = ins;
4488                                 ip += 2;
4489                                 break;
4490                         case CEE_MONO_LDNATIVEOBJ:
4491                                 CHECK_STACK (1);
4492                                 token = read32 (ip + 2);
4493                                 klass = mono_method_get_wrapper_data (method, token);
4494                                 g_assert (klass->valuetype);
4495                                 mono_class_init (klass);
4496                                 NEW_INDLOAD (cfg, ins, sp [-1], &klass->byval_arg);
4497                                 sp [-1] = ins;
4498                                 ip += 6;
4499                                 break;
4500                         case CEE_MONO_RETOBJ:
4501                                 g_assert (cfg->ret);
4502                                 g_assert (method->signature->pinvoke); 
4503                                 CHECK_STACK (1);
4504                                 --sp;
4505                                 
4506                                 token = read32 (ip + 2);    
4507                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
4508
4509                                 NEW_RETLOADA (cfg, ins);
4510                                 handle_stobj (cfg, bblock, ins, *sp, ip, klass, FALSE, TRUE);
4511                                 
4512                                 if (sp != stack_start)
4513                                         goto unverified;
4514                                 
4515                                 MONO_INST_NEW (cfg, ins, CEE_BR);
4516                                 ins->cil_code = ip;
4517                                 ins->inst_target_bb = end_bblock;
4518                                 MONO_ADD_INS (bblock, ins);
4519                                 link_bblock (cfg, bblock, end_bblock);
4520                                 start_new_bblock = 1;
4521                                 ip += 6;
4522                                 break;
4523                         default:
4524                                 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
4525                                 break;
4526                         }
4527                         break;
4528                 }
4529                 case CEE_PREFIX1: {
4530                         switch (ip [1]) {
4531                         case CEE_ARGLIST: {
4532                                 /* somewhat similar to LDTOKEN */
4533                                 MonoInst *addr, *vtvar;
4534                                 CHECK_STACK_OVF (1);
4535                                 vtvar = mono_compile_create_var (cfg, &mono_defaults.argumenthandle_class->byval_arg, OP_LOCAL); 
4536
4537                                 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
4538                                 addr->cil_code = ip;
4539                                 MONO_INST_NEW (cfg, ins, OP_ARGLIST);
4540                                 ins->cil_code = ip;
4541                                 ins->inst_left = addr;
4542                                 MONO_ADD_INS (bblock, ins);
4543                                 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
4544                                 ins->cil_code = ip;
4545                                 *sp++ = ins;
4546                                 ip += 2;
4547                                 break;
4548                         }
4549                         case CEE_CEQ:
4550                         case CEE_CGT:
4551                         case CEE_CGT_UN:
4552                         case CEE_CLT:
4553                         case CEE_CLT_UN: {
4554                                 MonoInst *cmp;
4555                                 CHECK_STACK (2);
4556                                 MONO_INST_NEW (cfg, cmp, 256 + ip [1]);
4557                                 MONO_INST_NEW (cfg, ins, cmp->opcode);
4558                                 sp -= 2;
4559                                 cmp->inst_i0 = sp [0];
4560                                 cmp->inst_i1 = sp [1];
4561                                 cmp->cil_code = ip;
4562                                 type_from_op (cmp);
4563                                 CHECK_TYPE (cmp);
4564                                 cmp->opcode = OP_COMPARE;
4565                                 ins->cil_code = ip;
4566                                 ins->type = STACK_I4;
4567                                 ins->inst_i0 = cmp;
4568                                 *sp++ = ins;
4569                                 ip += 2;
4570                                 break;
4571                         }
4572                         case CEE_LDFTN: {
4573                                 MonoInst *argconst;
4574                                 int temp;
4575
4576                                 CHECK_STACK_OVF (1);
4577                                 n = read32 (ip + 2);
4578                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
4579                                         cmethod = mono_method_get_wrapper_data (method, n);
4580                                 else {
4581                                         cmethod = mono_get_method (image, n, NULL);
4582
4583                                         /*
4584                                          * We can't do this in mono_ldftn, since it is used in
4585                                          * the synchronized wrapper, leading to an infinite loop.
4586                                          */
4587                                         if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
4588                                                 cmethod = mono_marshal_get_synchronized_wrapper (cmethod);
4589                                 }
4590
4591                                 mono_class_init (cmethod->klass);
4592                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4593
4594                                 NEW_METHODCONST (cfg, argconst, cmethod);
4595                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn, &argconst, ip);
4596                                 NEW_TEMPLOAD (cfg, *sp, temp);
4597                                 sp ++;
4598                                 
4599                                 ip += 6;
4600                                 inline_costs += 10 * num_calls++;
4601                                 break;
4602                         }
4603                         case CEE_LDVIRTFTN: {
4604                                 MonoInst *args [2];
4605                                 int temp;
4606
4607                                 CHECK_STACK (1);
4608                                 n = read32 (ip + 2);
4609                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
4610                                         cmethod = mono_method_get_wrapper_data (method, n);
4611                                 else
4612                                         cmethod = mono_get_method (image, n, NULL);
4613
4614                                 mono_class_init (cmethod->klass);
4615                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4616
4617                                 --sp;
4618                                 args [0] = *sp;
4619                                 NEW_METHODCONST (cfg, args [1], cmethod);
4620                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldvirtfn, args, ip);
4621                                 NEW_TEMPLOAD (cfg, *sp, temp);
4622                                 sp ++;
4623
4624                                 ip += 6;
4625                                 inline_costs += 10 * num_calls++;
4626                                 break;
4627                         }
4628                         case CEE_LDARG:
4629                                 CHECK_STACK_OVF (1);
4630                                 NEW_ARGLOAD (cfg, ins, read16 (ip + 2));
4631                                 ins->cil_code = ip;
4632                                 *sp++ = ins;
4633                                 ip += 4;
4634                                 break;
4635                         case CEE_LDARGA:
4636                                 CHECK_STACK_OVF (1);
4637                                 NEW_ARGLOADA (cfg, ins, read16 (ip + 2));
4638                                 ins->cil_code = ip;
4639                                 *sp++ = ins;
4640                                 ip += 4;
4641                                 break;
4642                         case CEE_STARG:
4643                                 CHECK_STACK (1);
4644                                 --sp;
4645                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4646                                 n = read16 (ip + 2);
4647                                 NEW_ARGSTORE (cfg, ins, n, *sp);
4648                                 ins->cil_code = ip;
4649                                 if (ins->opcode == CEE_STOBJ) {
4650                                         NEW_ARGLOADA (cfg, ins, n);
4651                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
4652                                 } else
4653                                         MONO_ADD_INS (bblock, ins);
4654                                 ip += 4;
4655                                 break;
4656                         case CEE_LDLOC:
4657                                 CHECK_STACK_OVF (1);
4658                                 NEW_LOCLOAD (cfg, ins, read16 (ip + 2));
4659                                 ins->cil_code = ip;
4660                                 *sp++ = ins;
4661                                 ip += 4;
4662                                 break;
4663                         case CEE_LDLOCA:
4664                                 CHECK_STACK_OVF (1);
4665                                 NEW_LOCLOADA (cfg, ins, read16 (ip + 2));
4666                                 ins->cil_code = ip;
4667                                 *sp++ = ins;
4668                                 ip += 4;
4669                                 break;
4670                         case CEE_STLOC:
4671                                 CHECK_STACK (1);
4672                                 --sp;
4673                                 n = read16 (ip + 2);
4674                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4675                                 NEW_LOCSTORE (cfg, ins, n, *sp);
4676                                 ins->cil_code = ip;
4677                                 if (ins->opcode == CEE_STOBJ) {
4678                                         NEW_LOCLOADA (cfg, ins, n);
4679                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
4680                                 } else
4681                                         MONO_ADD_INS (bblock, ins);
4682                                 ip += 4;
4683                                 inline_costs += 1;
4684                                 break;
4685                         case CEE_LOCALLOC:
4686                                 CHECK_STACK (1);
4687                                 --sp;
4688                                 if (sp != stack_start) 
4689                                         goto unverified;
4690                                 MONO_INST_NEW (cfg, ins, 256 + ip [1]);
4691                                 ins->inst_left = *sp;
4692                                 ins->cil_code = ip;
4693
4694                                 if (header->init_locals)
4695                                         ins->flags |= MONO_INST_INIT;
4696
4697                                 *sp++ = ins;
4698                                 ip += 2;
4699                                 /* FIXME: set init flag if locals init is set in this method */
4700                                 break;
4701                         case CEE_ENDFILTER: {
4702                                 MonoExceptionClause *clause, *nearest;
4703                                 int cc, nearest_num;
4704
4705                                 CHECK_STACK (1);
4706                                 --sp;
4707                                 if ((sp != stack_start) || (sp [0]->type != STACK_I4)) 
4708                                         goto unverified;
4709                                 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
4710                                 ins->inst_left = *sp;
4711                                 ins->cil_code = ip;
4712                                 MONO_ADD_INS (bblock, ins);
4713                                 start_new_bblock = 1;
4714                                 ip += 2;
4715
4716                                 nearest = NULL;
4717                                 for (cc = 0; cc < header->num_clauses; ++cc) {
4718                                         clause = &header->clauses [cc];
4719                                         if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
4720                                             (!nearest || (clause->token_or_filter > nearest->token_or_filter))) {
4721                                                 nearest = clause;
4722                                                 nearest_num = cc;
4723                                         }
4724                                 }
4725                                 g_assert (nearest);
4726                                 filter_lengths [nearest_num] = (ip - header->code) -  nearest->token_or_filter;
4727
4728                                 break;
4729                         }
4730                         case CEE_UNALIGNED_:
4731                                 ins_flag |= MONO_INST_UNALIGNED;
4732                                 ip += 3;
4733                                 break;
4734                         case CEE_VOLATILE_:
4735                                 ins_flag |= MONO_INST_VOLATILE;
4736                                 ip += 2;
4737                                 break;
4738                         case CEE_TAIL_:
4739                                 ins_flag |= MONO_INST_TAILCALL;
4740                                 ip += 2;
4741                                 break;
4742                         case CEE_INITOBJ:
4743                                 CHECK_STACK (1);
4744                                 --sp;
4745                                 token = read32 (ip + 2);
4746                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
4747                                         klass = mono_method_get_wrapper_data (method, token);
4748                                 else
4749                                         klass = mono_class_get (image, token);
4750                                 handle_initobj (cfg, bblock, *sp, NULL, klass, stack_start, sp);
4751                                 ip += 6;
4752                                 inline_costs += 1;
4753                                 break;
4754                         case CEE_CPBLK:
4755                         case CEE_INITBLK: {
4756                                 MonoInst *iargs [3];
4757                                 CHECK_STACK (3);
4758                                 sp -= 3;
4759                                 iargs [0] = sp [0];
4760                                 iargs [1] = sp [1];
4761                                 iargs [2] = sp [2];
4762                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4763                                 if (ip [1] == CEE_CPBLK) {
4764                                         mono_emit_jit_icall (cfg, bblock, helper_memcpy, iargs, ip);
4765                                 } else {
4766                                         mono_emit_jit_icall (cfg, bblock, helper_memset, iargs, ip);
4767                                 }
4768                                 ip += 2;
4769                                 inline_costs += 1;
4770                                 break;
4771                         }
4772                         case CEE_RETHROW: {
4773                                 MonoInst *load;
4774                                 /* FIXME: check we are in a catch handler */
4775                                 NEW_TEMPLOAD (cfg, load, cfg->exvar->inst_c0);
4776                                 load->cil_code = ip;
4777                                 MONO_INST_NEW (cfg, ins, CEE_THROW);
4778                                 ins->inst_left = load;
4779                                 ins->cil_code = ip;
4780                                 MONO_ADD_INS (bblock, ins);
4781                                 sp = stack_start;
4782                                 start_new_bblock = 1;
4783                                 ip += 2;
4784                                 break;
4785                         }
4786                         case CEE_SIZEOF:
4787                                 CHECK_STACK_OVF (1);
4788                                 token = read32 (ip + 2);
4789                                 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC) {
4790                                         MonoType *type = mono_type_create_from_typespec (image, token);
4791                                         token = mono_type_size (type, &align);
4792                                         mono_metadata_free_type (type);
4793                                 } else {
4794                                         MonoClass *szclass = mono_class_get (image, token);
4795                                         mono_class_init (szclass);
4796                                         token = mono_class_value_size (szclass, &align);
4797                                 }
4798                                 NEW_ICONST (cfg, ins, token);
4799                                 ins->cil_code = ip;
4800                                 *sp++= ins;
4801                                 ip += 6;
4802                                 break;
4803                         case CEE_REFANYTYPE:
4804                                 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
4805                                 break;
4806                         default:
4807                                 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
4808                         }
4809                         break;
4810                 }
4811                 default:
4812                         g_error ("opcode 0x%02x not handled", *ip);
4813                 }
4814         }
4815         if (start_new_bblock != 1)
4816                 goto unverified;
4817
4818         bblock->cil_length = ip - bblock->cil_code;
4819         bblock->next_bb = end_bblock;
4820         link_bblock (cfg, bblock, end_bblock);
4821
4822         if (cfg->method == method && cfg->domainvar) {
4823                 MonoCallInst *call;
4824                 MonoInst *store;
4825
4826                 MONO_INST_NEW_CALL (cfg, call, CEE_CALL);
4827                 call->signature = helper_sig_domain_get;
4828                 call->inst.type = STACK_PTR;
4829                 call->fptr = mono_domain_get;
4830                 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, (MonoInst*)call);
4831                 
4832                 MONO_ADD_INS (init_localsbb, store);
4833         }
4834
4835         if (header->init_locals) {
4836                 MonoInst *store;
4837                 for (i = 0; i < header->num_locals; ++i) {
4838                         int t = header->locals [i]->type;
4839                         if (t == MONO_TYPE_VALUETYPE && header->locals [i]->data.klass->enumtype)
4840                                 t = header->locals [i]->data.klass->enum_basetype->type;
4841                         /* FIXME: use initobj for valuetypes, handle pointers, long, float. */
4842                         if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
4843                                 NEW_ICONST (cfg, ins, 0);
4844                                 NEW_LOCSTORE (cfg, store, i, ins);
4845                                 MONO_ADD_INS (init_localsbb, store);
4846                         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
4847                                 MONO_INST_NEW (cfg, ins, OP_I8CONST);
4848                                 ins->type = STACK_I8;
4849                                 ins->inst_l = 0;
4850                                 NEW_LOCSTORE (cfg, store, i, ins);
4851                                 MONO_ADD_INS (init_localsbb, store);
4852                         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
4853                                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
4854                                 ins->type = STACK_R8;
4855                                 ins->inst_p0 = (void*)&r8_0;
4856                                 NEW_LOCSTORE (cfg, store, i, ins);
4857                                 MONO_ADD_INS (init_localsbb, store);
4858                         } else if (t == MONO_TYPE_VALUETYPE) {
4859                                 NEW_LOCLOADA (cfg, ins, i);
4860                                 handle_initobj (cfg, init_localsbb, ins, NULL, mono_class_from_mono_type (header->locals [i]), NULL, NULL);
4861                                 break;
4862                         } else {
4863                                 NEW_PCONST (cfg, ins, NULL);
4864                                 NEW_LOCSTORE (cfg, store, i, ins);
4865                                 MONO_ADD_INS (init_localsbb, store);
4866                         }
4867                 }
4868         }
4869
4870         
4871         /* resolve backward branches in the middle of an existing basic block */
4872         for (tmp = bb_recheck; tmp; tmp = tmp->next) {
4873                 bblock = tmp->data;
4874                 /*g_print ("need recheck in %s at IL_%04x\n", method->name, bblock->cil_code - header->code);*/
4875                 tblock = find_previous (bbhash, start_bblock, bblock->cil_code);
4876                 if (tblock != start_bblock) {
4877                         int l;
4878                         split_bblock (cfg, tblock, bblock);
4879                         l = bblock->cil_code - header->code;
4880                         bblock->cil_length = tblock->cil_length - l;
4881                         tblock->cil_length = l;
4882                 } else {
4883                         g_print ("recheck failed.\n");
4884                 }
4885         }
4886
4887         /* we compute regions here, because the length of filter clauses is not known in advance.
4888         * It is computed in the CEE_ENDFILTER case in the above switch statement*/
4889         if (cfg->method == method) {
4890                 MonoBasicBlock *bb;
4891                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4892                         bb->region = mono_find_block_region (cfg, bb->real_offset, filter_lengths);
4893                         if (cfg->verbose_level > 2)
4894                                 g_print ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
4895                 }
4896         } else {
4897                 g_hash_table_destroy (bbhash);
4898         }
4899
4900         dont_inline = g_list_remove (dont_inline, method);
4901         return inline_costs;
4902
4903  inline_failure:
4904         if (cfg->method != method) 
4905                 g_hash_table_destroy (bbhash);
4906         dont_inline = g_list_remove (dont_inline, method);
4907         return -1;
4908
4909  unverified:
4910         if (cfg->method != method) 
4911                 g_hash_table_destroy (bbhash);
4912         g_error ("Invalid IL code at IL%04x in %s: %s\n", ip - header->code, 
4913                  mono_method_full_name (method, TRUE), mono_disasm_code_one (NULL, method, ip, NULL));
4914         dont_inline = g_list_remove (dont_inline, method);
4915         return -1;
4916 }
4917
4918 void
4919 mono_print_tree (MonoInst *tree) {
4920         int arity;
4921
4922         if (!tree)
4923                 return;
4924
4925         arity = mono_burg_arity [tree->opcode];
4926
4927         printf (" %s%s", arity?"(":"",  mono_inst_name (tree->opcode));
4928
4929         switch (tree->opcode) {
4930         case OP_ICONST:
4931                 printf ("[%d]", tree->inst_c0);
4932                 break;
4933         case OP_I8CONST:
4934                 printf ("[%lld]", tree->inst_l);
4935                 break;
4936         case OP_R8CONST:
4937                 printf ("[%f]", *(double*)tree->inst_p0);
4938                 break;
4939         case OP_R4CONST:
4940                 printf ("[%f]", *(float*)tree->inst_p0);
4941                 break;
4942         case OP_ARG:
4943         case OP_LOCAL:
4944                 printf ("[%d]", tree->inst_c0);
4945                 break;
4946         case OP_REGOFFSET:
4947                 printf ("[0x%x(%s)]", tree->inst_offset, mono_arch_regname (tree->inst_basereg));
4948                 break;
4949         case OP_REGVAR:
4950                 printf ("[%s]", mono_arch_regname (tree->dreg));
4951                 break;
4952         case CEE_NEWARR:
4953                 printf ("[%s]",  tree->inst_newa_class->name);
4954                 mono_print_tree (tree->inst_newa_len);
4955                 break;
4956         case CEE_CALL:
4957         case CEE_CALLVIRT:
4958         case OP_FCALL:
4959         case OP_FCALLVIRT:
4960         case OP_LCALL:
4961         case OP_LCALLVIRT:
4962         case OP_VCALL:
4963         case OP_VCALLVIRT:
4964         case OP_VOIDCALL:
4965         case OP_VOIDCALLVIRT: {
4966                 MonoCallInst *call = (MonoCallInst*)tree;
4967                 if (call->method)
4968                         printf ("[%s]", call->method->name);
4969                 break;
4970         }
4971         case OP_PHI: {
4972                 int i;
4973                 printf ("[%d (", tree->inst_c0);
4974                 for (i = 0; i < tree->inst_phi_args [0]; i++) {
4975                         if (i)
4976                                 printf (", ");
4977                         printf ("%d", tree->inst_phi_args [i + 1]);
4978                 }
4979                 printf (")]");
4980                 break;
4981         }
4982         case OP_RENAME:
4983         case OP_RETARG:
4984         case CEE_NOP:
4985         case CEE_JMP:
4986         case CEE_BREAK:
4987                 break;
4988         case CEE_BR:
4989                 printf ("[B%d]", tree->inst_target_bb->block_num);
4990                 break;
4991         case CEE_SWITCH:
4992         case CEE_ISINST:
4993         case CEE_CASTCLASS:
4994         case OP_OUTARG:
4995         case OP_CALL_REG:
4996         case OP_FCALL_REG:
4997         case OP_LCALL_REG:
4998         case OP_VCALL_REG:
4999         case OP_VOIDCALL_REG:
5000                 mono_print_tree (tree->inst_left);
5001                 break;
5002         case CEE_BNE_UN:
5003         case CEE_BEQ:
5004         case CEE_BLT:
5005         case CEE_BLT_UN:
5006         case CEE_BGT:
5007         case CEE_BGT_UN:
5008         case CEE_BGE:
5009         case CEE_BGE_UN:
5010         case CEE_BLE:
5011         case CEE_BLE_UN:
5012                 printf ("[B%dB%d]", tree->inst_true_bb->block_num, tree->inst_false_bb->block_num);
5013                 mono_print_tree (tree->inst_left);
5014                 break;
5015         default:
5016                 if (arity) {
5017                         mono_print_tree (tree->inst_left);
5018                         if (arity > 1)
5019                                 mono_print_tree (tree->inst_right);
5020                 }
5021                 break;
5022         }
5023
5024         if (arity)
5025                 printf (")");
5026 }
5027
5028 static void
5029 create_helper_signature (void)
5030 {
5031         /* FIXME: set call conv */
5032         /* MonoArray * mono_array_new (MonoDomain *domain, MonoClass *klass, gint32 len) */
5033         helper_sig_newarr = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
5034         helper_sig_newarr->params [0] = helper_sig_newarr->params [1] = &mono_defaults.int_class->byval_arg;
5035         helper_sig_newarr->ret = &mono_defaults.object_class->byval_arg;
5036         helper_sig_newarr->params [2] = &mono_defaults.int32_class->byval_arg;
5037         helper_sig_newarr->pinvoke = 1;
5038
5039         /* MonoArray * mono_array_new_specific (MonoVTable *vtable, guint32 len) */
5040         helper_sig_newarr_specific = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
5041         helper_sig_newarr_specific->params [0] = &mono_defaults.int_class->byval_arg;
5042         helper_sig_newarr_specific->params [1] = &mono_defaults.int32_class->byval_arg;
5043         helper_sig_newarr_specific->ret = &mono_defaults.object_class->byval_arg;
5044         helper_sig_newarr_specific->pinvoke = 1;
5045
5046         /* MonoObject * mono_object_new (MonoDomain *domain, MonoClass *klass) */
5047         helper_sig_object_new = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
5048         helper_sig_object_new->params [0] = helper_sig_object_new->params [1] = &mono_defaults.int_class->byval_arg;
5049         helper_sig_object_new->ret = &mono_defaults.object_class->byval_arg;
5050         helper_sig_object_new->pinvoke = 1;
5051
5052         /* MonoObject * mono_object_new_specific (MonoVTable *vtable) */
5053         helper_sig_object_new_specific = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
5054         helper_sig_object_new_specific->params [0] = &mono_defaults.int_class->byval_arg;
5055         helper_sig_object_new_specific->ret = &mono_defaults.object_class->byval_arg;
5056         helper_sig_object_new_specific->pinvoke = 1;
5057
5058         /* void* mono_method_compile (MonoMethod*) */
5059         helper_sig_compile = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
5060         helper_sig_compile->params [0] = helper_sig_compile->ret = &mono_defaults.int_class->byval_arg;
5061         helper_sig_compile->pinvoke = 1;
5062
5063         /* void* mono_ldvirtfn (MonoObject *, MonoMethod*) */
5064         helper_sig_compile_virt = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
5065         helper_sig_compile_virt->params [0] = &mono_defaults.object_class->byval_arg;
5066         helper_sig_compile_virt->params [1] = helper_sig_compile_virt->ret = &mono_defaults.int_class->byval_arg;
5067         helper_sig_compile_virt->pinvoke = 1;
5068
5069         /* MonoString* mono_ldstr (MonoDomain *domain, MonoImage *image, guint32 str_index) */
5070         helper_sig_ldstr = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
5071         helper_sig_ldstr->params [0] = helper_sig_ldstr->params [1] = &mono_defaults.int_class->byval_arg;
5072         helper_sig_ldstr->params [2] = &mono_defaults.int32_class->byval_arg;
5073         helper_sig_ldstr->ret = &mono_defaults.object_class->byval_arg;
5074         helper_sig_ldstr->pinvoke = 1;
5075
5076         /* MonoDomain *mono_domain_get (void) */
5077         helper_sig_domain_get = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
5078         helper_sig_domain_get->ret = &mono_defaults.int_class->byval_arg;
5079         helper_sig_domain_get->pinvoke = 1;
5080
5081         /* void* stelem_ref (MonoArray *, int index, MonoObject *) */
5082         helper_sig_stelem_ref = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
5083         helper_sig_stelem_ref->params [0] = &mono_defaults.array_class->byval_arg;
5084         helper_sig_stelem_ref->params [1] = &mono_defaults.int32_class->byval_arg;
5085         helper_sig_stelem_ref->params [2] = &mono_defaults.object_class->byval_arg;
5086         helper_sig_stelem_ref->ret = &mono_defaults.void_class->byval_arg;
5087         helper_sig_stelem_ref->pinvoke = 1;
5088
5089         /* long amethod (long, long) */
5090         helper_sig_long_long_long = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
5091         helper_sig_long_long_long->params [0] = helper_sig_long_long_long->params [1] = 
5092                 &mono_defaults.int64_class->byval_arg;
5093         helper_sig_long_long_long->ret = &mono_defaults.int64_class->byval_arg;
5094         helper_sig_long_long_long->pinvoke = 1;
5095
5096         /* object  amethod (intptr) */
5097         helper_sig_obj_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
5098         helper_sig_obj_ptr->params [0] = &mono_defaults.int_class->byval_arg;
5099         helper_sig_obj_ptr->ret = &mono_defaults.object_class->byval_arg;
5100         helper_sig_obj_ptr->pinvoke = 1;
5101
5102         /* void amethod (intptr) */
5103         helper_sig_void_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
5104         helper_sig_void_ptr->params [0] = &mono_defaults.int_class->byval_arg;
5105         helper_sig_void_ptr->ret = &mono_defaults.void_class->byval_arg;
5106         helper_sig_void_ptr->pinvoke = 1;
5107
5108         /* void amethod (MonoObject *obj) */
5109         helper_sig_void_obj = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
5110         helper_sig_void_obj->params [0] = &mono_defaults.object_class->byval_arg;
5111         helper_sig_void_obj->ret = &mono_defaults.void_class->byval_arg;
5112         helper_sig_void_obj->pinvoke = 1;
5113
5114         /* intptr amethod (void) */
5115         helper_sig_ptr_void = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
5116         helper_sig_ptr_void->ret = &mono_defaults.int_class->byval_arg;
5117         helper_sig_ptr_void->pinvoke = 1;
5118
5119         /* void  amethod (intptr, intptr) */
5120         helper_sig_void_ptr_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
5121         helper_sig_void_ptr_ptr->params [0] = &mono_defaults.int_class->byval_arg;
5122         helper_sig_void_ptr_ptr->params [1] = &mono_defaults.int_class->byval_arg;
5123         helper_sig_void_ptr_ptr->ret = &mono_defaults.void_class->byval_arg;
5124         helper_sig_void_ptr_ptr->pinvoke = 1;
5125
5126         /* void  amethod (intptr, intptr, intptr) */
5127         helper_sig_void_ptr_ptr_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
5128         helper_sig_void_ptr_ptr_ptr->params [0] = &mono_defaults.int_class->byval_arg;
5129         helper_sig_void_ptr_ptr_ptr->params [1] = &mono_defaults.int_class->byval_arg;
5130         helper_sig_void_ptr_ptr_ptr->params [2] = &mono_defaults.int_class->byval_arg;
5131         helper_sig_void_ptr_ptr_ptr->ret = &mono_defaults.void_class->byval_arg;
5132         helper_sig_void_ptr_ptr_ptr->pinvoke = 1;
5133
5134         /* intptr  amethod (intptr, intptr) */
5135         helper_sig_ptr_ptr_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
5136         helper_sig_ptr_ptr_ptr->params [0] = &mono_defaults.int_class->byval_arg;
5137         helper_sig_ptr_ptr_ptr->params [1] = &mono_defaults.int_class->byval_arg;
5138         helper_sig_ptr_ptr_ptr->ret = &mono_defaults.int_class->byval_arg;
5139         helper_sig_ptr_ptr_ptr->pinvoke = 1;
5140
5141         /* IntPtr  amethod (object) */
5142         helper_sig_ptr_obj = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
5143         helper_sig_ptr_obj->params [0] = &mono_defaults.object_class->byval_arg;
5144         helper_sig_ptr_obj->ret = &mono_defaults.int_class->byval_arg;
5145         helper_sig_ptr_obj->pinvoke = 1;
5146
5147         /* IntPtr  amethod (int) */
5148         helper_sig_ptr_int = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
5149         helper_sig_ptr_int->params [0] = &mono_defaults.int32_class->byval_arg;
5150         helper_sig_ptr_int->ret = &mono_defaults.int_class->byval_arg;
5151         helper_sig_ptr_int->pinvoke = 1;
5152
5153         /* long amethod (long, guint32) */
5154         helper_sig_long_long_int = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
5155         helper_sig_long_long_int->params [0] = &mono_defaults.int64_class->byval_arg;
5156         helper_sig_long_long_int->params [1] = &mono_defaults.int32_class->byval_arg;
5157         helper_sig_long_long_int->ret = &mono_defaults.int64_class->byval_arg;
5158         helper_sig_long_long_int->pinvoke = 1;
5159
5160         /* ulong amethod (double) */
5161         helper_sig_ulong_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
5162         helper_sig_ulong_double->params [0] = &mono_defaults.double_class->byval_arg;
5163         helper_sig_ulong_double->ret = &mono_defaults.uint64_class->byval_arg;
5164         helper_sig_ulong_double->pinvoke = 1;
5165
5166         /* long amethod (double) */
5167         helper_sig_long_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
5168         helper_sig_long_double->params [0] = &mono_defaults.double_class->byval_arg;
5169         helper_sig_long_double->ret = &mono_defaults.int64_class->byval_arg;
5170         helper_sig_long_double->pinvoke = 1;
5171
5172         /* uint amethod (double) */
5173         helper_sig_uint_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
5174         helper_sig_uint_double->params [0] = &mono_defaults.double_class->byval_arg;
5175         helper_sig_uint_double->ret = &mono_defaults.uint32_class->byval_arg;
5176         helper_sig_uint_double->pinvoke = 1;
5177
5178         /* int amethod (double) */
5179         helper_sig_int_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
5180         helper_sig_int_double->params [0] = &mono_defaults.double_class->byval_arg;
5181         helper_sig_int_double->ret = &mono_defaults.int32_class->byval_arg;
5182         helper_sig_int_double->pinvoke = 1;
5183
5184         /* void  initobj (intptr, int size) */
5185         helper_sig_initobj = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
5186         helper_sig_initobj->params [0] = &mono_defaults.int_class->byval_arg;
5187         helper_sig_initobj->params [1] = &mono_defaults.int32_class->byval_arg;
5188         helper_sig_initobj->ret = &mono_defaults.void_class->byval_arg;
5189         helper_sig_initobj->pinvoke = 1;
5190
5191         /* void  memcpy (intptr, intptr, int size) */
5192         helper_sig_memcpy = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
5193         helper_sig_memcpy->params [0] = &mono_defaults.int_class->byval_arg;
5194         helper_sig_memcpy->params [1] = &mono_defaults.int_class->byval_arg;
5195         helper_sig_memcpy->params [2] = &mono_defaults.int32_class->byval_arg;
5196         helper_sig_memcpy->ret = &mono_defaults.void_class->byval_arg;
5197         helper_sig_memcpy->pinvoke = 1;
5198
5199         /* void  memset (intptr, int val, int size) */
5200         helper_sig_memset = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
5201         helper_sig_memset->params [0] = &mono_defaults.int_class->byval_arg;
5202         helper_sig_memset->params [1] = &mono_defaults.int32_class->byval_arg;
5203         helper_sig_memset->params [2] = &mono_defaults.int32_class->byval_arg;
5204         helper_sig_memset->ret = &mono_defaults.void_class->byval_arg;
5205         helper_sig_memset->pinvoke = 1;
5206 }
5207
5208 static GHashTable *jit_icall_hash_name = NULL;
5209 static GHashTable *jit_icall_hash_addr = NULL;
5210
5211 MonoJitICallInfo *
5212 mono_find_jit_icall_by_name (const char *name)
5213 {
5214         g_assert (jit_icall_hash_name);
5215
5216         //printf ("lookup addr %s %p\n", name, g_hash_table_lookup (jit_icall_hash_name, name));
5217         return g_hash_table_lookup (jit_icall_hash_name, name);
5218 }
5219
5220 MonoJitICallInfo *
5221 mono_find_jit_icall_by_addr (gconstpointer addr)
5222 {
5223         g_assert (jit_icall_hash_addr);
5224
5225         return g_hash_table_lookup (jit_icall_hash_addr, (gpointer)addr);
5226 }
5227
5228 gconstpointer
5229 mono_icall_get_wrapper (MonoJitICallInfo* callinfo)
5230 {
5231         char *name;
5232         MonoMethod *wrapper;
5233         
5234         if (callinfo->wrapper)
5235                 return callinfo->wrapper;
5236         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
5237         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func);
5238         callinfo->wrapper = mono_jit_compile_method (wrapper);
5239         g_free (name);
5240         return callinfo->wrapper;
5241 }
5242
5243 MonoJitICallInfo *
5244 mono_register_jit_icall (gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean is_save)
5245 {
5246         MonoJitICallInfo *info;
5247         
5248         g_assert (func);
5249         g_assert (name);
5250
5251         if (!jit_icall_hash_name) {
5252                 jit_icall_hash_name = g_hash_table_new (g_str_hash, g_str_equal);
5253                 jit_icall_hash_addr = g_hash_table_new (NULL, NULL);
5254         }
5255
5256         if (g_hash_table_lookup (jit_icall_hash_name, name)) {
5257                 g_warning ("jit icall already defined \"%s\"\n", name);
5258                 g_assert_not_reached ();
5259         }
5260
5261         info = g_new (MonoJitICallInfo, 1);
5262         
5263         info->name = name;
5264         info->func = func;
5265         info->sig = sig;
5266                 
5267         if (is_save
5268 #ifdef MONO_USE_EXC_TABLES
5269             || mono_arch_has_unwind_info (func)
5270 #endif
5271             ) {
5272                 info->wrapper = func;
5273         } else {
5274                 info->wrapper = NULL;
5275                 mono_icall_get_wrapper (info);
5276         }
5277
5278         g_hash_table_insert (jit_icall_hash_name, (gpointer)info->name, info);
5279         g_hash_table_insert (jit_icall_hash_addr, (gpointer)func, info);
5280         if (func != info->wrapper)
5281                 g_hash_table_insert (jit_icall_hash_addr, (gpointer)info->wrapper, info);
5282
5283         return info;
5284 }
5285
5286 static GHashTable *emul_opcode_hash = NULL;
5287
5288 static MonoJitICallInfo *
5289 mono_find_jit_opcode_emulation (int opcode)
5290 {
5291         if  (emul_opcode_hash)
5292                 return g_hash_table_lookup (emul_opcode_hash, (gpointer)opcode);
5293         else
5294                 return NULL;
5295 }
5296
5297 void
5298 mono_register_opcode_emulation (int opcode, const char *name, MonoMethodSignature *sig, gpointer func, gboolean no_throw)
5299 {
5300         MonoJitICallInfo *info;
5301
5302         if (!emul_opcode_hash)
5303                 emul_opcode_hash = g_hash_table_new (NULL, NULL);
5304
5305         g_assert (!sig->hasthis);
5306         g_assert (sig->param_count < 3);
5307
5308         info = mono_register_jit_icall (func, name, sig, no_throw);
5309
5310         g_hash_table_insert (emul_opcode_hash, (gpointer)opcode, info);
5311 }
5312
5313 static void
5314 decompose_foreach (MonoInst *tree, gpointer data) 
5315 {
5316         static MonoJitICallInfo *newarr_info = NULL;
5317         static MonoJitICallInfo *newarr_specific_info = NULL;
5318         MonoJitICallInfo *info;
5319
5320         switch (tree->opcode) {
5321         case CEE_NEWARR: {
5322                 MonoCompile *cfg = data;
5323                 MonoInst *iargs [3];
5324
5325                 if (!newarr_info) {
5326                         newarr_info = mono_find_jit_icall_by_addr (mono_array_new);
5327                         g_assert (newarr_info);
5328                         newarr_specific_info = mono_find_jit_icall_by_addr (mono_array_new_specific);
5329                         g_assert (newarr_specific_info);
5330                 }
5331
5332                 if ((cfg->opt & MONO_OPT_SHARED) || mono_compile_aot) {
5333                         NEW_DOMAINCONST (cfg, iargs [0]);
5334                         NEW_CLASSCONST (cfg, iargs [1], tree->inst_newa_class);
5335                         iargs [2] = tree->inst_newa_len;
5336
5337                         info = newarr_info;
5338                 }
5339                 else {
5340                         MonoVTable *vtable = mono_class_vtable (cfg->domain, 
5341                                                                                                         mono_array_class_get (&tree->inst_newa_class->byval_arg, 1));
5342
5343                         NEW_PCONST (cfg, iargs [0], vtable);
5344                         iargs [1] = tree->inst_newa_len;
5345
5346                         info = newarr_specific_info;
5347                 }
5348
5349                 mono_emulate_opcode (cfg, tree, iargs, info);
5350                 break;
5351         }
5352
5353         default:
5354                 break;
5355         }
5356 }
5357
5358 void
5359 mono_inst_foreach (MonoInst *tree, MonoInstFunc func, gpointer data) {
5360
5361         switch (mono_burg_arity [tree->opcode]) {
5362         case 0: break;
5363         case 1: 
5364                 mono_inst_foreach (tree->inst_left, func, data);
5365                 break;
5366         case 2: 
5367                 mono_inst_foreach (tree->inst_left, func, data);
5368                 mono_inst_foreach (tree->inst_right, func, data);
5369                 break;
5370         default:
5371                 g_assert_not_reached ();
5372         }
5373         func (tree, data);
5374 }
5375
5376 #if 0
5377 static void
5378 mono_print_bb_code (MonoBasicBlock *bb) {
5379         if (bb->code) {
5380                 MonoInst *c = bb->code;
5381                 while (c) {
5382                         mono_print_tree (c);
5383                         g_print ("\n");
5384                         c = c->next;
5385                 }
5386         }
5387 }
5388 #endif
5389
5390 static void
5391 print_dfn (MonoCompile *cfg) {
5392         int i, j;
5393         char *code;
5394         MonoBasicBlock *bb;
5395
5396         g_print ("IR code for method %s\n", mono_method_full_name (cfg->method, TRUE));
5397
5398         for (i = 0; i < cfg->num_bblocks; ++i) {
5399                 bb = cfg->bblocks [i];
5400                 if (bb->cil_code) {
5401                         char* code1, *code2;
5402                         code1 = mono_disasm_code_one (NULL, cfg->method, bb->cil_code, NULL);
5403                         if (bb->last_ins->cil_code)
5404                                 code2 = mono_disasm_code_one (NULL, cfg->method, bb->last_ins->cil_code, NULL);
5405                         else
5406                                 code2 = g_strdup ("");
5407
5408                         code1 [strlen (code1) - 1] = 0;
5409                         code = g_strdup_printf ("%s -> %s", code1, code2);
5410                         g_free (code1);
5411                         g_free (code2);
5412                 } else
5413                         code = g_strdup ("\n");
5414                 g_print ("\nBB%d DFN%d (len: %d): %s", bb->block_num, i, bb->cil_length, code);
5415                 if (bb->code) {
5416                         MonoInst *c = bb->code;
5417                         while (c) {
5418                                 mono_print_tree (c);
5419                                 g_print ("\n");
5420                                 c = c->next;
5421                         }
5422                 } else {
5423
5424                 }
5425
5426                 g_print ("\tprev:");
5427                 for (j = 0; j < bb->in_count; ++j) {
5428                         g_print (" BB%d", bb->in_bb [j]->block_num);
5429                 }
5430                 g_print ("\t\tsucc:");
5431                 for (j = 0; j < bb->out_count; ++j) {
5432                         g_print (" BB%d", bb->out_bb [j]->block_num);
5433                 }
5434                 g_print ("\n\tidom: BB%d\n", bb->idom? bb->idom->block_num: -1);
5435
5436                 if (bb->idom)
5437                         g_assert (mono_bitset_test_fast (bb->dominators, bb->idom->dfn));
5438
5439                 if (bb->dominators)
5440                         mono_blockset_print (cfg, bb->dominators, "\tdominators", bb->idom? bb->idom->dfn: -1);
5441                 if (bb->dfrontier)
5442                         mono_blockset_print (cfg, bb->dfrontier, "\tdfrontier", -1);
5443                 g_free (code);
5444         }
5445
5446         g_print ("\n");
5447 }
5448
5449 /*
5450  * returns the offset used by spillvar. It allocates a new
5451  * spill variable if necessary. 
5452  */
5453 int
5454 mono_spillvar_offset (MonoCompile *cfg, int spillvar)
5455 {
5456         MonoSpillInfo **si, *info;
5457         int i = 0;
5458
5459         si = &cfg->spill_info; 
5460         
5461         while (i <= spillvar) {
5462
5463                 if (!*si) {
5464                         *si = info = mono_mempool_alloc (cfg->mempool, sizeof (MonoSpillInfo));
5465                         info->next = NULL;
5466                         cfg->stack_offset -= sizeof (gpointer);
5467                         info->offset = cfg->stack_offset;
5468                 }
5469
5470                 if (i == spillvar)
5471                         return (*si)->offset;
5472
5473                 i++;
5474                 si = &(*si)->next;
5475         }
5476
5477         g_assert_not_reached ();
5478         return 0;
5479 }
5480
5481 void
5482 mono_bblock_add_inst (MonoBasicBlock *bb, MonoInst *inst)
5483 {
5484         inst->next = NULL;
5485         if (bb->last_ins) {
5486                 g_assert (bb->code);
5487                 bb->last_ins->next = inst;
5488                 bb->last_ins = inst;
5489         } else {
5490                 bb->last_ins = bb->code = inst;
5491         }
5492 }
5493
5494 void
5495 mono_destroy_compile (MonoCompile *cfg)
5496 {
5497         //mono_mempool_stats (cfg->mempool);
5498         g_hash_table_destroy (cfg->bb_hash);
5499         if (cfg->rs)
5500                 mono_regstate_free (cfg->rs);
5501         mono_mempool_destroy (cfg->mempool);
5502         g_list_free (cfg->ldstr_list);
5503
5504         g_free (cfg->varinfo);
5505         g_free (cfg->vars);
5506         g_free (cfg);
5507 }
5508
5509 gpointer 
5510 mono_get_lmf_addr (void)
5511 {
5512         MonoJitTlsData *jit_tls;        
5513
5514         if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
5515                 return &jit_tls->lmf;
5516
5517         g_assert_not_reached ();
5518         return NULL;
5519 }
5520
5521 /**
5522  * mono_thread_abort:
5523  * @obj: exception object
5524  *
5525  * abort the thread, print exception information and stack trace
5526  */
5527 static void
5528 mono_thread_abort (MonoObject *obj)
5529 {
5530         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
5531         
5532         g_free (jit_tls);
5533
5534         ExitThread (-1);
5535 }
5536
5537 static void
5538 mono_thread_start_cb (guint32 tid, gpointer stack_start, gpointer func)
5539 {
5540         MonoJitTlsData *jit_tls;
5541         MonoLMF *lmf;
5542
5543         jit_tls = g_new0 (MonoJitTlsData, 1);
5544
5545         TlsSetValue (mono_jit_tls_id, jit_tls);
5546
5547         jit_tls->abort_func = mono_thread_abort;
5548         jit_tls->end_of_stack = stack_start;
5549
5550         lmf = g_new0 (MonoLMF, 1);
5551         lmf->ebp = -1;
5552
5553         jit_tls->lmf = lmf;
5554 }
5555
5556 void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
5557
5558 static void
5559 mono_thread_abort_dummy (MonoObject *obj)
5560 {
5561   if (mono_thread_attach_aborted_cb)
5562     mono_thread_attach_aborted_cb (obj);
5563   else
5564     mono_thread_abort (obj);
5565 }
5566
5567 static void
5568 mono_thread_attach_cb (guint32 tid, gpointer stack_start)
5569 {
5570         MonoJitTlsData *jit_tls;
5571         MonoLMF *lmf;
5572
5573         jit_tls = g_new0 (MonoJitTlsData, 1);
5574
5575         TlsSetValue (mono_jit_tls_id, jit_tls);
5576
5577         jit_tls->abort_func = mono_thread_abort_dummy;
5578         jit_tls->end_of_stack = stack_start;
5579
5580         lmf = g_new0 (MonoLMF, 1);
5581         lmf->ebp = -1;
5582
5583         jit_tls->lmf = lmf;
5584 }
5585
5586 void
5587 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
5588 {
5589         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
5590
5591         ji->ip.i = ip;
5592         ji->type = type;
5593         ji->data.target = target;
5594         ji->next = cfg->patch_info;
5595
5596         cfg->patch_info = ji;
5597 }
5598
5599 void
5600 mono_remove_patch_info (MonoCompile *cfg, int ip)
5601 {
5602         MonoJumpInfo **ji = &cfg->patch_info;
5603
5604         while (*ji) {
5605                 if ((*ji)->ip.i == ip)
5606                         *ji = (*ji)->next;
5607                 else
5608                         ji = &((*ji)->next);
5609         }
5610 }
5611
5612 static void
5613 dec_foreach (MonoInst *tree, MonoCompile *cfg) {
5614         MonoJitICallInfo *info;
5615
5616         switch (mono_burg_arity [tree->opcode]) {
5617         case 0: break;
5618         case 1: 
5619                 dec_foreach (tree->inst_left, cfg);
5620
5621                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
5622                         MonoInst *iargs [2];
5623                 
5624                         iargs [0] = tree->inst_left;
5625
5626                         mono_emulate_opcode (cfg, tree, iargs, info);
5627                         return;
5628                 }
5629
5630                 break;
5631         case 2:
5632                 if (tree->opcode == OP_LMUL
5633                                 && (cfg->opt & MONO_OPT_INTRINS)
5634                                 && (tree->inst_left->opcode == CEE_CONV_I8 
5635                                         || tree->inst_left->opcode == CEE_CONV_U8)
5636                                 && tree->inst_left->inst_left->type == STACK_I4
5637                                 && (tree->inst_right->opcode == CEE_CONV_I8 
5638                                         || tree->inst_right->opcode == CEE_CONV_U8)
5639                                 && tree->inst_right->inst_left->type == STACK_I4) {
5640                         tree->opcode = (tree->inst_left->opcode == CEE_CONV_I8 ? OP_BIGMUL: OP_BIGMUL_UN);
5641                         tree->inst_left = tree->inst_left->inst_left;
5642                         tree->inst_right = tree->inst_right->inst_left;
5643                         dec_foreach (tree, cfg);
5644                 } else if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
5645                         MonoInst *iargs [2];
5646                 
5647                         iargs [0] = tree->inst_i0;
5648                         iargs [1] = tree->inst_i1;
5649                 
5650                         mono_emulate_opcode (cfg, tree, iargs, info);
5651
5652                         dec_foreach (iargs [0], cfg);
5653                         dec_foreach (iargs [1], cfg);
5654                         return;
5655                 } else {
5656                         dec_foreach (tree->inst_left, cfg);
5657                         dec_foreach (tree->inst_right, cfg);
5658                 }
5659                 break;
5660         default:
5661                 g_assert_not_reached ();
5662         }
5663         decompose_foreach (tree, cfg);
5664 }
5665
5666 static void
5667 decompose_pass (MonoCompile *cfg) {
5668         MonoBasicBlock *bb;
5669
5670         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5671                 MonoInst *tree;
5672                 cfg->cbb = bb;
5673                 cfg->prev_ins = NULL;
5674                 for (tree = cfg->cbb->code; tree; tree = tree->next) {
5675                         dec_foreach (tree, cfg);
5676                         cfg->prev_ins = tree;
5677                 }
5678         }
5679 }
5680
5681 static void
5682 nullify_basic_block (MonoBasicBlock *bb) 
5683 {
5684         bb->in_count = 0;
5685         bb->out_count = 0;
5686         bb->in_bb = NULL;
5687         bb->out_bb = NULL;
5688         bb->next_bb = NULL;
5689         bb->code = bb->last_ins = NULL;
5690         bb->cil_code = NULL;
5691 }
5692
5693 static void 
5694 replace_out_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
5695 {
5696         int i;
5697
5698         for (i = 0; i < bb->out_count; i++) {
5699                 MonoBasicBlock *ob = bb->out_bb [i];
5700                 if (ob == orig) {
5701                         if (!repl) {
5702                                 if (bb->out_count > 1) {
5703                                         bb->out_bb [i] = bb->out_bb [bb->out_count - 1];
5704                                 }
5705                                 bb->out_count--;
5706                         } else {
5707                                 bb->out_bb [i] = repl;
5708                         }
5709                 }
5710         }
5711 }
5712
5713 static void 
5714 replace_in_block (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl)
5715 {
5716         int i;
5717
5718         for (i = 0; i < bb->in_count; i++) {
5719                 MonoBasicBlock *ib = bb->in_bb [i];
5720                 if (ib == orig) {
5721                         if (!repl) {
5722                                 if (bb->in_count > 1) {
5723                                         bb->in_bb [i] = bb->in_bb [bb->in_count - 1];
5724                                 }
5725                                 bb->in_count--;
5726                         } else {
5727                                 bb->in_bb [i] = repl;
5728                         }
5729                 }
5730         }
5731 }
5732
5733 static void 
5734 replace_basic_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
5735 {
5736         int i, j;
5737
5738         for (i = 0; i < bb->out_count; i++) {
5739                 MonoBasicBlock *ob = bb->out_bb [i];
5740                 for (j = 0; j < ob->in_count; j++) {
5741                         if (ob->in_bb [j] == orig) {
5742                                 ob->in_bb [j] = repl;
5743                         }
5744                 }
5745         }
5746
5747 }
5748
5749
5750 static void
5751 merge_basic_blocks (MonoBasicBlock *bb, MonoBasicBlock *bbn) 
5752 {
5753         bb->out_count = bbn->out_count;
5754         bb->out_bb = bbn->out_bb;
5755
5756         replace_basic_block (bb, bbn, bb);
5757
5758         if (bb->last_ins) {
5759                 if (bbn->code) {
5760                         bb->last_ins->next = bbn->code;
5761                         bb->last_ins = bbn->last_ins;
5762                 }
5763         } else {
5764                 bb->code = bbn->code;
5765                 bb->last_ins = bbn->last_ins;
5766         }
5767         bb->next_bb = bbn->next_bb;
5768         nullify_basic_block (bbn);
5769 }
5770
5771 static void
5772 optimize_branches (MonoCompile *cfg) {
5773         int i, changed = FALSE;
5774         MonoBasicBlock *bb, *bbn;
5775
5776         do {
5777                 changed = FALSE;
5778
5779                 /* we skip the entry block (exit is handled specially instead ) */
5780                 for (bb = cfg->bb_entry->next_bb; bb; bb = bb->next_bb) {
5781
5782                         /* dont touch code inside exception clauses */
5783                         if (bb->region != -1)
5784                                 continue;
5785
5786                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
5787                                 if (cfg->verbose_level > 2)
5788                                         g_print ("nullify block triggered %d\n", bbn->block_num);
5789
5790                                 bb->next_bb = bbn->next_bb;
5791
5792                                 for (i = 0; i < bbn->out_count; i++)
5793                                         replace_in_block (bbn->out_bb [i], bbn, NULL);
5794
5795                                 nullify_basic_block (bbn);                      
5796                                 changed = TRUE;
5797                         }
5798
5799                         if (bb->out_count == 1) {
5800                                 bbn = bb->out_bb [0];
5801
5802                                 /* conditional branches where true and false targets are the same can be also replaced with CEE_BR */
5803                                 if (bb->last_ins && MONO_IS_COND_BRANCH (bb->last_ins->opcode)) {
5804                                         bb->last_ins->opcode = CEE_BR;
5805                                         bb->last_ins->inst_target_bb = bb->last_ins->inst_true_bb;
5806                                         changed = TRUE;
5807                                         if (cfg->verbose_level > 2)
5808                                                 g_print ("cond branch removal triggered in %d %d\n", bb->block_num, bb->out_count);
5809                                 }
5810
5811                                 if (bb->region == bbn->region && bb->next_bb == bbn) {
5812                                         /* the block are in sequence anyway ... */
5813
5814                                         /* branches to the following block can be removed */
5815                                         if (bb->last_ins && bb->last_ins->opcode == CEE_BR) {
5816                                                 bb->last_ins->opcode = CEE_NOP;
5817                                                 changed = TRUE;
5818                                                 if (cfg->verbose_level > 2)
5819                                                         g_print ("br removal triggered %d -> %d\n", bb->block_num, bbn->block_num);
5820                                         }
5821
5822                                         if (bbn->in_count == 1) {
5823
5824                                                 if (bbn != cfg->bb_exit) {
5825                                                         if (cfg->verbose_level > 2)
5826                                                                 g_print ("block merge triggered %d -> %d\n", bb->block_num, bbn->block_num);
5827                                                         merge_basic_blocks (bb, bbn);
5828                                                         changed = TRUE;
5829                                                 }
5830
5831                                                 //mono_print_bb_code (bb);
5832                                         }
5833                                 }                               
5834                         }
5835                 }
5836         } while (changed);
5837
5838         do {
5839                 changed = FALSE;
5840
5841                 /* we skip the entry block (exit is handled specially instead ) */
5842                 for (bb = cfg->bb_entry->next_bb; bb; bb = bb->next_bb) {
5843
5844                         /* dont touch code inside exception clauses */
5845                         if (bb->region != -1)
5846                                 continue;
5847
5848                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
5849                                 if (cfg->verbose_level > 2) {
5850                                         g_print ("nullify block triggered %d\n", bbn->block_num);
5851                                 }
5852                                 bb->next_bb = bbn->next_bb;
5853
5854                                 for (i = 0; i < bbn->out_count; i++)
5855                                         replace_in_block (bbn->out_bb [i], bbn, NULL);
5856
5857                                 nullify_basic_block (bbn);                      
5858                                 changed = TRUE;
5859                                 break;
5860                         }
5861
5862
5863                         if (bb->out_count == 1) {
5864                                 bbn = bb->out_bb [0];
5865
5866                                 if (bb->last_ins && bb->last_ins->opcode == CEE_BR) {
5867                                         bbn = bb->last_ins->inst_target_bb;
5868                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR &&
5869                                             bbn->code->inst_target_bb->region == bb->region) {
5870                                                 
5871                                                 if (cfg->verbose_level > 2)
5872                                                         g_print ("in %s branch to branch triggered %d -> %d\n", cfg->method->name, 
5873                                                                  bb->block_num, bbn->block_num);
5874                                                 
5875                                                 replace_basic_block (bb, bb->out_bb [0], bbn->code->inst_target_bb);
5876                                                 bb->last_ins->inst_target_bb = bbn->code->inst_target_bb;
5877                                                 changed = TRUE;
5878                                                 break;
5879                                         }
5880                                 }
5881                         } else if (bb->out_count == 2) {
5882                                 if (bb->last_ins && MONO_IS_COND_BRANCH (bb->last_ins->opcode)) {
5883                                         bbn = bb->last_ins->inst_true_bb;
5884                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR &&
5885                                             bbn->code->inst_target_bb->region == bb->region) {
5886                                                 if (cfg->verbose_level > 2)             
5887                                                         g_print ("cbranch1 to branch triggered %d -> (%d) %d (0x%02x)\n", 
5888                                                                  bb->block_num, bbn->block_num, bbn->code->inst_target_bb->block_num, 
5889                                                                  bbn->code->opcode);
5890
5891                                                 bb->last_ins->inst_true_bb = bbn->code->inst_target_bb;
5892
5893                                                 replace_in_block (bbn, bb, NULL);
5894                                                 if (!bbn->in_count)
5895                                                         replace_in_block (bbn->code->inst_target_bb, bbn, bb);
5896                                                 replace_out_block (bb, bbn, bbn->code->inst_target_bb);
5897
5898                                                 link_bblock (cfg, bb, bbn->code->inst_target_bb);
5899
5900                                                 changed = TRUE;
5901                                                 break;
5902                                         }
5903
5904                                         bbn = bb->last_ins->inst_false_bb;
5905                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR &&
5906                                             bbn->code->inst_target_bb->region == bb->region) {
5907                                                 if (cfg->verbose_level > 2)
5908                                                         g_print ("cbranch2 to branch triggered %d -> (%d) %d (0x%02x)\n", 
5909                                                                  bb->block_num, bbn->block_num, bbn->code->inst_target_bb->block_num, 
5910                                                                  bbn->code->opcode);
5911
5912                                                 bb->last_ins->inst_false_bb = bbn->code->inst_target_bb;
5913
5914                                                 replace_in_block (bbn, bb, NULL);
5915                                                 if (!bbn->in_count)
5916                                                         replace_in_block (bbn->code->inst_target_bb, bbn, bb);
5917                                                 replace_out_block (bb, bbn, bbn->code->inst_target_bb);
5918
5919                                                 link_bblock (cfg, bb, bbn->code->inst_target_bb);
5920
5921                                                 changed = TRUE;
5922                                                 break;
5923                                         }
5924                                 }
5925                         }
5926                 }
5927         } while (changed);
5928
5929 }
5930
5931 static void
5932 mono_compile_create_vars (MonoCompile *cfg)
5933 {
5934         MonoMethodSignature *sig;
5935         MonoMethodHeader *header;
5936         int i;
5937
5938         header = ((MonoMethodNormal *)cfg->method)->header;
5939
5940         sig = cfg->method->signature;
5941         
5942         if (!MONO_TYPE_IS_VOID (sig->ret)) {
5943                 cfg->ret = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
5944                 cfg->ret->opcode = OP_RETARG;
5945                 cfg->ret->inst_vtype = sig->ret;
5946                 cfg->ret->klass = mono_class_from_mono_type (sig->ret);
5947         }
5948
5949         if (sig->hasthis)
5950                 mono_compile_create_var (cfg, &cfg->method->klass->this_arg, OP_ARG);
5951
5952         for (i = 0; i < sig->param_count; ++i)
5953                 mono_compile_create_var (cfg, sig->params [i], OP_ARG);
5954
5955         cfg->locals_start = cfg->num_varinfo;
5956
5957         for (i = 0; i < header->num_locals; ++i)
5958                 mono_compile_create_var (cfg, header->locals [i], OP_LOCAL);
5959 }
5960
5961 #if 0
5962 static void
5963 mono_print_code (MonoCompile *cfg)
5964 {
5965         MonoBasicBlock *bb;
5966         
5967         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5968                 MonoInst *tree = bb->code;      
5969
5970                 if (!tree)
5971                         continue;
5972                 
5973                 g_print ("CODE BLOCK %d (nesting %d):\n", bb->block_num, bb->nesting);
5974
5975                 for (; tree; tree = tree->next) {
5976                         mono_print_tree (tree);
5977                         g_print ("\n");
5978                 }
5979
5980                 if (bb->last_ins)
5981                         bb->last_ins->next = NULL;
5982         }
5983 }
5984 #endif
5985
5986 extern const char * const mono_burg_rule_string [];
5987
5988 static void
5989 emit_state (MonoCompile *cfg, MBState *state, int goal)
5990 {
5991         MBState *kids [10];
5992         int ern = mono_burg_rule (state, goal);
5993         const guint16 *nts = mono_burg_nts [ern];
5994         MBEmitFunc emit;
5995
5996         //g_print ("rule: %s\n", mono_burg_rule_string [ern]);
5997         switch (goal) {
5998         case MB_NTERM_reg:
5999                 //if (state->reg2)
6000                 //      state->reg1 = state->reg2; /* chain rule */
6001                 //else
6002                 state->reg1 = mono_regstate_next_int (cfg->rs);
6003                 //g_print ("alloc symbolic R%d (reg2: R%d) in block %d\n", state->reg1, state->reg2, cfg->cbb->block_num);
6004                 break;
6005         case MB_NTERM_lreg:
6006                 state->reg1 = mono_regstate_next_int (cfg->rs);
6007                 state->reg2 = mono_regstate_next_int (cfg->rs);
6008                 break;
6009         case MB_NTERM_freg:
6010                 state->reg1 = mono_regstate_next_float (cfg->rs);
6011                 break;
6012         default:
6013                 /* do nothing */
6014                 break;
6015         }
6016         if (nts [0]) {
6017                 mono_burg_kids (state, ern, kids);
6018
6019                 emit_state (cfg, kids [0], nts [0]);
6020                 if (nts [1]) {
6021                         emit_state (cfg, kids [1], nts [1]);
6022                         if (nts [2]) {
6023                                 g_assert (!nts [3]);
6024                                 emit_state (cfg, kids [2], nts [2]);
6025                         }
6026                 }
6027         }
6028
6029 //      g_print ("emit: %s (%p)\n", mono_burg_rule_string [ern], state);
6030         if ((emit = mono_burg_func [ern]))
6031                 emit (state, state->tree, cfg); 
6032 }
6033
6034 #define DEBUG_SELECTION
6035
6036 static void 
6037 mini_select_instructions (MonoCompile *cfg)
6038 {
6039         static int reverse_map [] = {
6040                 CEE_BNE_UN, CEE_BLT, CEE_BLE, CEE_BGT, CEE_BGE,
6041                 CEE_BEQ, CEE_BLT_UN, CEE_BLE_UN, CEE_BGT_UN, CEE_BGE_UN
6042         };
6043         static int reverse_fmap [] = {
6044                 OP_FBNE_UN, OP_FBLT, OP_FBLE, OP_FBGT, OP_FBGE,
6045                 OP_FBEQ, OP_FBLT_UN, OP_FBLE_UN, OP_FBGT_UN, OP_FBGE_UN
6046         };
6047         static int reverse_lmap [] = {
6048                 OP_LBNE_UN, OP_LBLT, OP_LBLE, OP_LBGT, OP_LBGE,
6049                 OP_LBEQ, OP_LBLT_UN, OP_LBLE_UN, OP_LBGT_UN, OP_LBGE_UN
6050         };
6051
6052         MonoBasicBlock *bb;
6053         
6054         cfg->state_pool = mono_mempool_new ();
6055         cfg->rs = mono_regstate_new ();
6056
6057         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
6058                 if (bb->last_ins && MONO_IS_COND_BRANCH (bb->last_ins->opcode) &&
6059                     bb->next_bb != bb->last_ins->inst_false_bb) {
6060
6061                         if (bb->next_bb ==  bb->last_ins->inst_true_bb) {
6062                                 MonoBasicBlock *tmp =  bb->last_ins->inst_true_bb;
6063                                 bb->last_ins->inst_true_bb = bb->last_ins->inst_false_bb;
6064                                 bb->last_ins->inst_false_bb = tmp;
6065                                 
6066                                 if (bb->last_ins->opcode >= CEE_BEQ && bb->last_ins->opcode <= CEE_BLT_UN) {
6067                                         bb->last_ins->opcode = reverse_map [bb->last_ins->opcode - CEE_BEQ];
6068                                 } else if (bb->last_ins->opcode >= OP_FBEQ && bb->last_ins->opcode <= OP_FBLT_UN) {
6069                                         bb->last_ins->opcode = reverse_fmap [bb->last_ins->opcode - OP_FBEQ];
6070                                 } else if (bb->last_ins->opcode >= OP_LBEQ && bb->last_ins->opcode <= OP_LBLT_UN) {
6071                                         bb->last_ins->opcode = reverse_lmap [bb->last_ins->opcode - OP_LBEQ];
6072                                 }
6073                         } else {                        
6074                                 MonoInst *inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
6075                                 inst->opcode = CEE_BR;
6076                                 inst->inst_target_bb = bb->last_ins->inst_false_bb;
6077                                 mono_bblock_add_inst (bb, inst);
6078                         }
6079                 }
6080         }
6081
6082 #ifdef DEBUG_SELECTION
6083         if (cfg->verbose_level >= 4) {
6084         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
6085                 MonoInst *tree = bb->code;      
6086                 g_print ("DUMP BLOCK %d:\n", bb->block_num);
6087                 if (!tree)
6088                         continue;
6089                 for (; tree; tree = tree->next) {
6090                         mono_print_tree (tree);
6091                         g_print ("\n");
6092                 }
6093         }
6094         }
6095 #endif
6096
6097         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
6098                 MonoInst *tree = bb->code, *next;       
6099                 MBState *mbstate;
6100
6101                 if (!tree)
6102                         continue;
6103                 bb->code = NULL;
6104                 bb->last_ins = NULL;
6105                 
6106                 cfg->cbb = bb;
6107                 mono_regstate_reset (cfg->rs);
6108
6109 #ifdef DEBUG_SELECTION
6110                 if (cfg->verbose_level >= 3)
6111                         g_print ("LABEL BLOCK %d:\n", bb->block_num);
6112 #endif
6113                 for (; tree; tree = next) {
6114                         next = tree->next;
6115 #ifdef DEBUG_SELECTION
6116                         if (cfg->verbose_level >= 3) {
6117                                 mono_print_tree (tree);
6118                                 g_print ("\n");
6119                         }
6120 #endif
6121
6122                         if (!(mbstate = mono_burg_label (tree, cfg))) {
6123                                 g_warning ("unabled to label tree %p", tree);
6124                                 mono_print_tree (tree);
6125                                 g_print ("\n");                         
6126                                 g_assert_not_reached ();
6127                         }
6128                         emit_state (cfg, mbstate, MB_NTERM_stmt);
6129                 }
6130                 bb->max_ireg = cfg->rs->next_vireg;
6131                 bb->max_freg = cfg->rs->next_vfreg;
6132
6133                 if (bb->last_ins)
6134                         bb->last_ins->next = NULL;
6135
6136                 mono_mempool_empty (cfg->state_pool); 
6137         }
6138         mono_mempool_destroy (cfg->state_pool); 
6139 }
6140
6141 void
6142 mono_codegen (MonoCompile *cfg)
6143 {
6144         MonoJumpInfo *patch_info;
6145         MonoBasicBlock *bb;
6146         int i, max_epilog_size;
6147         guint8 *code;
6148
6149         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
6150                 cfg->spill_count = 0;
6151                 /* we reuse dfn here */
6152                 /* bb->dfn = bb_count++; */
6153                 mono_arch_local_regalloc (cfg, bb);
6154         }
6155
6156         if (cfg->prof_options & MONO_PROFILE_COVERAGE)
6157                 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, cfg->num_bblocks);
6158
6159         code = mono_arch_emit_prolog (cfg);
6160
6161         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
6162                 code = mono_arch_instrument_prolog (cfg, mono_profiler_method_enter, code, FALSE);
6163
6164         cfg->code_len = code - cfg->native_code;
6165         cfg->prolog_end = cfg->code_len;
6166
6167         mono_debug_open_method (cfg);
6168              
6169         /* emit code all basic blocks */
6170         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
6171                 bb->native_offset = cfg->code_len;
6172                 mono_arch_output_basic_block (cfg, bb);
6173         }
6174         cfg->bb_exit->native_offset = cfg->code_len;
6175
6176         code = cfg->native_code + cfg->code_len;
6177
6178         max_epilog_size = mono_arch_max_epilog_size (cfg);
6179
6180         /* we always allocate code in cfg->domain->code_mp to increase locality */
6181         cfg->code_size = cfg->code_len + max_epilog_size;
6182         /* fixme: align to MONO_ARCH_CODE_ALIGNMENT */
6183         code = mono_mempool_alloc (cfg->domain->code_mp, cfg->code_size);
6184         memcpy (code, cfg->native_code, cfg->code_len);
6185         g_free (cfg->native_code);
6186         cfg->native_code = code;
6187         code = cfg->native_code + cfg->code_len;
6188   
6189         /* g_assert (((int)cfg->native_code & (MONO_ARCH_CODE_ALIGNMENT - 1)) == 0); */
6190
6191         cfg->epilog_begin = cfg->code_len;
6192
6193         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
6194                 code = mono_arch_instrument_epilog (cfg, mono_profiler_method_leave, code, FALSE);
6195
6196         cfg->code_len = code - cfg->native_code;
6197
6198         mono_arch_emit_epilog (cfg);
6199
6200         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6201                 switch (patch_info->type) {
6202                 case MONO_PATCH_INFO_ABS: {
6203                         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (patch_info->data.target);
6204                         if (info) {
6205                                 //printf ("TEST %s %p\n", info->name, patch_info->data.target);
6206                                 patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
6207                                 patch_info->data.name = info->name;
6208                         }
6209                         break;
6210                 }
6211                 case MONO_PATCH_INFO_SWITCH: {
6212                         gpointer *table = g_new (gpointer, patch_info->table_size);
6213                         patch_info->ip.i = patch_info->ip.label->inst_c0;
6214                         for (i = 0; i < patch_info->table_size; i++) {
6215                                 table [i] = (gpointer)patch_info->data.table [i]->native_offset;
6216                         }
6217                         patch_info->data.target = table;
6218                         break;
6219                 }
6220                 default:
6221                         /* do nothing */
6222                         break;
6223                 }
6224         }
6225        
6226         if (cfg->verbose_level > 1)
6227                 g_print ("Method %s::%s emmitted at %p to %p\n", cfg->method->klass->name, 
6228                          cfg->method->name, cfg->native_code, cfg->native_code + cfg->code_len);
6229
6230         mono_arch_patch_code (cfg->method, cfg->domain, cfg->native_code, cfg->patch_info);
6231
6232         mono_debug_close_method (cfg);
6233 }
6234
6235 static void
6236 mono_cprop_copy_values (MonoCompile *cfg, MonoInst *tree, MonoInst **acp)
6237 {
6238         MonoInst *cp;
6239         int arity;
6240
6241         if (tree->ssa_op == MONO_SSA_LOAD && (tree->inst_i0->opcode == OP_LOCAL || tree->inst_i0->opcode == OP_ARG) && 
6242             (cp = acp [tree->inst_i0->inst_c0]) && !tree->inst_i0->flags) {
6243
6244                 if (cp->opcode == OP_ICONST) {
6245                         if (cfg->opt & MONO_OPT_CONSPROP) {
6246                                 //{ static int c = 0; printf ("CCOPY %d %d %s\n", c++, cp->inst_c0, mono_method_full_name (cfg->method, TRUE)); }
6247                                 *tree = *cp;
6248                         }
6249                 } else {
6250                         if (tree->inst_i0->inst_vtype->type == cp->inst_vtype->type) {
6251                                 if (cfg->opt & MONO_OPT_COPYPROP) {
6252                                         //{ static int c = 0; printf ("VCOPY %d\n", ++c); }
6253                                         tree->inst_i0 = cp;
6254                                 } 
6255                         }
6256                 } 
6257         } else {
6258                 arity = mono_burg_arity [tree->opcode];
6259
6260                 if (arity) {
6261                         mono_cprop_copy_values (cfg, tree->inst_i0, acp);
6262                         if (cfg->opt & MONO_OPT_CFOLD)
6263                                 mono_constant_fold_inst (tree, NULL); 
6264                         if (arity > 1) {
6265                                 mono_cprop_copy_values (cfg, tree->inst_i1, acp);
6266                                 if (cfg->opt & MONO_OPT_CFOLD)
6267                                         mono_constant_fold_inst (tree, NULL); 
6268                         }
6269                         mono_constant_fold_inst (tree, NULL); 
6270                 }
6271         }
6272 }
6273
6274 static void
6275 mono_cprop_invalidate_values (MonoInst *tree, MonoInst **acp, int acp_size)
6276 {
6277         int arity;
6278
6279         switch (tree->opcode) {
6280         case CEE_STIND_I:
6281         case CEE_STIND_I1:
6282         case CEE_STIND_I2:
6283         case CEE_STIND_I4:
6284         case CEE_STIND_REF:
6285         case CEE_STIND_I8:
6286         case CEE_STIND_R4:
6287         case CEE_STIND_R8:
6288         case CEE_STOBJ:
6289                 if (tree->ssa_op == MONO_SSA_NOP) {
6290                         memset (acp, 0, sizeof (MonoInst *) * acp_size);
6291                         return;
6292                 }
6293
6294                 break;
6295         case CEE_CALL:
6296         case OP_CALL_REG:
6297         case CEE_CALLVIRT:
6298         case OP_LCALL_REG:
6299         case OP_LCALLVIRT:
6300         case OP_LCALL:
6301         case OP_FCALL_REG:
6302         case OP_FCALLVIRT:
6303         case OP_FCALL:
6304         case OP_VCALL_REG:
6305         case OP_VCALLVIRT:
6306         case OP_VCALL:
6307         case OP_VOIDCALL_REG:
6308         case OP_VOIDCALLVIRT:
6309         case OP_VOIDCALL: {
6310                 MonoCallInst *call = (MonoCallInst *)tree;
6311                 MonoMethodSignature *sig = call->signature;
6312                 int i, byref = FALSE;
6313
6314                 for (i = 0; i < sig->param_count; i++) {
6315                         if (sig->params [i]->byref) {
6316                                 byref = TRUE;
6317                                 break;
6318                         }
6319                 }
6320
6321                 if (byref)
6322                         memset (acp, 0, sizeof (MonoInst *) * acp_size);
6323
6324                 return;
6325         }
6326         default:
6327                 break;
6328         }
6329
6330         arity = mono_burg_arity [tree->opcode];
6331
6332         switch (arity) {
6333         case 0:
6334                 break;
6335         case 1:
6336                 mono_cprop_invalidate_values (tree->inst_i0, acp, acp_size);
6337                 break;
6338         case 2:
6339                 mono_cprop_invalidate_values (tree->inst_i0, acp, acp_size);
6340                 mono_cprop_invalidate_values (tree->inst_i1, acp, acp_size);
6341                 break;
6342         default:
6343                 g_assert_not_reached ();
6344         }
6345 }
6346
6347 static void
6348 mono_local_cprop_bb (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst **acp, int acp_size)
6349 {
6350         MonoInst *tree = bb->code;      
6351         int i;
6352
6353         if (!tree)
6354                 return;
6355
6356         for (; tree; tree = tree->next) {
6357
6358                 mono_cprop_copy_values (cfg, tree, acp);
6359
6360                 mono_cprop_invalidate_values (tree, acp, acp_size);
6361
6362                 if (tree->ssa_op == MONO_SSA_STORE  && 
6363                     (tree->inst_i0->opcode == OP_LOCAL || tree->inst_i0->opcode == OP_ARG)) {
6364                         MonoInst *i1 = tree->inst_i1;
6365
6366                         acp [tree->inst_i0->inst_c0] = NULL;
6367
6368                         for (i = 0; i < acp_size; i++) {
6369                                 if (acp [i] && acp [i]->opcode != OP_ICONST && 
6370                                     acp [i]->inst_c0 == tree->inst_i0->inst_c0) {
6371                                         acp [i] = NULL;
6372                                 }
6373                         }
6374
6375                         if (i1->opcode == OP_ICONST) {
6376                                 acp [tree->inst_i0->inst_c0] = i1;
6377                                 //printf ("DEF1 BB%d %d\n", bb->block_num,tree->inst_i0->inst_c0);
6378                         }
6379                         if (i1->ssa_op == MONO_SSA_LOAD && 
6380                             (i1->inst_i0->opcode == OP_LOCAL || i1->inst_i0->opcode == OP_ARG) &&
6381                             (i1->inst_i0->inst_c0 != tree->inst_i0->inst_c0)) {
6382                                 acp [tree->inst_i0->inst_c0] = i1->inst_i0;
6383                                 //printf ("DEF2 BB%d %d %d\n", bb->block_num,tree->inst_i0->inst_c0,i1->inst_i0->inst_c0);
6384                         }
6385                 }
6386
6387                 /*
6388                   if (tree->opcode == CEE_BEQ) {
6389                   g_assert (tree->inst_i0->opcode == OP_COMPARE);
6390                   if (tree->inst_i0->inst_i0->opcode == OP_ICONST &&
6391                   tree->inst_i0->inst_i1->opcode == OP_ICONST) {
6392                   
6393                   tree->opcode = CEE_BR;
6394                   if (tree->inst_i0->inst_i0->opcode == tree->inst_i0->inst_i1->opcode) {
6395                   tree->inst_target_bb = tree->inst_true_bb;
6396                   } else {
6397                   tree->inst_target_bb = tree->inst_false_bb;
6398                   }
6399                   }
6400                   }
6401                 */
6402         }
6403 }
6404
6405 static void
6406 mono_local_cprop (MonoCompile *cfg)
6407 {
6408         MonoBasicBlock *bb;
6409         MonoInst **acp;
6410
6411         acp = alloca (sizeof (MonoInst *) * cfg->num_varinfo);
6412
6413         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
6414                 memset (acp, 0, sizeof (MonoInst *) * cfg->num_varinfo);
6415                 mono_local_cprop_bb (cfg, bb, acp, cfg->num_varinfo);
6416         }
6417 }
6418
6419 MonoCompile*
6420 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, int parts)
6421 {
6422         MonoMethodHeader *header = ((MonoMethodNormal *)method)->header;
6423         guint8 *ip = (guint8 *)header->code;
6424         MonoCompile *cfg;
6425         MonoJitInfo *jinfo;
6426         int dfn = 0, i, code_size_ratio;
6427
6428         mono_jit_stats.methods_compiled++;
6429         if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)
6430                 mono_profiler_method_jit (method);
6431
6432         cfg = g_new0 (MonoCompile, 1);
6433         cfg->method = method;
6434         cfg->mempool = mono_mempool_new ();
6435         cfg->opt = opts;
6436         cfg->prof_options = mono_profiler_get_events ();
6437         cfg->bb_hash = g_hash_table_new (g_direct_hash, NULL);
6438         cfg->domain = domain;
6439         cfg->verbose_level = mini_verbose;
6440         cfg->intvars = mono_mempool_alloc0 (cfg->mempool, sizeof (guint16) * STACK_MAX * 
6441                                             ((MonoMethodNormal *)method)->header->max_stack);
6442
6443         /*
6444          * create MonoInst* which represents arguments and local variables
6445          */
6446         mono_compile_create_vars (cfg);
6447
6448         if (cfg->verbose_level > 2)
6449                 g_print ("converting method %s\n", mono_method_full_name (method, TRUE));
6450
6451         if ((i = mono_method_to_ir (cfg, method, NULL, NULL, cfg->locals_start, NULL, NULL, NULL, 0, FALSE)) < 0) {
6452                 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
6453                         mono_profiler_method_end_jit (method, MONO_PROFILE_FAILED);
6454                 mono_destroy_compile (cfg);
6455                 return NULL;
6456         }
6457
6458         mono_jit_stats.basic_blocks += cfg->num_bblocks;
6459         mono_jit_stats.max_basic_blocks = MAX (cfg->num_bblocks, mono_jit_stats.max_basic_blocks);
6460
6461         if (cfg->num_varinfo > 2000) {
6462                 /* 
6463                  * we disable some optimizations if there are too many variables
6464                  * because JIT time may become too expensive. The actual number needs 
6465                  * to be tweaked and eventually the non-linear algorithms should be fixed.
6466                  */
6467                 cfg->opt &= ~ (MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP);
6468                 cfg->disable_ssa = TRUE;
6469         }
6470         /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/
6471
6472         /* Depth-first ordering on basic blocks */
6473         cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
6474
6475         if (cfg->opt & MONO_OPT_BRANCH)
6476                 optimize_branches (cfg);
6477
6478         df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
6479         if (cfg->num_bblocks != dfn + 1) {
6480                 MonoBasicBlock *bb;
6481
6482                 cfg->num_bblocks = dfn + 1;
6483
6484                 if (!header->clauses) {
6485                         /* remove unreachable code, because the code in them may be 
6486                          * inconsistent  (access to dead variables for example) */
6487                         for (bb = cfg->bb_entry; bb;) {
6488                                 MonoBasicBlock *bbn = bb->next_bb;
6489
6490                                 if (bbn && bbn->region == -1 && !bbn->dfn) {
6491                                         if (cfg->verbose_level > 1)
6492                                                 g_print ("found unreachabel code in BB%d\n", bbn->block_num);
6493                                         bb->next_bb = bbn->next_bb;
6494                                         nullify_basic_block (bbn);                      
6495                                 } else {
6496                                         bb = bb->next_bb;
6497                                 }
6498                         }
6499                 }
6500         }
6501
6502         if (cfg->opt & MONO_OPT_LOOP) {
6503                 mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM);
6504                 mono_compute_natural_loops (cfg);
6505         }
6506
6507
6508         /* after method_to_ir */
6509         if (parts == 1)
6510                 return cfg;
6511
6512 //#define DEBUGSSA "logic_run"
6513 #define DEBUGSSA_CLASS "Tests"
6514 #ifdef DEBUGSSA
6515
6516
6517         if (!header->num_clauses && !cfg->disable_ssa) {
6518                 mono_local_cprop (cfg);
6519                 mono_ssa_compute (cfg);
6520         }
6521 #else 
6522
6523         /* fixme: add all optimizations which requires SSA */
6524         if (cfg->opt & (MONO_OPT_DEADCE)) {
6525                 if (!(cfg->comp_done & MONO_COMP_SSA) && !header->num_clauses && !cfg->disable_ssa) {
6526                         mono_local_cprop (cfg);
6527                         mono_ssa_compute (cfg);
6528
6529                         if (cfg->verbose_level >= 2) {
6530                                 print_dfn (cfg);
6531                         }
6532                 }
6533         }
6534 #endif
6535
6536         /* after SSA translation */
6537         if (parts == 2)
6538                 return cfg;
6539
6540         if ((cfg->opt & MONO_OPT_CONSPROP) ||  (cfg->opt & MONO_OPT_COPYPROP)) {
6541                 if (cfg->comp_done & MONO_COMP_SSA) {
6542                         mono_ssa_cprop (cfg);
6543                 } else {
6544                         mono_local_cprop (cfg);
6545                 }
6546         }
6547
6548         if (cfg->comp_done & MONO_COMP_SSA) {                   
6549                 mono_ssa_deadce (cfg);
6550
6551                 //mono_ssa_strength_reduction (cfg);
6552
6553                 mono_ssa_remove (cfg);
6554
6555                 if (cfg->opt & MONO_OPT_BRANCH)
6556                         optimize_branches (cfg);
6557         }
6558
6559         /* after SSA removal */
6560         if (parts == 3)
6561                 return cfg;
6562         
6563         decompose_pass (cfg);
6564
6565         /* FIXME: disabled with exception clauses: bug #42136 */
6566         if ((!header->num_clauses) && (cfg->opt & MONO_OPT_LINEARS)) {
6567                 GList *vars, *regs;
6568
6569                 /* fixme: maybe we can avoid to compute livenesss here if already computed ? */
6570                 cfg->comp_done &= ~MONO_COMP_LIVENESS;
6571                 if (!(cfg->comp_done & MONO_COMP_LIVENESS))
6572                         mono_analyze_liveness (cfg);
6573
6574                 if ((vars = mono_arch_get_allocatable_int_vars (cfg))) {
6575                         regs = mono_arch_get_global_int_regs (cfg);
6576                         mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs);
6577                 }
6578         }
6579
6580         //mono_print_code (cfg);
6581
6582        //print_dfn (cfg);
6583         
6584         /* variables are allocated after decompose, since decompose could create temps */
6585         mono_arch_allocate_vars (cfg);
6586
6587         if (cfg->opt & MONO_OPT_CFOLD)
6588                 mono_constant_fold (cfg);
6589
6590         mini_select_instructions (cfg);
6591
6592         mono_codegen (cfg);
6593         if (cfg->verbose_level >= 2) {
6594                 char *id =  mono_method_full_name (cfg->method, FALSE);
6595                 mono_disassemble_code (cfg->native_code, cfg->code_len, id + 3);
6596                 g_free (id);
6597         }
6598         
6599         jinfo = mono_mempool_alloc0 (cfg->domain->mp, sizeof (MonoJitInfo));
6600
6601         jinfo = g_new0 (MonoJitInfo, 1);
6602         jinfo->method = method;
6603         jinfo->code_start = cfg->native_code;
6604         jinfo->code_size = cfg->code_len;
6605         jinfo->used_regs = cfg->used_int_regs;
6606
6607         if (header->num_clauses) {
6608                 int i;
6609
6610                 jinfo->exvar_offset = cfg->exvar? cfg->exvar->inst_offset: 0;
6611                 jinfo->num_clauses = header->num_clauses;
6612                 jinfo->clauses = mono_mempool_alloc0 (cfg->domain->mp, 
6613                         sizeof (MonoJitExceptionInfo) * header->num_clauses);
6614
6615                 for (i = 0; i < header->num_clauses; i++) {
6616                         MonoExceptionClause *ec = &header->clauses [i];
6617                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
6618                         MonoBasicBlock *tblock;
6619
6620                         ei->flags = ec->flags;
6621
6622                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
6623                                 tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->token_or_filter);
6624                                 g_assert (tblock);
6625                                 ei->data.filter = cfg->native_code + tblock->native_offset;
6626                         } else {
6627                                 ei->data.token = ec->token_or_filter;
6628                         }
6629
6630                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->try_offset);
6631                         g_assert (tblock);
6632                         ei->try_start = cfg->native_code + tblock->native_offset;
6633                         g_assert (tblock->native_offset);
6634                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->try_offset + ec->try_len);
6635                         g_assert (tblock);
6636                         ei->try_end = cfg->native_code + tblock->native_offset;
6637                         g_assert (tblock->native_offset);
6638                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->handler_offset);
6639                         g_assert (tblock);
6640                         ei->handler_start = cfg->native_code + tblock->native_offset;
6641                 }
6642         }
6643
6644         mono_jit_info_table_add (cfg->domain, jinfo);
6645
6646         /* collect statistics */
6647         mono_jit_stats.allocated_code_size += cfg->code_len;
6648         code_size_ratio = cfg->code_len;
6649         if (code_size_ratio > mono_jit_stats.biggest_method_size) {
6650                         mono_jit_stats.biggest_method_size = code_size_ratio;
6651                         mono_jit_stats.biggest_method = method;
6652         }
6653         code_size_ratio = (code_size_ratio * 100) / ((MonoMethodNormal *)method)->header->code_size;
6654         if (code_size_ratio > mono_jit_stats.max_code_size_ratio) {
6655                 mono_jit_stats.max_code_size_ratio = code_size_ratio;
6656                 mono_jit_stats.max_ratio_method = method;
6657         }
6658         mono_jit_stats.native_code_size += cfg->code_len;
6659
6660         if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
6661                 mono_profiler_method_end_jit (method, MONO_PROFILE_OK);
6662
6663         return cfg;
6664 }
6665
6666 static gpointer
6667 mono_jit_compile_method (MonoMethod *method)
6668 {
6669         /* FIXME: later copy the code from mono */
6670         MonoDomain *target_domain, *domain = mono_domain_get ();
6671         MonoCompile *cfg;
6672         GHashTable *jit_code_hash;
6673         gpointer code;
6674
6675         if (default_opt & MONO_OPT_SHARED)
6676                 target_domain = mono_root_domain;
6677         else 
6678                 target_domain = domain;
6679
6680         jit_code_hash = target_domain->jit_code_hash;
6681
6682         if ((code = g_hash_table_lookup (jit_code_hash, method))) {
6683                 mono_jit_stats.methods_lookups++;
6684                 return code;
6685         }
6686
6687 #ifdef MONO_USE_AOT_COMPILER
6688         if (!mono_compile_aot) {
6689                 mono_class_init (method->klass);
6690                 if ((code = mono_aot_get_method (method))) {
6691                         g_hash_table_insert (jit_code_hash, method, code);
6692                         return code;
6693                 }
6694         }
6695 #endif
6696
6697         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
6698             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
6699                 if (!method->info) {
6700                         MonoMethod *nm;
6701
6702                         if (!method->addr && (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
6703                                 mono_lookup_pinvoke_call (method);
6704 #ifdef MONO_USE_EXC_TABLES
6705                         if (mono_method_blittable (method)) {
6706                                 method->info = method->addr;
6707                         } else {
6708 #endif
6709                                 nm = mono_marshal_get_native_wrapper (method);
6710                                 method->info = mono_compile_method (nm);
6711
6712                                 //if (mono_debug_format != MONO_DEBUG_FORMAT_NONE) 
6713                                 //mono_debug_add_wrapper (method, nm);
6714 #ifdef MONO_USE_EXC_TABLES
6715                         }
6716 #endif
6717                 }
6718                 return method->info;
6719         } else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
6720                 const char *name = method->name;
6721                 MonoMethod *nm;
6722
6723                 if (method->klass->parent == mono_defaults.multicastdelegate_class) {
6724                         if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
6725                                 /* FIXME: uhm, we need a wrapper to handle exceptions? */
6726                                 return (gpointer)mono_delegate_ctor;
6727                         } else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
6728                                 nm = mono_marshal_get_delegate_invoke (method);
6729                                 return mono_jit_compile_method (nm);
6730                         } else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
6731                                 nm = mono_marshal_get_delegate_begin_invoke (method);
6732                                 return mono_jit_compile_method (nm);
6733                         } else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
6734                                 nm = mono_marshal_get_delegate_end_invoke (method);
6735                                 return mono_jit_compile_method (nm);
6736                         }
6737                 }
6738                 return NULL;
6739         }
6740
6741         cfg = mini_method_compile (method, default_opt, target_domain, 0);
6742         code = cfg->native_code;
6743         mono_destroy_compile (cfg);
6744
6745         g_hash_table_insert (jit_code_hash, method, code);
6746
6747         if (target_domain->jump_target_hash) {
6748                 MonoJumpInfo patch_info;
6749                 GSList *list, *tmp;
6750                 list = g_hash_table_lookup (target_domain->jump_target_hash, method);
6751                 if (list) {
6752                         patch_info.next = NULL;
6753                         patch_info.ip.i = 0;
6754                         patch_info.type = MONO_PATCH_INFO_METHOD_JUMP;
6755                         patch_info.data.method = method;
6756                         g_hash_table_remove (target_domain->jump_target_hash, method);
6757                 }
6758                 for (tmp = list; tmp; tmp = tmp->next)
6759                         mono_arch_patch_code (NULL, target_domain, tmp->data, &patch_info);
6760                 g_slist_free (list);
6761         }
6762         /* make sure runtime_init is called */
6763         mono_runtime_class_init (mono_class_vtable (target_domain, method->klass));
6764
6765         return code;
6766 }
6767
6768 /**
6769  * mono_jit_runtime_invoke:
6770  * @method: the method to invoke
6771  * @obj: this pointer
6772  * @params: array of parameter values.
6773  * @exc: used to catch exceptions objects
6774  */
6775 static MonoObject*
6776 mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
6777 {
6778         MonoMethod *invoke;
6779         MonoObject *(*runtime_invoke) (MonoObject *this, void **params, MonoObject **exc);
6780         invoke = mono_marshal_get_runtime_invoke (method);
6781         runtime_invoke = mono_jit_compile_method (invoke);      
6782         return runtime_invoke (obj, params, exc);
6783 }
6784
6785 #ifdef PLATFORM_WIN32
6786 #define GET_CONTEXT \
6787         struct sigcontext *ctx = (struct sigcontext*)_dummy;
6788 #else
6789 #define GET_CONTEXT \
6790         void **_p = (void **)&_dummy; \
6791         struct sigcontext *ctx = (struct sigcontext *)++_p;
6792 #endif
6793
6794 static void
6795 sigfpe_signal_handler (int _dummy)
6796 {
6797         MonoException *exc;
6798         GET_CONTEXT
6799
6800         exc = mono_get_exception_divide_by_zero ();
6801         
6802         mono_arch_handle_exception (ctx, exc, FALSE);
6803 }
6804
6805 static void
6806 sigill_signal_handler (int _dummy)
6807 {
6808         MonoException *exc;
6809         GET_CONTEXT
6810         exc = mono_get_exception_execution_engine ("SIGILL");
6811         
6812         mono_arch_handle_exception (ctx, exc, FALSE);
6813 }
6814
6815 static void
6816 sigsegv_signal_handler (int _dummy)
6817 {
6818         MonoException *exc;
6819         GET_CONTEXT
6820
6821         exc = mono_get_exception_null_reference ();
6822         
6823         mono_arch_handle_exception (ctx, exc, FALSE);
6824 }
6825
6826 static void
6827 sigusr1_signal_handler (int _dummy)
6828 {
6829         MonoThread *thread;
6830         GET_CONTEXT
6831         
6832         thread = mono_thread_current ();
6833         
6834         g_assert (thread->abort_exc);
6835
6836         mono_arch_handle_exception (ctx, thread->abort_exc, FALSE);
6837 }
6838
6839 static void
6840 mono_runtime_install_handlers (void)
6841 {
6842 #ifndef PLATFORM_WIN32
6843         struct sigaction sa;
6844 #endif
6845
6846 #ifdef PLATFORM_WIN32
6847         win32_seh_init();
6848         win32_seh_set_handler(SIGFPE, sigfpe_signal_handler);
6849         win32_seh_set_handler(SIGILL, sigill_signal_handler);
6850         win32_seh_set_handler(SIGSEGV, sigsegv_signal_handler);
6851 #else /* !PLATFORM_WIN32 */
6852
6853         /* libpthreads has its own implementation of sigaction(),
6854          * but it seems to work well with our current exception
6855          * handlers. If not we must call syscall directly instead 
6856          * of sigaction */
6857         
6858         /* catch SIGFPE */
6859         sa.sa_handler = sigfpe_signal_handler;
6860         sigemptyset (&sa.sa_mask);
6861         sa.sa_flags = 0;
6862         //g_assert (syscall (SYS_sigaction, SIGFPE, &sa, NULL) != -1);
6863         g_assert (sigaction (SIGFPE, &sa, NULL) != -1);
6864
6865         /* catch SIGILL */
6866         sa.sa_handler = sigill_signal_handler;
6867         sigemptyset (&sa.sa_mask);
6868         sa.sa_flags = 0;
6869         //g_assert (syscall (SYS_sigaction, SIGILL, &sa, NULL) != -1);
6870         g_assert (sigaction (SIGILL, &sa, NULL) != -1);
6871
6872         /* catch thread abort signal */
6873         sa.sa_handler = sigusr1_signal_handler;
6874         sigemptyset (&sa.sa_mask);
6875         sa.sa_flags = 0;
6876         //g_assert (syscall (SYS_sigaction, SIGILL, &sa, NULL) != -1);
6877         g_assert (sigaction (mono_thread_get_abort_signal (), &sa, NULL) != -1);
6878
6879 #if 1
6880         /* catch SIGSEGV */
6881         sa.sa_handler = sigsegv_signal_handler;
6882         sigemptyset (&sa.sa_mask);
6883         sa.sa_flags = 0;
6884         //g_assert (syscall (SYS_sigaction, SIGSEGV, &sa, NULL) != -1);
6885         g_assert (sigaction (SIGSEGV, &sa, NULL) != -1);
6886 #endif
6887 #endif /* PLATFORM_WIN32 */
6888 }
6889
6890 /* mono_jit_create_remoting_trampoline:
6891  * @method: pointer to the method info
6892  *
6893  * Creates a trampoline which calls the remoting functions. This
6894  * is used in the vtable of transparent proxies.
6895  * 
6896  * Returns: a pointer to the newly created code 
6897  */
6898 static gpointer
6899 mono_jit_create_remoting_trampoline (MonoMethod *method)
6900 {
6901         MonoMethod *nm;
6902         guint8 *addr = NULL;
6903
6904         if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) || 
6905             (method->signature->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class))) {
6906                 nm = mono_marshal_get_remoting_invoke (method);
6907                 addr = mono_compile_method (nm);
6908         } else {
6909                 addr = mono_compile_method (method);
6910         }
6911         return addr;
6912 }
6913
6914 static CRITICAL_SECTION ms;
6915
6916 MonoDomain *
6917 mini_init (const char *filename)
6918 {
6919         MonoDomain *domain;
6920
6921         mono_arch_cpu_init ();
6922
6923         metadata_section = &ms;
6924         InitializeCriticalSection (metadata_section);
6925
6926         mono_jit_tls_id = TlsAlloc ();
6927         mono_thread_start_cb (GetCurrentThreadId (), (gpointer)-1, NULL);
6928
6929         mono_burg_init ();
6930
6931         mono_runtime_install_handlers ();
6932
6933         mono_install_compile_method (mono_jit_compile_method);
6934         mono_install_trampoline (mono_arch_create_jit_trampoline);
6935         mono_install_remoting_trampoline (mono_jit_create_remoting_trampoline);
6936         mono_install_runtime_invoke (mono_jit_runtime_invoke);
6937         mono_install_handler (mono_arch_get_throw_exception ());
6938         mono_install_stack_walk (mono_jit_walk_stack);
6939         mono_install_get_config_dir ();
6940
6941         domain = mono_init (filename);
6942         mono_init_icall ();
6943
6944         mono_add_internal_call ("System.Diagnostics.StackFrame::get_frame_info", 
6945                                 ves_icall_get_frame_info);
6946         mono_add_internal_call ("System.Diagnostics.StackTrace::get_trace", 
6947                                 ves_icall_get_trace);
6948         mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers", 
6949                                 mono_runtime_install_handlers);
6950
6951
6952         create_helper_signature ();
6953
6954         mono_arch_register_lowlevel_calls ();
6955         mono_register_jit_icall (mono_profiler_method_enter, "mono_profiler_method_enter", NULL, TRUE);
6956         mono_register_jit_icall (mono_profiler_method_leave, "mono_profiler_method_leave", NULL, TRUE);
6957
6958         mono_register_jit_icall (mono_get_lmf_addr, "mono_get_lmf_addr", helper_sig_ptr_void, TRUE);
6959         mono_register_jit_icall (mono_domain_get, "mono_domain_get", helper_sig_domain_get, TRUE);
6960
6961         /* fixme: we cant hanlde vararg methods this way, because the signature is not constant */
6962         //mono_register_jit_icall (ves_array_element_address, "ves_array_element_address", NULL);
6963         //mono_register_jit_icall (mono_array_new_va, "mono_array_new_va", NULL);
6964
6965         mono_register_jit_icall (mono_arch_get_throw_exception (), "mono_arch_throw_exception", helper_sig_void_obj, TRUE);
6966         mono_register_jit_icall (mono_arch_get_throw_exception_by_name (), "mono_arch_throw_exception_by_name", 
6967                                  helper_sig_void_ptr, TRUE);
6968
6969         /* 
6970          * NOTE, NOTE, NOTE, NOTE:
6971          * when adding emulation for some opcodes, remember to also add a dummy
6972          * rule to the burg files, because we need the arity information to be correct.
6973          */
6974         mono_register_opcode_emulation (OP_LMUL, "__emul_lmul", helper_sig_long_long_long, mono_llmult, TRUE);
6975         mono_register_opcode_emulation (OP_LMUL_OVF_UN, "__emul_lmul_ovf_un", helper_sig_long_long_long, mono_llmult_ovf_un, FALSE);
6976         mono_register_opcode_emulation (OP_LMUL_OVF, "__emul_lmul_ovf", helper_sig_long_long_long, mono_llmult_ovf, FALSE);
6977         mono_register_opcode_emulation (OP_LDIV, "__emul_ldiv", helper_sig_long_long_long, mono_lldiv, FALSE);
6978         mono_register_opcode_emulation (OP_LDIV_UN, "__emul_ldiv_un", helper_sig_long_long_long, mono_lldiv_un, FALSE);
6979         mono_register_opcode_emulation (OP_LREM, "__emul_lrem", helper_sig_long_long_long, mono_llrem, FALSE);
6980         mono_register_opcode_emulation (OP_LREM_UN, "__emul_lrem_un", helper_sig_long_long_long, mono_llrem_un, FALSE);
6981
6982         mono_register_opcode_emulation (OP_LSHL, "__emul_lshl", helper_sig_long_long_int, mono_lshl, TRUE);
6983         mono_register_opcode_emulation (OP_LSHR, "__emul_lshr", helper_sig_long_long_int, mono_lshr, TRUE);
6984         mono_register_opcode_emulation (OP_LSHR_UN, "__emul_lshr_un", helper_sig_long_long_int, mono_lshr_un, TRUE);
6985
6986         mono_register_opcode_emulation (OP_FCONV_TO_U8, "__emul_fconv_to_u8", helper_sig_ulong_double, mono_fconv_u8, FALSE);
6987         mono_register_opcode_emulation (OP_FCONV_TO_U4, "__emul_fconv_to_u4", helper_sig_uint_double, mono_fconv_u4, FALSE);
6988         mono_register_opcode_emulation (OP_FCONV_TO_OVF_I8, "__emul_fconv_to_ovf_i8", helper_sig_long_double, mono_fconv_ovf_i8, TRUE);
6989         mono_register_opcode_emulation (OP_FCONV_TO_OVF_U8, "__emul_fconv_to_ovf_u8", helper_sig_ulong_double, mono_fconv_ovf_u8, TRUE);
6990
6991 #if SIZEOF_VOID_P == 4
6992         mono_register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", helper_sig_uint_double, mono_fconv_u4, TRUE);
6993 #else
6994 #warning "fixme: add opcode emulation"
6995 #endif
6996
6997         /* other jit icalls */
6998         mono_register_jit_icall (mono_class_static_field_address , "mono_class_static_field_address", 
6999                                  helper_sig_ptr_ptr_ptr, FALSE);
7000         mono_register_jit_icall (mono_ldtoken_wrapper, "mono_ldtoken_wrapper", helper_sig_ptr_ptr_ptr, FALSE);
7001         mono_register_jit_icall (mono_threads_get_static_data, "mono_threads_get_static_data", helper_sig_ptr_int, FALSE);
7002         mono_register_jit_icall (mono_ldstr, "mono_ldstr", helper_sig_ldstr, FALSE);
7003         mono_register_jit_icall (helper_memcpy, "helper_memcpy", helper_sig_memcpy, FALSE);
7004         mono_register_jit_icall (helper_memset, "helper_memset", helper_sig_memset, FALSE);
7005         mono_register_jit_icall (helper_initobj, "helper_initobj", helper_sig_initobj, FALSE);
7006         mono_register_jit_icall (helper_stelem_ref, "helper_stelem_ref", helper_sig_stelem_ref, FALSE);
7007         mono_register_jit_icall (mono_object_new, "mono_object_new", helper_sig_object_new, FALSE);
7008         mono_register_jit_icall (mono_object_new_specific, "mono_object_new_specific", helper_sig_object_new_specific, FALSE);
7009         mono_register_jit_icall (mono_object_new_fast, "mono_object_new_fast", helper_sig_object_new_specific, FALSE);
7010         mono_register_jit_icall (mono_array_new, "mono_array_new", helper_sig_newarr, FALSE);
7011         mono_register_jit_icall (mono_array_new_specific, "mono_array_new_specific", helper_sig_newarr_specific, FALSE);
7012         mono_register_jit_icall (mono_string_to_utf16, "mono_string_to_utf16", helper_sig_ptr_obj, FALSE);
7013         mono_register_jit_icall (mono_string_from_utf16, "mono_string_from_utf16", helper_sig_obj_ptr, FALSE);
7014         mono_register_jit_icall (mono_string_new_wrapper, "mono_string_new_wrapper", helper_sig_obj_ptr, FALSE);
7015         mono_register_jit_icall (mono_string_to_utf8, "mono_string_to_utf8", helper_sig_ptr_obj, FALSE);
7016         mono_register_jit_icall (mono_string_to_bstr, "mono_string_to_bstr", helper_sig_ptr_obj, FALSE);
7017         mono_register_jit_icall (mono_string_to_ansibstr, "mono_string_to_ansibstr", helper_sig_ptr_obj, FALSE);
7018         mono_register_jit_icall (mono_string_builder_to_utf8, "mono_string_builder_to_utf8", helper_sig_ptr_obj, FALSE);
7019         mono_register_jit_icall (mono_array_to_savearray, "mono_array_to_savearray", helper_sig_ptr_obj, FALSE);
7020         mono_register_jit_icall (mono_array_to_lparray, "mono_array_to_lparray", helper_sig_ptr_obj, FALSE);
7021         mono_register_jit_icall (mono_delegate_to_ftnptr, "mono_delegate_to_ftnptr", helper_sig_ptr_obj, FALSE);
7022         mono_register_jit_icall (mono_marshal_string_array, "mono_marshal_string_array", helper_sig_ptr_obj, FALSE);
7023         mono_register_jit_icall (mono_string_utf8_to_builder, "mono_string_utf8_to_builder", helper_sig_void_ptr_ptr, FALSE);
7024         mono_register_jit_icall (mono_marshal_free_array, "mono_marshal_free_array", helper_sig_void_ptr_ptr, FALSE);
7025         mono_register_jit_icall (mono_string_to_byvalstr, "mono_string_to_byvalstr", helper_sig_void_ptr_ptr_ptr, FALSE);
7026         mono_register_jit_icall (mono_string_to_byvalwstr, "mono_string_to_byvalwstr", helper_sig_void_ptr_ptr_ptr, FALSE);
7027         mono_register_jit_icall (g_free, "g_free", helper_sig_void_ptr, FALSE);
7028         mono_register_jit_icall (mono_runtime_class_init, "mono_runtime_class_init", helper_sig_void_ptr, FALSE);
7029         mono_register_jit_icall (mono_ldftn, "mono_ldftn", helper_sig_compile, FALSE);
7030         mono_register_jit_icall (mono_ldvirtfn, "mono_ldvirtfn", helper_sig_compile_virt, FALSE);
7031
7032         mono_runtime_install_cleanup ((MonoDomainFunc)mini_cleanup);
7033         mono_runtime_init (domain, mono_thread_start_cb, mono_thread_attach_cb);
7034
7035         //mono_thread_attach (domain);
7036         return domain;
7037 }
7038
7039 MonoJitStats mono_jit_stats = {0};
7040
7041 static void 
7042 print_jit_stats (void)
7043 {
7044         if (mono_jit_stats.enabled) {
7045                 g_print ("Mono Jit statistics\n");
7046                 g_print ("Compiled methods:       %ld\n", mono_jit_stats.methods_compiled);
7047                 g_print ("Methods from AOT:       %ld\n", mono_jit_stats.methods_aot);
7048                 g_print ("Methods cache lookup:   %ld\n", mono_jit_stats.methods_lookups);
7049                 g_print ("Method trampolines:     %ld\n", mono_jit_stats.method_trampolines);
7050                 g_print ("Basic blocks:           %ld\n", mono_jit_stats.basic_blocks);
7051                 g_print ("Max basic blocks:       %ld\n", mono_jit_stats.max_basic_blocks);
7052                 g_print ("Allocated vars:         %ld\n", mono_jit_stats.allocate_var);
7053                 g_print ("Analyze stack repeat:   %ld\n", mono_jit_stats.analyze_stack_repeat);
7054                 g_print ("Compiled CIL code size: %ld\n", mono_jit_stats.cil_code_size);
7055                 g_print ("Native code size:       %ld\n", mono_jit_stats.native_code_size);
7056                 g_print ("Max code size ratio:    %.2f (%s::%s)\n", mono_jit_stats.max_code_size_ratio/100.0,
7057                                 mono_jit_stats.max_ratio_method->klass->name, mono_jit_stats.max_ratio_method->name);
7058                 g_print ("Biggest method:         %ld (%s::%s)\n", mono_jit_stats.biggest_method_size,
7059                                 mono_jit_stats.biggest_method->klass->name, mono_jit_stats.biggest_method->name);
7060                 g_print ("Code reallocs:          %ld\n", mono_jit_stats.code_reallocs);
7061                 g_print ("Allocated code size:    %ld\n", mono_jit_stats.allocated_code_size);
7062                 g_print ("Inlineable methods:     %ld\n", mono_jit_stats.inlineable_methods);
7063                 g_print ("Inlined methods:        %ld\n", mono_jit_stats.inlined_methods);
7064                 
7065                 g_print ("\nCreated object count:   %ld\n", mono_stats.new_object_count);
7066                 g_print ("Initialized classes:    %ld\n", mono_stats.initialized_class_count);
7067                 g_print ("Used classes:           %ld\n", mono_stats.used_class_count);
7068                 g_print ("Static data size:       %ld\n", mono_stats.class_static_data_size);
7069                 g_print ("VTable data size:       %ld\n", mono_stats.class_vtable_size);
7070         }
7071 }
7072
7073 void
7074 mini_cleanup (MonoDomain *domain)
7075 {
7076         /* 
7077          * mono_runtime_cleanup() and mono_domain_finalize () need to
7078          * be called early since they need the execution engine still
7079          * fully working (mono_domain_finalize may invoke managed finalizers
7080          * and mono_runtime_cleanup will wait for other threads to finish).
7081          */
7082         mono_domain_finalize (domain);
7083
7084         mono_runtime_cleanup (domain);
7085
7086         mono_profiler_shutdown ();
7087
7088         mono_debug_cleanup ();
7089
7090 #ifdef PLATFORM_WIN32
7091         win32_seh_cleanup();
7092 #endif
7093
7094         mono_domain_unload (domain, TRUE);
7095
7096         print_jit_stats ();
7097         DeleteCriticalSection (metadata_section);
7098 }
7099
7100 void
7101 mono_set_defaults (int verbose_level, guint32 opts)
7102 {
7103         mini_verbose = verbose_level;
7104         default_opt = opts;
7105 }
7106