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