2004-03-08 Zoltan Varga <vargaz@freemail.hu>
[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         if (!sighash)
2116                 sighash = g_hash_table_new (NULL, NULL);
2117
2118
2119         if ((res = g_hash_table_lookup (sighash, (gpointer)arity)))
2120                 return res;
2121
2122         res = mono_metadata_signature_alloc (mono_defaults.corlib, arity + 1);
2123
2124         res->pinvoke = 1;
2125         res->params [0] = &mono_defaults.array_class->byval_arg; 
2126         
2127         for (i = 1; i <= arity; i++)
2128                 res->params [i] = &mono_defaults.int_class->byval_arg;
2129
2130         res->ret = &mono_defaults.int_class->byval_arg;
2131
2132         g_hash_table_insert (sighash, (gpointer)arity, res);
2133
2134         return res;
2135 }
2136
2137 static void
2138 handle_stobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, MonoInst *src, const unsigned char *ip, MonoClass *klass, gboolean to_end, gboolean native) {
2139         MonoInst *iargs [3];
2140         int n;
2141         guint32 align = 0;
2142
2143         g_assert (klass);
2144         /*
2145          * This check breaks with spilled vars... need to handle it during verification anyway.
2146          * g_assert (klass && klass == src->klass && klass == dest->klass);
2147          */
2148
2149         if (native)
2150                 n = mono_class_native_size (klass, &align);
2151         else
2152                 n = mono_class_value_size (klass, &align);
2153
2154         if ((cfg->opt & MONO_OPT_INTRINS) && !to_end && n <= sizeof (gpointer) * 5) {
2155                 MonoInst *inst;
2156                 MONO_INST_NEW (cfg, inst, OP_MEMCPY);
2157                 inst->inst_left = dest;
2158                 inst->inst_right = src;
2159                 inst->cil_code = ip;
2160                 inst->unused = n;
2161                 MONO_ADD_INS (bblock, inst);
2162                 return;
2163         }
2164         iargs [0] = dest;
2165         iargs [1] = src;
2166         NEW_ICONST (cfg, iargs [2], n);
2167
2168         mono_emit_native_call (cfg, bblock, helper_memcpy, helper_sig_memcpy, iargs, ip, to_end);
2169 }
2170
2171 static void
2172 handle_initobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, const guchar *ip, MonoClass *klass, MonoInst **stack_start, MonoInst **sp)
2173 {
2174         MonoInst *iargs [2];
2175         MonoInst *ins, *zero_int32;
2176         int n;
2177
2178         NEW_ICONST (cfg, zero_int32, 0);
2179
2180         mono_class_init (klass);
2181         n = mono_class_value_size (klass, NULL);
2182         MONO_INST_NEW (cfg, ins, 0);
2183         ins->cil_code = ip;
2184         ins->inst_left = dest;
2185         ins->inst_right = zero_int32;
2186         switch (n) {
2187         case 1:
2188                 ins->opcode = CEE_STIND_I1;
2189                 MONO_ADD_INS (bblock, ins);
2190                 break;
2191         case 2:
2192                 ins->opcode = CEE_STIND_I2;
2193                 MONO_ADD_INS (bblock, ins);
2194                 break;
2195         case 4:
2196                 ins->opcode = CEE_STIND_I4;
2197                 MONO_ADD_INS (bblock, ins);
2198                 break;
2199         default:
2200                 if (n <= sizeof (gpointer) * 5) {
2201                         ins->opcode = OP_MEMSET;
2202                         ins->inst_imm = 0;
2203                         ins->unused = n;
2204                         MONO_ADD_INS (bblock, ins);
2205                         break;
2206                 }
2207                 handle_loaded_temps (cfg, bblock, stack_start, sp);
2208                 NEW_ICONST (cfg, ins, n);
2209                 iargs [0] = dest;
2210                 iargs [1] = ins;
2211                 mono_emit_jit_icall (cfg, bblock, helper_initobj, iargs, ip);
2212                 break;
2213         }
2214 }
2215
2216 #define CODE_IS_STLOC(ip) (((ip) [0] >= CEE_STLOC_0 && (ip) [0] <= CEE_STLOC_3) || ((ip) [0] == CEE_STLOC_S))
2217
2218 static gboolean
2219 mono_method_check_inlining (MonoCompile *cfg, MonoMethod *method)
2220 {
2221         MonoMethodHeader *header = ((MonoMethodNormal *)method)->header;
2222         MonoMethodSignature *signature = method->signature;
2223         MonoVTable *vtable;
2224         int i;
2225
2226         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2227             (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
2228             (method->iflags & METHOD_IMPL_ATTRIBUTE_NOINLINING) ||
2229             (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) ||
2230             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2231             (method->klass->marshalbyref) ||
2232             !header || header->num_clauses ||
2233             /* fixme: why cant we inline valuetype returns? */
2234             MONO_TYPE_ISSTRUCT (signature->ret))
2235                 return FALSE;
2236
2237         /* its not worth to inline methods with valuetype arguments?? */
2238         for (i = 0; i < signature->param_count; i++) {
2239                 if (MONO_TYPE_ISSTRUCT (signature->params [i])) {
2240                         return FALSE;
2241                 }
2242         }
2243
2244         /*
2245          * if we can initialize the class of the method right away, we do,
2246          * otherwise we don't allow inlining if the class needs initialization,
2247          * since it would mean inserting a call to mono_runtime_class_init()
2248          * inside the inlined code
2249          */
2250         if (!(cfg->opt & MONO_OPT_SHARED)) {
2251                 vtable = mono_class_vtable (cfg->domain, method->klass);
2252                 if (method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) {
2253                         if (cfg->run_cctors)
2254                                 mono_runtime_class_init (vtable);
2255                 }
2256                 else if (!vtable->initialized && mono_class_needs_cctor_run (method->klass, NULL))
2257                         return FALSE;
2258         } else {
2259                 /* 
2260                  * If we're compiling for shared code
2261                  * the cctor will need to be run at aot method load time, for example,
2262                  * or at the end of the compilation of the inlining method.
2263                  */
2264                 if (mono_class_needs_cctor_run (method->klass, NULL) && !((method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
2265                         return FALSE;
2266         }
2267         //if (!MONO_TYPE_IS_VOID (signature->ret)) return FALSE;
2268
2269         /* also consider num_locals? */
2270         if (getenv ("MONO_INLINELIMIT"))
2271                 if (header->code_size < atoi (getenv ("MONO_INLINELIMIT"))) {
2272                         return TRUE;
2273                 }
2274
2275         if (header->code_size < 20)
2276                 return TRUE;
2277
2278         return FALSE;
2279 }
2280
2281 static MonoInst*
2282 mini_get_ldelema_ins (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *cmethod, MonoInst **sp, unsigned char *ip, gboolean is_set)
2283 {
2284         int temp, rank;
2285         MonoInst *addr;
2286         MonoMethodSignature *esig;
2287         char icall_name [256];
2288         MonoJitICallInfo *info;
2289
2290         rank = cmethod->signature->param_count - (is_set? 1: 0);
2291
2292         if (rank == 2 && (cfg->opt & MONO_OPT_INTRINS)) {
2293                 MonoInst *indexes;
2294                 NEW_GROUP (cfg, indexes, sp [1], sp [2]);
2295                 MONO_INST_NEW (cfg, addr, OP_LDELEMA2D);
2296                 addr->inst_left = sp [0];
2297                 addr->inst_right = indexes;
2298                 addr->cil_code = ip;
2299                 addr->type = STACK_MP;
2300                 addr->klass = cmethod->klass;
2301                 return addr;
2302         }
2303
2304         /* Need to register the icall so it gets an icall wrapper */
2305         sprintf (icall_name, "ves_array_element_address_%d", rank);
2306
2307         info = mono_find_jit_icall_by_name (icall_name);
2308         if (info == NULL) {
2309                 esig = mono_get_element_address_signature (rank);
2310                 info = mono_register_jit_icall (ves_array_element_address, g_strdup (icall_name), esig, FALSE);
2311         }
2312
2313         temp = mono_emit_native_call (cfg, bblock, mono_icall_get_wrapper (info), info->sig, sp, ip, FALSE);
2314
2315         NEW_TEMPLOAD (cfg, addr, temp);
2316         return addr;
2317 }
2318
2319 static MonoJitICallInfo **emul_opcode_map = NULL;
2320
2321 static inline MonoJitICallInfo *
2322 mono_find_jit_opcode_emulation (int opcode)
2323 {
2324         if  (emul_opcode_map)
2325                 return emul_opcode_map [opcode];
2326         else
2327                 return NULL;
2328 }
2329
2330 static MonoInst*
2331 mini_get_opcode_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
2332 {
2333         int pc, op;
2334         MonoInst *ins;
2335
2336         if (cmethod->klass == mono_defaults.string_class) {
2337                 if (cmethod->name [0] != 'g')
2338                         return NULL;
2339  
2340                 if (strcmp (cmethod->name, "get_Chars") == 0)
2341                         op = OP_GETCHR;
2342                 else if (strcmp (cmethod->name, "get_Length") == 0)
2343                         op = OP_STRLEN;
2344                 else return NULL;
2345         } else if (cmethod->klass == mono_defaults.object_class) {
2346                 if (strcmp (cmethod->name, "GetType") == 0)
2347                         op = OP_GETTYPE;
2348                 else
2349                         return NULL;
2350         } else if (cmethod->klass == mono_defaults.array_class) {
2351                 if (strcmp (cmethod->name, "get_Rank") == 0)
2352                         op = OP_ARRAY_RANK;
2353                 else if (strcmp (cmethod->name, "get_Length") == 0)
2354                         op = CEE_LDLEN;
2355                 else
2356                         return NULL;
2357         } else {
2358                 op = mono_arch_get_opcode_for_method (cfg, cmethod, fsig, args);
2359                 if (op < 0)
2360                         return NULL;
2361         }
2362         pc = fsig->param_count + fsig->hasthis;
2363         MONO_INST_NEW (cfg, ins, op);
2364
2365         if (pc > 0) {
2366                 ins->inst_i0 = args [0];
2367                 if (pc > 1)
2368                         ins->inst_i1 = args [1];
2369         }
2370
2371         return ins;
2372 }
2373
2374 static void
2375 mono_save_args (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, MonoInst **sp, MonoInst **args)
2376 {
2377         MonoInst *store, *temp;
2378         int i;
2379
2380         g_assert (!MONO_TYPE_ISSTRUCT (sig->ret));
2381
2382         if (!sig->hasthis && sig->param_count == 0) 
2383                 return;
2384
2385         if (sig->hasthis) {
2386                 if (sp [0]->opcode == OP_ICONST) {
2387                         *args++ = sp [0];
2388                 } else {
2389                         temp = mono_compile_create_var (cfg, type_from_stack_type (*sp), OP_LOCAL);
2390                         *args++ = temp;
2391                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
2392                         store->cil_code = sp [0]->cil_code;
2393                         MONO_ADD_INS (bblock, store);
2394                 }
2395                 sp++;
2396         }
2397
2398         for (i = 0; i < sig->param_count; ++i) {
2399                 if (sp [0]->opcode == OP_ICONST) {
2400                         *args++ = sp [0];
2401                 } else {
2402                         temp = mono_compile_create_var (cfg, sig->params [i], OP_LOCAL);
2403                         *args++ = temp;
2404                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
2405                         store->cil_code = sp [0]->cil_code;
2406                         if (store->opcode == CEE_STOBJ) {
2407                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
2408                                 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, temp->klass, FALSE, FALSE);
2409                         } else {
2410                                 MONO_ADD_INS (bblock, store);
2411                         } 
2412                 }
2413                 sp++;
2414         }
2415 }
2416
2417 static int
2418 inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoBasicBlock *bblock, MonoInst **sp,
2419                 guchar *ip, guint real_offset, GList *dont_inline, MonoBasicBlock **last_b)
2420 {
2421         MonoInst *ins, *rvar = NULL;
2422         MonoMethodHeader *cheader;
2423         MonoBasicBlock *ebblock, *sbblock;
2424         int i, costs, new_locals_offset;
2425
2426         if (cfg->verbose_level > 2)
2427                 g_print ("INLINE START %p %s -> %s\n", cmethod,  mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
2428
2429         cheader = ((MonoMethodNormal *)cmethod)->header;
2430
2431         if (!cmethod->inline_info) {
2432                 mono_jit_stats.inlineable_methods++;
2433                 cmethod->inline_info = 1;
2434         }
2435         /* allocate space to store the return value */
2436         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
2437                 rvar =  mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
2438         }
2439
2440         /* allocate local variables */
2441         new_locals_offset = cfg->num_varinfo;
2442         for (i = 0; i < cheader->num_locals; ++i)
2443                 mono_compile_create_var (cfg, cheader->locals [i], OP_LOCAL);
2444         
2445         /* allocate starte and end blocks */
2446         sbblock = NEW_BBLOCK (cfg);
2447         sbblock->block_num = cfg->num_bblocks++;
2448         sbblock->real_offset = real_offset;
2449
2450         ebblock = NEW_BBLOCK (cfg);
2451         ebblock->block_num = cfg->num_bblocks++;
2452         ebblock->real_offset = real_offset;
2453
2454         costs = mono_method_to_ir (cfg, cmethod, sbblock, ebblock, new_locals_offset, rvar, dont_inline, sp, real_offset, *ip == CEE_CALLVIRT);
2455
2456         if (costs >= 0 && costs < 60) {
2457                 if (cfg->verbose_level > 2)
2458                         g_print ("INLINE END %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
2459                 
2460                 mono_jit_stats.inlined_methods++;
2461
2462                 /* always add some code to avoid block split failures */
2463                 MONO_INST_NEW (cfg, ins, CEE_NOP);
2464                 MONO_ADD_INS (bblock, ins);
2465                 ins->cil_code = ip;
2466
2467                 bblock->next_bb = sbblock;
2468                 link_bblock (cfg, bblock, sbblock);
2469
2470                 if (rvar) {
2471                         NEW_TEMPLOAD (cfg, ins, rvar->inst_c0);
2472                         *sp++ = ins;
2473                 }
2474                 *last_b = ebblock;
2475                 return costs + 1;
2476         } else {
2477                 if (cfg->verbose_level > 2)
2478                         g_print ("INLINE ABORTED %s\n", mono_method_full_name (cmethod, TRUE));
2479         }
2480         return 0;
2481 }
2482
2483 /*
2484  * Some of these comments may well be out-of-date.
2485  * Design decisions: we do a single pass over the IL code (and we do bblock 
2486  * splitting/merging in the few cases when it's required: a back jump to an IL
2487  * address that was not already seen as bblock starting point).
2488  * Code is validated as we go (full verification is still better left to metadata/verify.c).
2489  * Complex operations are decomposed in simpler ones right away. We need to let the 
2490  * arch-specific code peek and poke inside this process somehow (except when the 
2491  * optimizations can take advantage of the full semantic info of coarse opcodes).
2492  * All the opcodes of the form opcode.s are 'normalized' to opcode.
2493  * MonoInst->opcode initially is the IL opcode or some simplification of that 
2494  * (OP_LOAD, OP_STORE). The arch-specific code may rearrange it to an arch-specific 
2495  * opcode with value bigger than OP_LAST.
2496  * At this point the IR can be handed over to an interpreter, a dumb code generator
2497  * or to the optimizing code generator that will translate it to SSA form.
2498  *
2499  * Profiling directed optimizations.
2500  * We may compile by default with few or no optimizations and instrument the code
2501  * or the user may indicate what methods to optimize the most either in a config file
2502  * or through repeated runs where the compiler applies offline the optimizations to 
2503  * each method and then decides if it was worth it.
2504  *
2505  * TODO:
2506  * * consider using an array instead of an hash table (bb_hash)
2507  */
2508
2509 #define CHECK_TYPE(ins) if (!(ins)->type) goto unverified
2510 #define CHECK_STACK(num) if ((sp - stack_start) < (num)) goto unverified
2511 #define CHECK_STACK_OVF(num) if (((sp - stack_start) + (num)) > header->max_stack) goto unverified
2512 #define CHECK_ARG(num) if ((unsigned)(num) >= (unsigned)num_args) goto unverified
2513 #define CHECK_LOCAL(num) if ((unsigned)(num) >= (unsigned)header->num_locals) goto unverified
2514 #define CHECK_OPSIZE(size) if (ip + size > end) goto unverified
2515
2516 #define TYPE_PARAM_TO_TYPE(num) (method->klass->generic_inst->type_argv [(num)])
2517 #define TYPE_PARAM_TO_CLASS(num) (mono_class_from_mono_type (TYPE_PARAM_TO_TYPE ((num))))
2518
2519 #define MTYPE_PARAM_TO_TYPE(num) (method->signature->gen_method->mtype_argv [(num)])
2520 #define MTYPE_PARAM_TO_CLASS(num) (mono_class_from_mono_type (MTYPE_PARAM_TO_TYPE ((num))))
2521
2522
2523 /* offset from br.s -> br like opcodes */
2524 #define BIG_BRANCH_OFFSET 13
2525
2526 static int
2527 get_basic_blocks (MonoCompile *cfg, GHashTable *bbhash, MonoMethodHeader* header, guint real_offset, unsigned char *start, unsigned char *end, unsigned char **pos)
2528 {
2529         unsigned char *ip = start;
2530         unsigned char *target;
2531         int i;
2532         guint cli_addr;
2533         MonoBasicBlock *bblock;
2534         const MonoOpcode *opcode;
2535
2536         while (ip < end) {
2537                 cli_addr = ip - start;
2538                 i = mono_opcode_value ((const guint8 **)&ip);
2539                 opcode = &mono_opcodes [i];
2540                 switch (opcode->argument) {
2541                 case MonoInlineNone:
2542                         ip++; 
2543                         break;
2544                 case MonoInlineString:
2545                 case MonoInlineType:
2546                 case MonoInlineField:
2547                 case MonoInlineMethod:
2548                 case MonoInlineTok:
2549                 case MonoInlineSig:
2550                 case MonoShortInlineR:
2551                 case MonoInlineI:
2552                         ip += 5;
2553                         break;
2554                 case MonoInlineVar:
2555                         ip += 3;
2556                         break;
2557                 case MonoShortInlineVar:
2558                 case MonoShortInlineI:
2559                         ip += 2;
2560                         break;
2561                 case MonoShortInlineBrTarget:
2562                         target = start + cli_addr + 2 + (signed char)ip [1];
2563                         GET_BBLOCK (cfg, bbhash, bblock, target);
2564                         ip += 2;
2565                         break;
2566                 case MonoInlineBrTarget:
2567                         target = start + cli_addr + 5 + (gint32)read32 (ip + 1);
2568                         GET_BBLOCK (cfg, bbhash, bblock, target);
2569                         ip += 5;
2570                         break;
2571                 case MonoInlineSwitch: {
2572                         guint32 n = read32 (ip + 1);
2573                         guint32 j;
2574                         ip += 5;
2575                         cli_addr += 5 + 4 * n;
2576                         target = start + cli_addr;
2577                         GET_BBLOCK (cfg, bbhash, bblock, target);
2578                         
2579                         for (j = 0; j < n; ++j) {
2580                                 target = start + cli_addr + (gint32)read32 (ip);
2581                                 GET_BBLOCK (cfg, bbhash, bblock, target);
2582                                 ip += 4;
2583                         }
2584                         break;
2585                 }
2586                 case MonoInlineR:
2587                 case MonoInlineI8:
2588                         ip += 9;
2589                         break;
2590                 default:
2591                         g_assert_not_reached ();
2592                 }
2593         }
2594         return 0;
2595 unverified:
2596         *pos = ip;
2597         return 1;
2598 }
2599
2600 static MonoClassField *
2601 get_generic_field_inst (MonoClassField *field, MonoClass *klass, MonoClass **retclass)
2602 {
2603         int i;
2604         for (i = 0; i < field->parent->field.count; ++i) {
2605                 if (field == &field->parent->fields [i]) {
2606                         *retclass = klass;
2607                         return &klass->fields [i];
2608                 }
2609         }
2610         return NULL;
2611 }
2612
2613 static MonoClassField *
2614 inflate_generic_field (MonoClassField *field, MonoClass *klass, MonoClass **retclass)
2615 {
2616         MonoGenericInst *ginst;
2617         MonoClassField *res;
2618
2619         res = g_new0 (MonoClassField, 1);
2620         *res = *field;
2621         ginst = klass->generic_inst;
2622         res->type = mono_class_inflate_generic_type (field->type, ginst, NULL);
2623         return res;
2624 }
2625
2626 static MonoMethod *
2627 mini_get_method (MonoImage *image, guint32 token, MonoMethod *calling_method)
2628 {
2629         MonoMethod *method = mono_get_method (image, token, NULL);
2630         MonoGenericMethod *gmethod;
2631
2632         if (!calling_method->signature->gen_method || !method->signature->gen_method)
2633                 return method;
2634
2635         gmethod = g_new0 (MonoGenericMethod, 1);
2636         *gmethod = *calling_method->signature->gen_method;
2637         gmethod->generic_method = method;
2638         gmethod->generic_inst = calling_method->klass->generic_inst;
2639
2640         return mono_class_inflate_generic_method (method, gmethod, NULL);
2641 }
2642
2643 /*
2644  * mono_method_to_ir: translates IL into basic blocks containing trees
2645  */
2646 static int
2647 mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
2648                    int locals_offset, MonoInst *return_var, GList *dont_inline, MonoInst **inline_args, 
2649                    guint inline_offset, gboolean is_virtual_call)
2650 {
2651         MonoInst *zero_int32, *zero_int64, *zero_ptr, *zero_obj, *zero_r8;
2652         MonoInst *ins, **sp, **stack_start;
2653         MonoBasicBlock *bblock, *tblock = NULL, *init_localsbb = NULL;
2654         GHashTable *bbhash;
2655         MonoMethod *cmethod;
2656         MonoInst **arg_array;
2657         MonoMethodHeader *header;
2658         MonoImage *image;
2659         guint32 token, ins_flag;
2660         MonoClass *klass;
2661         unsigned char *ip, *end, *target, *err_pos;
2662         static double r8_0 = 0.0;
2663         MonoMethodSignature *sig;
2664         MonoType **param_types;
2665         GList *bb_recheck = NULL, *tmp;
2666         int i, n, start_new_bblock, align;
2667         int num_calls = 0, inline_costs = 0;
2668         int *filter_lengths = NULL;
2669         int breakpoint_id = 0;
2670         guint real_offset, num_args;
2671
2672         image = method->klass->image;
2673         header = ((MonoMethodNormal *)method)->header;
2674         sig = method->signature;
2675         num_args = sig->hasthis + sig->param_count;
2676         ip = (unsigned char*)header->code;
2677         end = ip + header->code_size;
2678         mono_jit_stats.cil_code_size += header->code_size;
2679
2680         if (cfg->method == method) {
2681                 real_offset = 0;
2682                 bbhash = cfg->bb_hash;
2683         } else {
2684                 real_offset = inline_offset;
2685                 bbhash = g_hash_table_new (g_direct_hash, NULL);
2686         }
2687
2688         if (cfg->verbose_level > 2)
2689                 g_print ("method to IR %s\n", mono_method_full_name (method, TRUE));
2690
2691         if (cfg->prof_options & MONO_PROFILE_INS_COVERAGE)
2692                 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, header->code_size);
2693
2694         dont_inline = g_list_prepend (dont_inline, method);
2695         if (cfg->method == method) {
2696
2697                 /* ENTRY BLOCK */
2698                 cfg->bb_entry = start_bblock = NEW_BBLOCK (cfg);
2699                 start_bblock->cil_code = NULL;
2700                 start_bblock->cil_length = 0;
2701                 start_bblock->block_num = cfg->num_bblocks++;
2702
2703                 /* EXIT BLOCK */
2704                 cfg->bb_exit = end_bblock = NEW_BBLOCK (cfg);
2705                 end_bblock->cil_code = NULL;
2706                 end_bblock->cil_length = 0;
2707                 end_bblock->block_num = cfg->num_bblocks++;
2708                 g_assert (cfg->num_bblocks == 2);
2709
2710                 arg_array = alloca (sizeof (MonoInst *) * num_args);
2711                 for (i = num_args - 1; i >= 0; i--)
2712                         arg_array [i] = cfg->varinfo [i];
2713
2714                 if (header->num_clauses) {
2715                         int size = sizeof (int) * header->num_clauses;
2716                         filter_lengths = alloca (size);
2717                         memset (filter_lengths, 0, size);
2718
2719                         cfg->spvars = g_hash_table_new (NULL, NULL);
2720                 }
2721                 /* handle exception clauses */
2722                 for (i = 0; i < header->num_clauses; ++i) {
2723                         //unsigned char *p = ip;
2724                         MonoExceptionClause *clause = &header->clauses [i];
2725                         GET_BBLOCK (cfg, bbhash, tblock, ip + clause->try_offset);
2726                         tblock->real_offset = clause->try_offset;
2727                         GET_BBLOCK (cfg, bbhash, tblock, ip + clause->handler_offset);
2728                         tblock->real_offset = clause->handler_offset;
2729
2730                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY ||
2731                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
2732                                 MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
2733                                 MONO_ADD_INS (tblock, ins);
2734                         }
2735
2736                         /*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);
2737                           while (p < end) {
2738                           g_print ("%s", mono_disasm_code_one (NULL, method, p, &p));
2739                           }*/
2740                         /* catch and filter blocks get the exception object on the stack */
2741                         if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE ||
2742                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
2743                                 /* mostly like handle_stack_args (), but just sets the input args */
2744                                 /* g_print ("handling clause at IL_%04x\n", clause->handler_offset); */
2745                                 if (!cfg->exvar) {
2746                                         cfg->exvar = mono_compile_create_var (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL);
2747                                         /* prevent it from being register allocated */
2748                                         cfg->exvar->flags |= MONO_INST_INDIRECT;
2749                                 }
2750                                 tblock->in_scount = 1;
2751                                 tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
2752                                 tblock->in_stack [0] = cfg->exvar;
2753                                 
2754                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
2755                                         GET_BBLOCK (cfg, bbhash, tblock, ip + clause->token_or_filter);
2756                                         tblock->real_offset = clause->token_or_filter;
2757                                         tblock->in_scount = 1;
2758                                         tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
2759                                         tblock->in_stack [0] = cfg->exvar;
2760                                         MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
2761                                         MONO_ADD_INS (tblock, ins);
2762                                 }
2763                         }
2764                 }
2765
2766         } else {
2767                 arg_array = alloca (sizeof (MonoInst *) * num_args);
2768                 mono_save_args (cfg, start_bblock, sig, inline_args, arg_array);
2769         }
2770
2771         /* FIRST CODE BLOCK */
2772         bblock = NEW_BBLOCK (cfg);
2773         bblock->cil_code = ip;
2774
2775         ADD_BBLOCK (cfg, bbhash, bblock);
2776
2777         if (cfg->method == method) {
2778                 breakpoint_id = mono_debugger_method_has_breakpoint (method);
2779                 if (breakpoint_id && (mono_debug_format != MONO_DEBUG_FORMAT_DEBUGGER)) {
2780                         MONO_INST_NEW (cfg, ins, CEE_BREAK);
2781                         MONO_ADD_INS (bblock, ins);
2782                 }
2783         }
2784         
2785         if ((header->init_locals || (cfg->method == method && (cfg->opt & MONO_OPT_SHARED))) || mono_compile_aot) {
2786                 /* we use a separate basic block for the initialization code */
2787                 cfg->bb_init = init_localsbb = NEW_BBLOCK (cfg);
2788                 init_localsbb->real_offset = real_offset;
2789                 start_bblock->next_bb = init_localsbb;
2790                 init_localsbb->next_bb = bblock;
2791                 link_bblock (cfg, start_bblock, init_localsbb);
2792                 link_bblock (cfg, init_localsbb, bblock);
2793                 init_localsbb->block_num = cfg->num_bblocks++;
2794         } else {
2795                 start_bblock->next_bb = bblock;
2796                 link_bblock (cfg, start_bblock, bblock);
2797         }
2798
2799         if (get_basic_blocks (cfg, bbhash, header, real_offset, ip, end, &err_pos)) {
2800                 ip = err_pos;
2801                 goto unverified;
2802         }
2803
2804         mono_debug_init_method (cfg, bblock, breakpoint_id);
2805
2806         param_types = mono_mempool_alloc (cfg->mempool, sizeof (MonoType*) * num_args);
2807         if (sig->hasthis)
2808                 param_types [0] = method->klass->valuetype?&method->klass->this_arg:&method->klass->byval_arg;
2809         for (n = 0; n < sig->param_count; ++n)
2810                 param_types [n + sig->hasthis] = sig->params [n];
2811
2812         /* do this somewhere outside - not here */
2813         NEW_ICONST (cfg, zero_int32, 0);
2814         NEW_ICONST (cfg, zero_int64, 0);
2815         zero_int64->type = STACK_I8;
2816         NEW_PCONST (cfg, zero_ptr, 0);
2817         NEW_PCONST (cfg, zero_obj, 0);
2818         zero_obj->type = STACK_OBJ;
2819
2820         MONO_INST_NEW (cfg, zero_r8, OP_R8CONST);
2821         zero_r8->type = STACK_R8;
2822         zero_r8->inst_p0 = &r8_0;
2823
2824         /* add a check for this != NULL to inlined methods */
2825         if (is_virtual_call) {
2826                 MONO_INST_NEW (cfg, ins, OP_CHECK_THIS);
2827                 NEW_ARGLOAD (cfg, ins->inst_left, 0);
2828                 ins->cil_code = ip;
2829                 MONO_ADD_INS (bblock, ins);
2830         }
2831
2832         /* we use a spare stack slot in SWITCH and NEWOBJ and others */
2833         stack_start = sp = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (header->max_stack + 1));
2834
2835         ins_flag = 0;
2836         start_new_bblock = 0;
2837         while (ip < end) {
2838
2839                 if (cfg->method == method)
2840                         real_offset = ip - header->code;
2841                 else
2842                         real_offset = inline_offset;
2843
2844                 if (start_new_bblock) {
2845                         bblock->cil_length = ip - bblock->cil_code;
2846                         if (start_new_bblock == 2) {
2847                                 g_assert (ip == tblock->cil_code);
2848                         } else {
2849                                 GET_BBLOCK (cfg, bbhash, tblock, ip);
2850                         }
2851                         bblock->next_bb = tblock;
2852                         bblock = tblock;
2853                         start_new_bblock = 0;
2854                         for (i = 0; i < bblock->in_scount; ++i) {
2855                                 NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
2856                                 *sp++ = ins;
2857                         }
2858                 } else {
2859                         if ((tblock = g_hash_table_lookup (bbhash, ip)) && (tblock != bblock)) {
2860                                 link_bblock (cfg, bblock, tblock);
2861                                 if (sp != stack_start) {
2862                                         handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
2863                                         sp = stack_start;
2864                                 }
2865                                 bblock->next_bb = tblock;
2866                                 bblock = tblock;
2867                                 for (i = 0; i < bblock->in_scount; ++i) {
2868                                         NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
2869                                         *sp++ = ins;
2870                                 }
2871                         }
2872                 }
2873
2874                 if (cfg->coverage_info) {
2875                         MonoInst *store, *one;
2876                         guint32 cil_offset = ip - header->code;
2877                         cfg->coverage_info->data [cil_offset].cil_code = ip;
2878
2879                         /* TODO: Use an increment here */
2880                         NEW_ICONST (cfg, one, 1);
2881                         one->cil_code = ip;
2882
2883                         NEW_PCONST (cfg, ins, &(cfg->coverage_info->data [cil_offset].count));
2884                         ins->cil_code = ip;
2885
2886                         MONO_INST_NEW (cfg, store, CEE_STIND_I);
2887                         store->cil_code = ip;
2888                         store->inst_left = ins;
2889                         store->inst_right = one;
2890
2891                         MONO_ADD_INS (bblock, store);
2892                 }
2893
2894                 if (cfg->verbose_level > 3)
2895                         g_print ("converting (in B%d: stack: %d) %s", bblock->block_num, sp-stack_start, mono_disasm_code_one (NULL, method, ip, NULL));
2896
2897                 /* Workaround for bug #51126 */
2898                 bblock->real_offset = real_offset;
2899
2900                 switch (*ip) {
2901                 case CEE_NOP:
2902                         ++ip;
2903                         break;
2904                 case CEE_BREAK:
2905                         MONO_INST_NEW (cfg, ins, CEE_BREAK);
2906                         ins->cil_code = ip++;
2907                         MONO_ADD_INS (bblock, ins);
2908                         break;
2909                 case CEE_LDARG_0:
2910                 case CEE_LDARG_1:
2911                 case CEE_LDARG_2:
2912                 case CEE_LDARG_3:
2913                         CHECK_STACK_OVF (1);
2914                         n = (*ip)-CEE_LDARG_0;
2915                         CHECK_ARG (n);
2916                         NEW_ARGLOAD (cfg, ins, n);
2917                         ins->cil_code = ip++;
2918                         *sp++ = ins;
2919                         break;
2920                 case CEE_LDLOC_0:
2921                 case CEE_LDLOC_1:
2922                 case CEE_LDLOC_2:
2923                 case CEE_LDLOC_3:
2924                         CHECK_STACK_OVF (1);
2925                         n = (*ip)-CEE_LDLOC_0;
2926                         CHECK_LOCAL (n);
2927                         NEW_LOCLOAD (cfg, ins, n);
2928                         ins->cil_code = ip++;
2929                         *sp++ = ins;
2930                         break;
2931                 case CEE_STLOC_0:
2932                 case CEE_STLOC_1:
2933                 case CEE_STLOC_2:
2934                 case CEE_STLOC_3:
2935                         CHECK_STACK (1);
2936                         n = (*ip)-CEE_STLOC_0;
2937                         CHECK_LOCAL (n);
2938                         --sp;
2939                         handle_loaded_temps (cfg, bblock, stack_start, sp);
2940                         NEW_LOCSTORE (cfg, ins, n, *sp);
2941                         ins->cil_code = ip;
2942                         if (ins->opcode == CEE_STOBJ) {
2943                                 NEW_LOCLOADA (cfg, ins, n);
2944                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
2945                         } else
2946                                 MONO_ADD_INS (bblock, ins);
2947                         ++ip;
2948                         inline_costs += 1;
2949                         break;
2950                 case CEE_LDARG_S:
2951                         CHECK_OPSIZE (2);
2952                         CHECK_STACK_OVF (1);
2953                         CHECK_ARG (ip [1]);
2954                         NEW_ARGLOAD (cfg, ins, ip [1]);
2955                         ins->cil_code = ip;
2956                         *sp++ = ins;
2957                         ip += 2;
2958                         break;
2959                 case CEE_LDARGA_S:
2960                         CHECK_OPSIZE (2);
2961                         CHECK_STACK_OVF (1);
2962                         CHECK_ARG (ip [1]);
2963                         NEW_ARGLOADA (cfg, ins, ip [1]);
2964                         ins->cil_code = ip;
2965                         *sp++ = ins;
2966                         ip += 2;
2967                         break;
2968                 case CEE_STARG_S:
2969                         CHECK_OPSIZE (2);
2970                         CHECK_STACK (1);
2971                         --sp;
2972                         CHECK_ARG (ip [1]);
2973                         NEW_ARGSTORE (cfg, ins, ip [1], *sp);
2974                         handle_loaded_temps (cfg, bblock, stack_start, sp);
2975                         ins->cil_code = ip;
2976                         if (ins->opcode == CEE_STOBJ) {
2977                                 NEW_ARGLOADA (cfg, ins, ip [1]);
2978                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
2979                         } else
2980                                 MONO_ADD_INS (bblock, ins);
2981                         ip += 2;
2982                         break;
2983                 case CEE_LDLOC_S:
2984                         CHECK_OPSIZE (2);
2985                         CHECK_STACK_OVF (1);
2986                         CHECK_LOCAL (ip [1]);
2987                         NEW_LOCLOAD (cfg, ins, ip [1]);
2988                         ins->cil_code = ip;
2989                         *sp++ = ins;
2990                         ip += 2;
2991                         break;
2992                 case CEE_LDLOCA_S:
2993                         CHECK_OPSIZE (2);
2994                         CHECK_STACK_OVF (1);
2995                         CHECK_LOCAL (ip [1]);
2996                         NEW_LOCLOADA (cfg, ins, ip [1]);
2997                         ins->cil_code = ip;
2998                         *sp++ = ins;
2999                         ip += 2;
3000                         break;
3001                 case CEE_STLOC_S:
3002                         CHECK_OPSIZE (2);
3003                         CHECK_STACK (1);
3004                         --sp;
3005                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3006                         CHECK_LOCAL (ip [1]);
3007                         NEW_LOCSTORE (cfg, ins, ip [1], *sp);
3008                         ins->cil_code = ip;
3009                         if (ins->opcode == CEE_STOBJ) {
3010                                 NEW_LOCLOADA (cfg, ins, ip [1]);
3011                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
3012                         } else
3013                                 MONO_ADD_INS (bblock, ins);
3014                         ip += 2;
3015                         inline_costs += 1;
3016                         break;
3017                 case CEE_LDNULL:
3018                         CHECK_STACK_OVF (1);
3019                         NEW_PCONST (cfg, ins, NULL);
3020                         ins->cil_code = ip;
3021                         ins->type = STACK_OBJ;
3022                         ++ip;
3023                         *sp++ = ins;
3024                         break;
3025                 case CEE_LDC_I4_M1:
3026                         CHECK_STACK_OVF (1);
3027                         NEW_ICONST (cfg, ins, -1);
3028                         ins->cil_code = ip;
3029                         ++ip;
3030                         *sp++ = ins;
3031                         break;
3032                 case CEE_LDC_I4_0:
3033                 case CEE_LDC_I4_1:
3034                 case CEE_LDC_I4_2:
3035                 case CEE_LDC_I4_3:
3036                 case CEE_LDC_I4_4:
3037                 case CEE_LDC_I4_5:
3038                 case CEE_LDC_I4_6:
3039                 case CEE_LDC_I4_7:
3040                 case CEE_LDC_I4_8:
3041                         CHECK_STACK_OVF (1);
3042                         NEW_ICONST (cfg, ins, (*ip) - CEE_LDC_I4_0);
3043                         ins->cil_code = ip;
3044                         ++ip;
3045                         *sp++ = ins;
3046                         break;
3047                 case CEE_LDC_I4_S:
3048                         CHECK_OPSIZE (2);
3049                         CHECK_STACK_OVF (1);
3050                         ++ip;
3051                         NEW_ICONST (cfg, ins, *((signed char*)ip));
3052                         ins->cil_code = ip;
3053                         ++ip;
3054                         *sp++ = ins;
3055                         break;
3056                 case CEE_LDC_I4:
3057                         CHECK_OPSIZE (5);
3058                         CHECK_STACK_OVF (1);
3059                         NEW_ICONST (cfg, ins, (gint32)read32 (ip + 1));
3060                         ins->cil_code = ip;
3061                         ip += 5;
3062                         *sp++ = ins;
3063                         break;
3064                 case CEE_LDC_I8:
3065                         CHECK_OPSIZE (9);
3066                         CHECK_STACK_OVF (1);
3067                         MONO_INST_NEW (cfg, ins, OP_I8CONST);
3068                         ins->cil_code = ip;
3069                         ins->type = STACK_I8;
3070                         ++ip;
3071                         ins->inst_l = (gint64)read64 (ip);
3072                         ip += 8;
3073                         *sp++ = ins;
3074                         break;
3075                 case CEE_LDC_R4: {
3076                         float *f = g_malloc (sizeof (float));
3077                         CHECK_OPSIZE (5);
3078                         CHECK_STACK_OVF (1);
3079                         MONO_INST_NEW (cfg, ins, OP_R4CONST);
3080                         ins->type = STACK_R8;
3081                         ++ip;
3082                         readr4 (ip, f);
3083                         ins->inst_p0 = f;
3084                         ip += 4;
3085                         *sp++ = ins;                    
3086                         break;
3087                 }
3088                 case CEE_LDC_R8: {
3089                         double *d = g_malloc (sizeof (double));
3090                         CHECK_OPSIZE (9);
3091                         CHECK_STACK_OVF (1);
3092                         MONO_INST_NEW (cfg, ins, OP_R8CONST);
3093                         ins->type = STACK_R8;
3094                         ++ip;
3095                         readr8 (ip, d);
3096                         ins->inst_p0 = d;
3097                         ip += 8;
3098                         *sp++ = ins;                    
3099                         break;
3100                 }
3101                 case CEE_DUP: {
3102                         MonoInst *temp, *store;
3103                         CHECK_STACK (1);
3104                         CHECK_STACK_OVF (1);
3105                         sp--;
3106                         ins = *sp;
3107                 
3108                         /* 
3109                          * small optimization: if the loaded value was from a local already,
3110                          * just load it twice.
3111                          */
3112                         if (ins->ssa_op == MONO_SSA_LOAD && 
3113                             (ins->inst_i0->opcode == OP_LOCAL || ins->inst_i0->opcode == OP_ARG)) {
3114                                 sp++;
3115                                 MONO_INST_NEW (cfg, temp, 0);
3116                                 *temp = *ins;
3117                                 temp->cil_code = ip;
3118                                 *sp++ = temp;
3119                         } else {
3120                                 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
3121                                 temp->cil_code = ip;
3122                                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
3123                                 store->cil_code = ip;
3124                                 MONO_ADD_INS (bblock, store);
3125                                 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
3126                                 *sp++ = ins;
3127                                 ins->cil_code = ip;
3128                                 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
3129                                 *sp++ = ins;
3130                                 ins->cil_code = ip;
3131                         }
3132                         ++ip;
3133                         inline_costs += 2;
3134                         break;
3135                 }
3136                 case CEE_POP:
3137                         CHECK_STACK (1);
3138                         MONO_INST_NEW (cfg, ins, CEE_POP);
3139                         MONO_ADD_INS (bblock, ins);
3140                         ins->cil_code = ip++;
3141                         --sp;
3142                         ins->inst_i0 = *sp;
3143                         break;
3144                 case CEE_JMP:
3145                         CHECK_OPSIZE (5);
3146                         if (stack_start != sp)
3147                                 goto unverified;
3148                         MONO_INST_NEW (cfg, ins, CEE_JMP);
3149                         token = read32 (ip + 1);
3150                         /* FIXME: check the signature matches */
3151                         cmethod = mini_get_method (image, token, method);
3152                         ins->inst_p0 = cmethod;
3153                         MONO_ADD_INS (bblock, ins);
3154                         ip += 5;
3155                         start_new_bblock = 1;
3156                         break;
3157                 case CEE_CALLI:
3158                 case CEE_CALL:
3159                 case CEE_CALLVIRT: {
3160                         MonoInst *addr = NULL;
3161                         MonoMethodSignature *fsig = NULL;
3162                         int temp, array_rank = 0;
3163                         int virtual = *ip == CEE_CALLVIRT;
3164
3165                         CHECK_OPSIZE (5);
3166                         token = read32 (ip + 1);
3167
3168                         if (*ip == CEE_CALLI) {
3169                                 cmethod = NULL;
3170                                 CHECK_STACK (1);
3171                                 --sp;
3172                                 addr = *sp;
3173                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
3174                                         fsig = (MonoMethodSignature *)mono_method_get_wrapper_data (method, token);
3175                                 else
3176                                         fsig = mono_metadata_parse_signature (image, token);
3177
3178                                 n = fsig->param_count + fsig->hasthis;
3179                         } else {
3180                                 if (method->wrapper_type != MONO_WRAPPER_NONE) {
3181                                         cmethod =  (MonoMethod *)mono_method_get_wrapper_data (method, token);
3182                                 } else {
3183                                         cmethod = mini_get_method (image, token, method);
3184                                 }
3185
3186                                 if (!cmethod->klass->inited)
3187                                         mono_class_init (cmethod->klass);
3188
3189                                 if (cmethod->signature->pinvoke) {
3190 #ifdef MONO_USE_EXC_TABLES
3191                                         if (mono_method_blittable (cmethod)) {
3192                                                 fsig = cmethod->signature;
3193                                         } else {
3194 #endif
3195                                                 MonoMethod *wrapper = mono_marshal_get_native_wrapper (cmethod);
3196                                                 fsig = wrapper->signature;
3197 #ifdef MONO_USE_EXC_TABLES
3198                                         }
3199 #endif
3200                                 } else {
3201                                         fsig = mono_method_get_signature (cmethod, image, token);
3202                                 }
3203
3204                                 n = fsig->param_count + fsig->hasthis;
3205
3206                                 if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL &&
3207                                     cmethod->klass->parent == mono_defaults.array_class) {
3208                                         array_rank = cmethod->klass->rank;
3209                                 }
3210
3211                                 if (cmethod->string_ctor)
3212                                         g_assert_not_reached ();
3213
3214                         }
3215
3216                         CHECK_STACK (n);
3217
3218                         //g_assert (!virtual || fsig->hasthis);
3219
3220                         sp -= n;
3221
3222                         if (*ip != CEE_CALLI && check_call_signature (cfg, fsig, sp))
3223                                 goto unverified;
3224
3225                         if ((ins_flag & MONO_INST_TAILCALL) && cmethod && (*ip == CEE_CALL) && (mono_metadata_signature_equal (method->signature, cmethod->signature))) {
3226                                 int i;
3227                                 /* FIXME: This assumes the two methods has the same number and type of arguments */
3228                                 for (i = 0; i < n; ++i) {
3229                                         /* Check if argument is the same */
3230                                         NEW_ARGLOAD (cfg, ins, i);
3231                                         if ((ins->opcode == sp [i]->opcode) && (ins->inst_i0 == sp [i]->inst_i0))
3232                                                 continue;
3233
3234                                         /* Prevent argument from being register allocated */
3235                                         arg_array [i]->flags |= MONO_INST_VOLATILE;
3236                                         NEW_ARGSTORE (cfg, ins, i, sp [i]);
3237                                         ins->cil_code = ip;
3238                                         if (ins->opcode == CEE_STOBJ) {
3239                                                 NEW_ARGLOADA (cfg, ins, i);
3240                                                 handle_stobj (cfg, bblock, ins, sp [i], sp [i]->cil_code, ins->klass, FALSE, FALSE);
3241                                         }
3242                                         else
3243                                                 MONO_ADD_INS (bblock, ins);
3244                                 }
3245                                 MONO_INST_NEW (cfg, ins, CEE_JMP);
3246                                 ins->cil_code = ip;
3247                                 ins->inst_p0 = cmethod;
3248                                 ins->inst_p1 = arg_array [0];
3249                                 MONO_ADD_INS (bblock, ins);
3250                                 start_new_bblock = 1;
3251                                 /* skip CEE_RET as well */
3252                                 ip += 6;
3253                                 ins_flag = 0;
3254                                 break;
3255                         }
3256                         if (cmethod && (cfg->opt & MONO_OPT_INTRINS) && (ins = mini_get_opcode_for_method (cfg, cmethod, fsig, sp))) {
3257                                 ins->cil_code = ip;
3258
3259                                 if (MONO_TYPE_IS_VOID (fsig->ret)) {
3260                                         MONO_ADD_INS (bblock, ins);
3261                                 } else {
3262                                         type_to_eval_stack_type (fsig->ret, ins);
3263                                         *sp = ins;
3264                                         sp++;
3265                                 }
3266
3267                                 ip += 5;
3268                                 break;
3269                         }
3270
3271                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3272
3273                         if ((cfg->opt & MONO_OPT_INLINE) && cmethod &&
3274                             (!virtual || !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) || (cmethod->flags & METHOD_ATTRIBUTE_FINAL)) && 
3275                             mono_method_check_inlining (cfg, cmethod) &&
3276                             !g_list_find (dont_inline, cmethod)) {
3277                                 int costs;
3278                                 MonoBasicBlock *ebblock;
3279
3280                                 if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock))) {
3281                                         ip += 5;
3282                                         real_offset += 5;
3283
3284                                         GET_BBLOCK (cfg, bbhash, bblock, ip);
3285                                         ebblock->next_bb = bblock;
3286                                         link_bblock (cfg, ebblock, bblock);
3287
3288                                         if (!MONO_TYPE_IS_VOID (fsig->ret))
3289                                                 sp++;
3290
3291                                         /* indicates start of a new block, and triggers a load of all 
3292                                            stack arguments at bb boundarie */
3293                                         bblock = ebblock;
3294
3295                                         inline_costs += costs;
3296                                         break;
3297                                 }
3298                         }
3299                         
3300                         inline_costs += 10 * num_calls++;
3301
3302                         /* tail recursion elimination */
3303                         if ((cfg->opt & MONO_OPT_TAILC) && *ip == CEE_CALL && cmethod == method && ip [5] == CEE_RET) {
3304                                 gboolean has_vtargs = FALSE;
3305                                 int i;
3306                                 
3307                                 /* keep it simple */
3308                                 for (i =  fsig->param_count - 1; i >= 0; i--) {
3309                                         if (MONO_TYPE_ISSTRUCT (cmethod->signature->params [i])) 
3310                                                 has_vtargs = TRUE;
3311                                 }
3312
3313                                 if (!has_vtargs) {
3314                                         for (i = 0; i < n; ++i) {
3315                                                 NEW_ARGSTORE (cfg, ins, i, sp [i]);
3316                                                 ins->cil_code = ip;
3317                                                 MONO_ADD_INS (bblock, ins);
3318                                         }
3319                                         MONO_INST_NEW (cfg, ins, CEE_BR);
3320                                         ins->cil_code = ip;
3321                                         MONO_ADD_INS (bblock, ins);
3322                                         tblock = start_bblock->out_bb [0];
3323                                         link_bblock (cfg, bblock, tblock);
3324                                         ins->inst_target_bb = tblock;
3325                                         start_new_bblock = 1;
3326                                         ip += 5;
3327                                         
3328                                         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
3329                                                 /* just create a dummy - the value is never used */
3330                                                 ins = mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
3331                                                 NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
3332                                                 sp++;
3333                                         }
3334
3335                                         break;
3336                                 }
3337                         }
3338
3339                         if (*ip == CEE_CALLI) {
3340
3341                                 if ((temp = mono_emit_calli (cfg, bblock, fsig, sp, addr, ip)) != -1) {
3342                                         NEW_TEMPLOAD (cfg, *sp, temp);
3343                                         sp++;
3344                                 }
3345                                         
3346                         } else if (array_rank) {
3347                                 MonoInst *addr;
3348
3349                                 if (strcmp (cmethod->name, "Set") == 0) { /* array Set */ 
3350                                         if (sp [fsig->param_count]->type == STACK_OBJ) {
3351                                                 MonoInst *iargs [2];
3352
3353                                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
3354                                                 
3355                                                 iargs [0] = sp [0];
3356                                                 iargs [1] = sp [fsig->param_count];
3357                         
3358                                                 mono_emit_jit_icall (cfg, bblock, helper_stelem_ref_check, iargs, ip);                                          
3359                                         }
3360
3361                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, TRUE);
3362                                         NEW_INDSTORE (cfg, ins, addr, sp [fsig->param_count], fsig->params [fsig->param_count - 1]);
3363                                         ins->cil_code = ip;
3364                                         if (ins->opcode == CEE_STOBJ) {
3365                                                 handle_stobj (cfg, bblock, addr, sp [fsig->param_count], ip, mono_class_from_mono_type (fsig->params [fsig->param_count-1]), FALSE, FALSE);
3366                                         } else {
3367                                                 MONO_ADD_INS (bblock, ins);
3368                                         }
3369
3370                                 } else if (strcmp (cmethod->name, "Get") == 0) { /* array Get */
3371                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
3372                                         NEW_INDLOAD (cfg, ins, addr, fsig->ret);
3373                                         ins->cil_code = ip;
3374
3375                                         *sp++ = ins;
3376                                 } else if (strcmp (cmethod->name, "Address") == 0) { /* array Address */
3377                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
3378                                         *sp++ = addr;
3379                                 } else {
3380                                         g_assert_not_reached ();
3381                                 }
3382
3383                         } else {
3384                                 if (0 && CODE_IS_STLOC (ip + 5) && (!MONO_TYPE_ISSTRUCT (fsig->ret)) && (!MONO_TYPE_IS_VOID (fsig->ret) || cmethod->string_ctor)) {
3385                                         /* no need to spill */
3386                                         ins = (MonoInst*)mono_emit_method_call (cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL);
3387                                         *sp++ = ins;
3388                                 } else {
3389                                         if ((temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL)) != -1) {
3390                                                 NEW_TEMPLOAD (cfg, *sp, temp);
3391                                                 sp++;
3392                                         }
3393                                 }
3394                         }
3395
3396                         ip += 5;
3397                         break;
3398                 }
3399                 case CEE_RET:
3400                         if (cfg->method != method) {
3401                                 /* return from inlined methode */
3402                                 if (return_var) {
3403                                         MonoInst *store;
3404                                         CHECK_STACK (1);
3405                                         --sp;
3406                                         //g_assert (returnvar != -1);
3407                                         NEW_TEMPSTORE (cfg, store, return_var->inst_c0, *sp);
3408                                         store->cil_code = sp [0]->cil_code;
3409                                         if (store->opcode == CEE_STOBJ) {
3410                                                 g_assert_not_reached ();
3411                                                 NEW_TEMPLOADA (cfg, store, return_var->inst_c0);
3412                                                 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, return_var->klass, FALSE, FALSE);
3413                                         } else
3414                                                 MONO_ADD_INS (bblock, store);
3415                                 } 
3416                         } else {
3417                                 if (cfg->ret) {
3418                                         g_assert (!return_var);
3419                                         CHECK_STACK (1);
3420                                         --sp;
3421                                         MONO_INST_NEW (cfg, ins, CEE_NOP);
3422                                         ins->opcode = mono_type_to_stind (method->signature->ret);
3423                                         if (ins->opcode == CEE_STOBJ) {
3424                                                 NEW_RETLOADA (cfg, ins);
3425                                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
3426                                         } else {
3427                                                 ins->opcode = OP_SETRET;
3428                                                 ins->cil_code = ip;
3429                                                 ins->inst_i0 = *sp;;
3430                                                 ins->inst_i1 = NULL;
3431                                                 MONO_ADD_INS (bblock, ins);
3432                                         }
3433                                 }
3434                         }
3435                         if (sp != stack_start)
3436                                 goto unverified;
3437                         MONO_INST_NEW (cfg, ins, CEE_BR);
3438                         ins->cil_code = ip++;
3439                         ins->inst_target_bb = end_bblock;
3440                         MONO_ADD_INS (bblock, ins);
3441                         link_bblock (cfg, bblock, end_bblock);
3442                         start_new_bblock = 1;
3443                         break;
3444                 case CEE_BR_S:
3445                         CHECK_OPSIZE (2);
3446                         MONO_INST_NEW (cfg, ins, CEE_BR);
3447                         ins->cil_code = ip++;
3448                         MONO_ADD_INS (bblock, ins);
3449                         target = ip + 1 + (signed char)(*ip);
3450                         ++ip;
3451                         GET_BBLOCK (cfg, bbhash, tblock, target);
3452                         link_bblock (cfg, bblock, tblock);
3453                         CHECK_BBLOCK (target, ip, tblock);
3454                         ins->inst_target_bb = tblock;
3455                         if (sp != stack_start) {
3456                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3457                                 sp = stack_start;
3458                         }
3459                         start_new_bblock = 1;
3460                         inline_costs += 10;
3461                         break;
3462                 case CEE_BRFALSE_S:
3463                 case CEE_BRTRUE_S:
3464                         CHECK_OPSIZE (2);
3465                         CHECK_STACK (1);
3466                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
3467                         ins->cil_code = ip++;
3468                         target = ip + 1 + *(signed char*)ip;
3469                         ip++;
3470                         ADD_UNCOND (ins->opcode == CEE_BRTRUE);
3471                         if (sp != stack_start) {
3472                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3473                                 sp = stack_start;
3474                         }
3475                         inline_costs += 10;
3476                         break;
3477                 case CEE_BEQ_S:
3478                 case CEE_BGE_S:
3479                 case CEE_BGT_S:
3480                 case CEE_BLE_S:
3481                 case CEE_BLT_S:
3482                 case CEE_BNE_UN_S:
3483                 case CEE_BGE_UN_S:
3484                 case CEE_BGT_UN_S:
3485                 case CEE_BLE_UN_S:
3486                 case CEE_BLT_UN_S:
3487                         CHECK_OPSIZE (2);
3488                         CHECK_STACK (2);
3489                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
3490                         ins->cil_code = ip++;
3491                         target = ip + 1 + *(signed char*)ip;
3492                         ip++;
3493                         ADD_BINCOND (NULL);
3494                         if (sp != stack_start) {
3495                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3496                                 sp = stack_start;
3497                         }
3498                         inline_costs += 10;
3499                         break;
3500                 case CEE_BR:
3501                         CHECK_OPSIZE (5);
3502                         MONO_INST_NEW (cfg, ins, CEE_BR);
3503                         ins->cil_code = ip++;
3504                         MONO_ADD_INS (bblock, ins);
3505                         target = ip + 4 + (gint32)read32(ip);
3506                         ip += 4;
3507                         GET_BBLOCK (cfg, bbhash, tblock, target);
3508                         link_bblock (cfg, bblock, tblock);
3509                         CHECK_BBLOCK (target, ip, tblock);
3510                         ins->inst_target_bb = tblock;
3511                         if (sp != stack_start) {
3512                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3513                                 sp = stack_start;
3514                         }
3515                         start_new_bblock = 1;
3516                         inline_costs += 10;
3517                         break;
3518                 case CEE_BRFALSE:
3519                 case CEE_BRTRUE:
3520                         CHECK_OPSIZE (5);
3521                         CHECK_STACK (1);
3522                         MONO_INST_NEW (cfg, ins, *ip);
3523                         ins->cil_code = ip++;
3524                         target = ip + 4 + (gint32)read32(ip);
3525                         ip += 4;
3526                         ADD_UNCOND(ins->opcode == CEE_BRTRUE);
3527                         if (sp != stack_start) {
3528                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3529                                 sp = stack_start;
3530                         }
3531                         inline_costs += 10;
3532                         break;
3533                 case CEE_BEQ:
3534                 case CEE_BGE:
3535                 case CEE_BGT:
3536                 case CEE_BLE:
3537                 case CEE_BLT:
3538                 case CEE_BNE_UN:
3539                 case CEE_BGE_UN:
3540                 case CEE_BGT_UN:
3541                 case CEE_BLE_UN:
3542                 case CEE_BLT_UN:
3543                         CHECK_OPSIZE (5);
3544                         CHECK_STACK (2);
3545                         MONO_INST_NEW (cfg, ins, *ip);
3546                         ins->cil_code = ip++;
3547                         target = ip + 4 + (gint32)read32(ip);
3548                         ip += 4;
3549                         ADD_BINCOND(NULL);
3550                         if (sp != stack_start) {
3551                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3552                                 sp = stack_start;
3553                         }
3554                         inline_costs += 10;
3555                         break;
3556                 case CEE_SWITCH:
3557                         CHECK_OPSIZE (5);
3558                         CHECK_STACK (1);
3559                         n = read32 (ip + 1);
3560                         MONO_INST_NEW (cfg, ins, *ip);
3561                         --sp;
3562                         ins->inst_left = *sp;
3563                         if (ins->inst_left->type != STACK_I4) goto unverified;
3564                         ins->cil_code = ip;
3565                         ip += 5;
3566                         CHECK_OPSIZE (n * sizeof (guint32));
3567                         target = ip + n * sizeof (guint32);
3568                         MONO_ADD_INS (bblock, ins);
3569                         GET_BBLOCK (cfg, bbhash, tblock, target);
3570                         link_bblock (cfg, bblock, tblock);
3571                         ins->klass = GUINT_TO_POINTER (n);
3572                         ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (n + 1));
3573                         ins->inst_many_bb [n] = tblock;
3574
3575                         for (i = 0; i < n; ++i) {
3576                                 GET_BBLOCK (cfg, bbhash, tblock, target + (gint32)read32(ip));
3577                                 link_bblock (cfg, bblock, tblock);
3578                                 ins->inst_many_bb [i] = tblock;
3579                                 ip += 4;
3580                         }
3581                         if (sp != stack_start) {
3582                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3583                                 sp = stack_start;
3584                         }
3585                         inline_costs += 20;
3586                         break;
3587                 case CEE_LDIND_I1:
3588                 case CEE_LDIND_U1:
3589                 case CEE_LDIND_I2:
3590                 case CEE_LDIND_U2:
3591                 case CEE_LDIND_I4:
3592                 case CEE_LDIND_U4:
3593                 case CEE_LDIND_I8:
3594                 case CEE_LDIND_I:
3595                 case CEE_LDIND_R4:
3596                 case CEE_LDIND_R8:
3597                 case CEE_LDIND_REF:
3598                         CHECK_STACK (1);
3599                         MONO_INST_NEW (cfg, ins, *ip);
3600                         ins->cil_code = ip;
3601                         --sp;
3602                         ins->inst_i0 = *sp;
3603                         *sp++ = ins;
3604                         ins->type = ldind_type [*ip - CEE_LDIND_I1];
3605                         ins->flags |= ins_flag;
3606                         ins_flag = 0;
3607                         ++ip;
3608                         break;
3609                 case CEE_STIND_REF:
3610                 case CEE_STIND_I1:
3611                 case CEE_STIND_I2:
3612                 case CEE_STIND_I4:
3613                 case CEE_STIND_I8:
3614                 case CEE_STIND_R4:
3615                 case CEE_STIND_R8:
3616                         CHECK_STACK (2);
3617                         MONO_INST_NEW (cfg, ins, *ip);
3618                         ins->cil_code = ip++;
3619                         sp -= 2;
3620                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3621                         MONO_ADD_INS (bblock, ins);
3622                         ins->inst_i0 = sp [0];
3623                         ins->inst_i1 = sp [1];
3624                         ins->flags |= ins_flag;
3625                         ins_flag = 0;
3626                         inline_costs += 1;
3627                         break;
3628                 case CEE_ADD:
3629                 case CEE_SUB:
3630                 case CEE_MUL:
3631                 case CEE_DIV:
3632                 case CEE_DIV_UN:
3633                 case CEE_REM:
3634                 case CEE_REM_UN:
3635                 case CEE_AND:
3636                 case CEE_OR:
3637                 case CEE_XOR:
3638                 case CEE_SHL:
3639                 case CEE_SHR:
3640                 case CEE_SHR_UN:
3641                         CHECK_STACK (2);
3642                         ADD_BINOP (*ip);
3643                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
3644                                 MonoInst *store, *temp, *load;
3645                                 --sp;
3646                                 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
3647                                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
3648                                 store->cil_code = ins->cil_code;
3649                                 MONO_ADD_INS (bblock, store);
3650                                 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
3651                                 load->cil_code = ins->cil_code;
3652                                 *sp++ = load;
3653                                 /*g_print ("found emulation for %d\n", ins->opcode);*/
3654                         }
3655                         ip++;
3656                         break;
3657                 case CEE_NEG:
3658                 case CEE_NOT:
3659                 case CEE_CONV_I1:
3660                 case CEE_CONV_I2:
3661                 case CEE_CONV_I4:
3662                 case CEE_CONV_R4:
3663                 case CEE_CONV_R8:
3664                 case CEE_CONV_U4:
3665                 case CEE_CONV_I8:
3666                 case CEE_CONV_U8:
3667                 case CEE_CONV_OVF_I8:
3668                 case CEE_CONV_OVF_U8:
3669                 case CEE_CONV_R_UN:
3670                         CHECK_STACK (1);
3671                         ADD_UNOP (*ip);
3672                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
3673                                 MonoInst *store, *temp, *load;
3674                                 --sp;
3675                                 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
3676                                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
3677                                 store->cil_code = ins->cil_code;
3678                                 MONO_ADD_INS (bblock, store);
3679                                 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
3680                                 load->cil_code = ins->cil_code;
3681                                 *sp++ = load;
3682                                 /*g_print ("found emulation for %d\n", ins->opcode);*/
3683                         }
3684                         ip++;                   
3685                         break;
3686                 case CEE_CONV_OVF_I4:
3687                 case CEE_CONV_OVF_I1:
3688                 case CEE_CONV_OVF_I2:
3689                 case CEE_CONV_OVF_I:
3690                 case CEE_CONV_OVF_U:
3691                         CHECK_STACK (1);
3692
3693                         if (sp [-1]->type == STACK_R8) {
3694                                 ADD_UNOP (CEE_CONV_OVF_I8);
3695                                 ADD_UNOP (*ip);
3696                         } else {
3697                                 ADD_UNOP (*ip);
3698                         }
3699
3700                         ip++;
3701                         break;
3702                 case CEE_CONV_OVF_U1:
3703                 case CEE_CONV_OVF_U2:
3704                 case CEE_CONV_OVF_U4:
3705                         CHECK_STACK (1);
3706
3707                         if (sp [-1]->type == STACK_R8) {
3708                                 ADD_UNOP (CEE_CONV_OVF_U8);
3709                                 ADD_UNOP (*ip);
3710                         } else {
3711                                 ADD_UNOP (*ip);
3712                         }
3713
3714                         ip++;
3715                         break;
3716                 case CEE_CONV_OVF_I1_UN:
3717                 case CEE_CONV_OVF_I2_UN:
3718                 case CEE_CONV_OVF_I4_UN:
3719                 case CEE_CONV_OVF_I8_UN:
3720                 case CEE_CONV_OVF_U1_UN:
3721                 case CEE_CONV_OVF_U2_UN:
3722                 case CEE_CONV_OVF_U4_UN:
3723                 case CEE_CONV_OVF_U8_UN:
3724                 case CEE_CONV_OVF_I_UN:
3725                 case CEE_CONV_OVF_U_UN:
3726                         CHECK_STACK (1);
3727                         ADD_UNOP (*ip);
3728                         ip++;
3729                         break;
3730                 case CEE_CPOBJ:
3731                         CHECK_OPSIZE (5);
3732                         CHECK_STACK (2);
3733                         token = read32 (ip + 1);
3734                         if (method->wrapper_type != MONO_WRAPPER_NONE)
3735                                 klass = mono_method_get_wrapper_data (method, token);
3736                         else
3737                                 klass = mono_class_get (image, token);
3738
3739                         mono_class_init (klass);
3740                         if (klass->byval_arg.type == MONO_TYPE_VAR)
3741                                 klass = TYPE_PARAM_TO_CLASS (klass->byval_arg.data.generic_param->num);
3742                         else if (klass->byval_arg.type == MONO_TYPE_MVAR)
3743                                 klass = MTYPE_PARAM_TO_CLASS (klass->byval_arg.data.generic_param->num);
3744                         sp -= 2;
3745                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
3746                                 MonoInst *store, *load;
3747                                 MONO_INST_NEW (cfg, load, CEE_LDIND_REF);
3748                                 load->cil_code = ip;
3749                                 load->inst_i0 = sp [1];
3750                                 load->type = ldind_type [CEE_LDIND_REF];
3751                                 load->flags |= ins_flag;
3752                                 MONO_INST_NEW (cfg, store, CEE_STIND_REF);
3753                                 store->cil_code = ip;
3754                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
3755                                 MONO_ADD_INS (bblock, store);
3756                                 store->inst_i0 = sp [0];
3757                                 store->inst_i1 = load;
3758                                 store->flags |= ins_flag;
3759                         } else {
3760                                 n = mono_class_value_size (klass, NULL);
3761                                 if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
3762                                         MonoInst *copy;
3763                                         MONO_INST_NEW (cfg, copy, OP_MEMCPY);
3764                                         copy->inst_left = sp [0];
3765                                         copy->inst_right = sp [1];
3766                                         copy->cil_code = ip;
3767                                         copy->unused = n;
3768                                         MONO_ADD_INS (bblock, copy);
3769                                 } else {
3770                                         MonoInst *iargs [3];
3771                                         iargs [0] = sp [0];
3772                                         iargs [1] = sp [1];
3773                                         NEW_ICONST (cfg, iargs [2], n);
3774                                         iargs [2]->cil_code = ip;
3775
3776                                         mono_emit_jit_icall (cfg, bblock, helper_memcpy, iargs, ip);
3777                                 }
3778                         }
3779                         ins_flag = 0;
3780                         ip += 5;
3781                         break;
3782                 case CEE_LDOBJ: {
3783                         MonoInst *iargs [3];
3784                         CHECK_OPSIZE (5);
3785                         CHECK_STACK (1);
3786                         --sp;
3787                         token = read32 (ip + 1);
3788                         if (method->wrapper_type != MONO_WRAPPER_NONE)
3789                                 klass = mono_method_get_wrapper_data (method, token);
3790                         else
3791                                 klass = mono_class_get (image, token);
3792
3793                         mono_class_init (klass);
3794                         if (klass->byval_arg.type == MONO_TYPE_VAR)
3795                                 klass = TYPE_PARAM_TO_CLASS (klass->byval_arg.data.generic_param->num);
3796                         else if (klass->byval_arg.type == MONO_TYPE_MVAR)
3797                                 klass = MTYPE_PARAM_TO_CLASS (klass->byval_arg.data.generic_param->num);
3798                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
3799                                 MONO_INST_NEW (cfg, ins, CEE_LDIND_REF);
3800                                 ins->cil_code = ip;
3801                                 ins->inst_i0 = sp [0];
3802                                 ins->type = ldind_type [CEE_LDIND_REF];
3803                                 ins->flags |= ins_flag;
3804                                 ins_flag = 0;
3805                                 *sp++ = ins;
3806                                 ip += 5;
3807                                 break;
3808                         }
3809                         n = mono_class_value_size (klass, NULL);
3810                         ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
3811                         NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
3812                         if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
3813                                 MonoInst *copy;
3814                                 MONO_INST_NEW (cfg, copy, OP_MEMCPY);
3815                                 copy->inst_left = iargs [0];
3816                                 copy->inst_right = *sp;
3817                                 copy->cil_code = ip;
3818                                 copy->unused = n;
3819                                 MONO_ADD_INS (bblock, copy);
3820                         } else {
3821                                 iargs [1] = *sp;
3822                                 NEW_ICONST (cfg, iargs [2], n);
3823                                 iargs [2]->cil_code = ip;
3824
3825                                 mono_emit_jit_icall (cfg, bblock, helper_memcpy, iargs, ip);
3826                         }
3827                         NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
3828                         ++sp;
3829                         ip += 5;
3830                         ins_flag = 0;
3831                         inline_costs += 1;
3832                         break;
3833                 }
3834                 case CEE_LDSTR:
3835                         CHECK_STACK_OVF (1);
3836                         CHECK_OPSIZE (5);
3837                         n = read32 (ip + 1);
3838
3839                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
3840                                 int temp;
3841                                 MonoInst *iargs [1];
3842
3843                                 NEW_PCONST (cfg, iargs [0], mono_method_get_wrapper_data (method, n));                          
3844                                 temp = mono_emit_jit_icall (cfg, bblock, mono_string_new_wrapper, iargs, ip);
3845                                 NEW_TEMPLOAD (cfg, *sp, temp);
3846
3847                         } else {
3848
3849                                 if (cfg->opt & MONO_OPT_SHARED) {
3850                                         int temp;
3851                                         MonoInst *iargs [3];
3852
3853                                         if (mono_compile_aot) {
3854                                                 cfg->ldstr_list = g_list_prepend (cfg->ldstr_list, (gpointer)n);
3855                                         }
3856
3857                                         NEW_TEMPLOAD (cfg, iargs [0], mono_get_domainvar (cfg)->inst_c0);
3858                                         NEW_IMAGECONST (cfg, iargs [1], image);
3859                                         NEW_ICONST (cfg, iargs [2], mono_metadata_token_index (n));
3860                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldstr, iargs, ip);
3861                                         NEW_TEMPLOAD (cfg, *sp, temp);
3862                                         mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
3863                                 } else {
3864                                         if (mono_compile_aot)
3865                                                 NEW_LDSTRCONST (cfg, ins, image, n);
3866                                         else {
3867                                                 NEW_PCONST (cfg, ins, NULL);
3868                                                 ins->cil_code = ip;
3869                                                 ins->type = STACK_OBJ;
3870                                                 ins->inst_p0 = mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
3871                                         }
3872                                         *sp = ins;
3873                                 }
3874                         }
3875
3876                         sp++;
3877                         ip += 5;
3878                         break;
3879                 case CEE_NEWOBJ: {
3880                         MonoInst *iargs [2];
3881                         MonoMethodSignature *fsig;
3882                         int temp;
3883
3884                         CHECK_OPSIZE (5);
3885                         token = read32 (ip + 1);
3886                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
3887                                 cmethod = mono_method_get_wrapper_data (method, token);
3888                         } else
3889                                 cmethod = mini_get_method (image, token, method);
3890                         fsig = mono_method_get_signature (cmethod, image, token);
3891
3892                         mono_class_init (cmethod->klass);
3893
3894                         n = fsig->param_count;
3895                         CHECK_STACK (n);
3896
3897                         /* move the args to allow room for 'this' in the first position */
3898                         while (n--) {
3899                                 --sp;
3900                                 sp [1] = sp [0];
3901                         }
3902
3903                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3904                         
3905
3906                         if (cmethod->klass->parent == mono_defaults.array_class) {
3907                                 NEW_METHODCONST (cfg, *sp, cmethod);
3908                                 temp = mono_emit_native_call (cfg, bblock, mono_array_new_va, fsig, sp, ip, FALSE);
3909
3910                         } else if (cmethod->string_ctor) {
3911                                 /* we simply pass a null pointer */
3912                                 NEW_PCONST (cfg, *sp, NULL); 
3913                                 /* now call the string ctor */
3914                                 temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, NULL);
3915                         } else {
3916                                 if (cmethod->klass->valuetype) {
3917                                         iargs [0] = mono_compile_create_var (cfg, &cmethod->klass->byval_arg, OP_LOCAL);
3918                                         temp = iargs [0]->inst_c0;
3919                                         NEW_TEMPLOADA (cfg, *sp, temp);
3920                                 } else {
3921                                         if (cfg->opt & MONO_OPT_SHARED) {
3922                                                 NEW_DOMAINCONST (cfg, iargs [0]);
3923                                                 NEW_CLASSCONST (cfg, iargs [1], cmethod->klass);
3924
3925                                                 temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
3926                                         } else {
3927                                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
3928                                                 NEW_VTABLECONST (cfg, iargs [0], vtable);
3929                                                 if (cmethod->klass->has_finalize || cmethod->klass->marshalbyref || (cfg->prof_options & MONO_PROFILE_ALLOCATIONS))
3930                                                         temp = mono_emit_jit_icall (cfg, bblock, mono_object_new_specific, iargs, ip);
3931                                                 else
3932                                                         temp = mono_emit_jit_icall (cfg, bblock, mono_object_new_fast, iargs, ip);
3933                                         }
3934                                         NEW_TEMPLOAD (cfg, *sp, temp);
3935                                 }
3936
3937                                 if ((cfg->opt & MONO_OPT_INLINE) && cmethod &&
3938                                     mono_method_check_inlining (cfg, cmethod) &&
3939                                     !mono_class_is_subclass_of (cmethod->klass, mono_defaults.exception_class, FALSE) &&
3940                                     !g_list_find (dont_inline, cmethod)) {
3941                                         int costs;
3942                                         MonoBasicBlock *ebblock;
3943                                         if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock))) {
3944
3945                                                 ip += 5;
3946                                                 real_offset += 5;
3947                                                 
3948                                                 GET_BBLOCK (cfg, bbhash, bblock, ip);
3949                                                 ebblock->next_bb = bblock;
3950                                                 link_bblock (cfg, ebblock, bblock);
3951
3952                                                 NEW_TEMPLOAD (cfg, *sp, temp);
3953                                                 sp++;
3954
3955                                                 /* indicates start of a new block, and triggers a load 
3956                                                    of all stack arguments at bb boundarie */
3957                                                 bblock = ebblock;
3958
3959                                                 inline_costs += costs;
3960                                                 break;
3961                                                 
3962                                         } else {
3963                                                 mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, sp[0]);
3964                                         }
3965                                 } else {
3966                                         /* now call the actual ctor */
3967                                         mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, sp[0]);
3968                                 }
3969                         }
3970
3971                         NEW_TEMPLOAD (cfg, *sp, temp);
3972                         sp++;
3973                         
3974                         ip += 5;
3975                         inline_costs += 5;
3976                         break;
3977                 }
3978                 case CEE_ISINST:
3979                         CHECK_STACK (1);
3980                         --sp;
3981                         CHECK_OPSIZE (5);
3982                         klass = mono_class_get (image, read32 (ip + 1));
3983                         mono_class_init (klass);
3984                 
3985                         if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
3986                         
3987                                 MonoMethod *mono_isinst;
3988                                 MonoInst *iargs [1];
3989                                 MonoBasicBlock *ebblock;
3990                                 int costs;
3991                                 int temp;
3992                                 
3993                                 mono_isinst = mono_marshal_get_isinst (klass); 
3994                                 iargs [0] = sp [0];
3995                                 
3996                                 costs = inline_method (cfg, mono_isinst, mono_isinst->signature, bblock, 
3997                                                            iargs, ip, real_offset, dont_inline, &ebblock);
3998                         
3999                                 g_assert (costs > 0);
4000                                 
4001                                 ip += 5;
4002                                 real_offset += 5;
4003                         
4004                                 GET_BBLOCK (cfg, bbhash, bblock, ip);
4005                                 ebblock->next_bb = bblock;
4006                                 link_bblock (cfg, ebblock, bblock);
4007
4008                                 temp = iargs [0]->inst_i0->inst_c0;
4009                                 NEW_TEMPLOAD (cfg, *sp, temp);
4010                                 
4011                                 sp++;
4012                                 bblock = ebblock;
4013                                 inline_costs += costs;
4014
4015                         }
4016                         else {
4017                                 MONO_INST_NEW (cfg, ins, *ip);
4018                                 ins->type = STACK_OBJ;
4019                                 ins->inst_left = *sp;
4020                                 ins->inst_newa_class = klass;
4021                                 ins->cil_code = ip;
4022                                 *sp++ = ins;
4023                                 ip += 5;
4024                         }
4025                         break;
4026                 case CEE_UNBOX_ANY: {
4027                         MonoInst *add, *vtoffset;
4028                         MonoInst *iargs [3];
4029
4030                         CHECK_STACK (1);
4031                         --sp;
4032                         CHECK_OPSIZE (5);
4033                         token = read32 (ip + 1);
4034                         if (method->wrapper_type != MONO_WRAPPER_NONE)
4035                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
4036                         else 
4037                                 klass = mono_class_get (image, token);
4038                         mono_class_init (klass);
4039
4040                         if (klass->byval_arg.type == MONO_TYPE_VAR)
4041                                 klass = TYPE_PARAM_TO_CLASS (klass->byval_arg.data.generic_param->num);
4042                         else if (klass->byval_arg.type == MONO_TYPE_MVAR)
4043                                 klass = MTYPE_PARAM_TO_CLASS (klass->byval_arg.data.generic_param->num);
4044
4045                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
4046                                 /* CASTCLASS */
4047                                 if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
4048                                         MonoMethod *mono_castclass;
4049                                         MonoInst *iargs [1];
4050                                         MonoBasicBlock *ebblock;
4051                                         int costs;
4052                                         int temp;
4053                                         
4054                                         mono_castclass = mono_marshal_get_castclass (klass); 
4055                                         iargs [0] = sp [0];
4056                                         
4057                                         costs = inline_method (cfg, mono_castclass, mono_castclass->signature, bblock, 
4058                                                                    iargs, ip, real_offset, dont_inline, &ebblock);
4059                                 
4060                                         g_assert (costs > 0);
4061                                         
4062                                         ip += 5;
4063                                         real_offset += 5;
4064                                 
4065                                         GET_BBLOCK (cfg, bbhash, bblock, ip);
4066                                         ebblock->next_bb = bblock;
4067                                         link_bblock (cfg, ebblock, bblock);
4068         
4069                                         temp = iargs [0]->inst_i0->inst_c0;
4070                                         NEW_TEMPLOAD (cfg, *sp, temp);
4071                                         
4072                                         sp++;
4073                                         bblock = ebblock;
4074                                         inline_costs += costs;                          
4075                                 }
4076                                 else {
4077                                         MONO_INST_NEW (cfg, ins, CEE_CASTCLASS);
4078                                         ins->type = STACK_OBJ;
4079                                         ins->inst_left = *sp;
4080                                         ins->klass = klass;
4081                                         ins->inst_newa_class = klass;
4082                                         ins->cil_code = ip;
4083                                         *sp++ = ins;
4084                                 }
4085                                 ip += 5;
4086                                 break;
4087                         }
4088
4089                         MONO_INST_NEW (cfg, ins, OP_UNBOXCAST);
4090                         ins->type = STACK_OBJ;
4091                         ins->inst_left = *sp;
4092                         ins->klass = klass;
4093                         ins->inst_newa_class = klass;
4094                         ins->cil_code = ip;
4095
4096                         MONO_INST_NEW (cfg, add, CEE_ADD);
4097                         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
4098                         add->inst_left = ins;
4099                         add->inst_right = vtoffset;
4100                         add->type = STACK_MP;
4101                         *sp = add;
4102                         ip += 5;
4103                         /* LDOBJ impl */
4104                         n = mono_class_value_size (klass, NULL);
4105                         ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
4106                         NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
4107                         if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
4108                                 MonoInst *copy;
4109                                 MONO_INST_NEW (cfg, copy, OP_MEMCPY);
4110                                 copy->inst_left = iargs [0];
4111                                 copy->inst_right = *sp;
4112                                 copy->cil_code = ip;
4113                                 copy->unused = n;
4114                                 MONO_ADD_INS (bblock, copy);
4115                         } else {
4116                                 iargs [1] = *sp;
4117                                 NEW_ICONST (cfg, iargs [2], n);
4118                                 iargs [2]->cil_code = ip;
4119
4120                                 mono_emit_jit_icall (cfg, bblock, helper_memcpy, iargs, ip);
4121                         }
4122                         NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
4123                         ++sp;
4124                         inline_costs += 2;
4125                         break;
4126                 }
4127                 case CEE_UNBOX: {
4128                         MonoInst *add, *vtoffset;
4129
4130                         CHECK_STACK (1);
4131                         --sp;
4132                         CHECK_OPSIZE (5);
4133                         token = read32 (ip + 1);
4134                         if (method->wrapper_type != MONO_WRAPPER_NONE)
4135                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
4136                         else 
4137                                 klass = mono_class_get (image, token);
4138                         mono_class_init (klass);
4139
4140                         if (klass->byval_arg.type == MONO_TYPE_VAR)
4141                                 klass = TYPE_PARAM_TO_CLASS (klass->byval_arg.data.generic_param->num);
4142                         else if (klass->byval_arg.type == MONO_TYPE_MVAR)
4143                                 klass = MTYPE_PARAM_TO_CLASS (klass->byval_arg.data.generic_param->num);
4144
4145                         MONO_INST_NEW (cfg, ins, OP_UNBOXCAST);
4146                         ins->type = STACK_OBJ;
4147                         ins->inst_left = *sp;
4148                         ins->klass = klass;
4149                         ins->inst_newa_class = klass;
4150                         ins->cil_code = ip;
4151
4152                         MONO_INST_NEW (cfg, add, CEE_ADD);
4153                         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
4154                         add->inst_left = ins;
4155                         add->inst_right = vtoffset;
4156                         add->type = STACK_MP;
4157                         *sp++ = add;
4158                         ip += 5;
4159                         inline_costs += 2;
4160                         break;
4161                 }
4162                 case CEE_CASTCLASS:
4163                         CHECK_STACK (1);
4164                         --sp;
4165                         CHECK_OPSIZE (5);
4166                         klass = mono_class_get (image, read32 (ip + 1));
4167                         mono_class_init (klass);
4168                         if (klass->byval_arg.type == MONO_TYPE_VAR)
4169                                 klass = TYPE_PARAM_TO_CLASS (klass->byval_arg.data.generic_param->num);
4170                         else if (klass->byval_arg.type == MONO_TYPE_MVAR)
4171                                 klass = MTYPE_PARAM_TO_CLASS (klass->byval_arg.data.generic_param->num);
4172                 
4173                         if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
4174                                 
4175                                 MonoMethod *mono_castclass;
4176                                 MonoInst *iargs [1];
4177                                 MonoBasicBlock *ebblock;
4178                                 int costs;
4179                                 int temp;
4180                                 
4181                                 mono_castclass = mono_marshal_get_castclass (klass); 
4182                                 iargs [0] = sp [0];
4183                                 
4184                                 costs = inline_method (cfg, mono_castclass, mono_castclass->signature, bblock, 
4185                                                            iargs, ip, real_offset, dont_inline, &ebblock);
4186                         
4187                                 g_assert (costs > 0);
4188                                 
4189                                 ip += 5;
4190                                 real_offset += 5;
4191                         
4192                                 GET_BBLOCK (cfg, bbhash, bblock, ip);
4193                                 ebblock->next_bb = bblock;
4194                                 link_bblock (cfg, ebblock, bblock);
4195
4196                                 temp = iargs [0]->inst_i0->inst_c0;
4197                                 NEW_TEMPLOAD (cfg, *sp, temp);
4198                                 
4199                                 sp++;
4200                                 bblock = ebblock;
4201                                 inline_costs += costs;
4202                         }
4203                         else {
4204                                 MONO_INST_NEW (cfg, ins, *ip);
4205                                 ins->type = STACK_OBJ;
4206                                 ins->inst_left = *sp;
4207                                 ins->klass = klass;
4208                                 ins->inst_newa_class = klass;
4209                                 ins->cil_code = ip;
4210                                 *sp++ = ins;
4211                                 ip += 5;
4212                         }
4213                         break;
4214                 case CEE_THROW:
4215                         CHECK_STACK (1);
4216                         MONO_INST_NEW (cfg, ins, *ip);
4217                         --sp;
4218                         ins->inst_left = *sp;
4219                         ins->cil_code = ip++;
4220                         MONO_ADD_INS (bblock, ins);
4221                         sp = stack_start;
4222                         start_new_bblock = 1;
4223                         break;
4224                 case CEE_LDFLD:
4225                 case CEE_LDFLDA:
4226                 case CEE_STFLD: {
4227                         MonoInst *offset_ins;
4228                         MonoClassField *field;
4229                         MonoBasicBlock *ebblock;
4230                         int costs;
4231                         guint foffset;
4232
4233                         if (*ip == CEE_STFLD) {
4234                                 CHECK_STACK (2);
4235                                 sp -= 2;
4236                         } else {
4237                                 CHECK_STACK (1);
4238                                 --sp;
4239                         }
4240                         // FIXME: enable this test later.
4241                         //if (sp [0]->type != STACK_OBJ && sp [0]->type != STACK_MP)
4242                         //      goto unverified;
4243                         CHECK_OPSIZE (5);
4244                         token = read32 (ip + 1);
4245                         field = mono_field_from_token (image, token, &klass);
4246                         if (field->parent->gen_params)
4247                                 field = get_generic_field_inst (field, method->klass, &klass);
4248                         else if (field->parent->generic_inst && method->klass->generic_inst)
4249                                 field = inflate_generic_field (field, method->klass, &klass);
4250                         mono_class_init (klass);
4251
4252                         foffset = klass->valuetype? field->offset - sizeof (MonoObject): field->offset;
4253                         /* FIXME: mark instructions for use in SSA */
4254                         if (*ip == CEE_STFLD) {
4255                                 if ((klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) || klass->contextbound) {
4256                                         MonoMethod *stfld_wrapper = mono_marshal_get_stfld_wrapper (field->type); 
4257                                         MonoInst *iargs [5];
4258
4259                                         iargs [0] = sp [0];
4260                                         NEW_CLASSCONST (cfg, iargs [1], klass);
4261                                         NEW_FIELDCONST (cfg, iargs [2], field);
4262                                         NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : 
4263                                                     field->offset);
4264                                         iargs [4] = sp [1];
4265
4266                                         if (cfg->opt & MONO_OPT_INLINE) {
4267                                                 costs = inline_method (cfg, stfld_wrapper, stfld_wrapper->signature, bblock, 
4268                                                                        iargs, ip, real_offset, dont_inline, &ebblock);
4269                                                 g_assert (costs > 0);
4270                                                       
4271                                                 ip += 5;
4272                                                 real_offset += 5;
4273
4274                                                 GET_BBLOCK (cfg, bbhash, bblock, ip);
4275                                                 ebblock->next_bb = bblock;
4276                                                 link_bblock (cfg, ebblock, bblock);
4277
4278                                                 /* indicates start of a new block, and triggers a load 
4279                                                    of all stack arguments at bb boundarie */
4280                                                 bblock = ebblock;
4281
4282                                                 inline_costs += costs;
4283                                                 break;
4284                                         } else {
4285                                                 mono_emit_method_call_spilled (cfg, bblock, stfld_wrapper, stfld_wrapper->signature, iargs, ip, NULL);
4286                                         }
4287                                 } else {
4288                                         MonoInst *store;
4289                                         NEW_ICONST (cfg, offset_ins, foffset);
4290                                         MONO_INST_NEW (cfg, ins, CEE_ADD);
4291                                         ins->cil_code = ip;
4292                                         ins->inst_left = *sp;
4293                                         ins->inst_right = offset_ins;
4294                                         ins->type = STACK_MP;
4295
4296                                         MONO_INST_NEW (cfg, store, mono_type_to_stind (field->type));
4297                                         store->cil_code = ip;
4298                                         store->inst_left = ins;
4299                                         store->inst_right = sp [1];
4300                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
4301                                         store->flags |= ins_flag;
4302                                         ins_flag = 0;
4303                                         if (store->opcode == CEE_STOBJ) {
4304                                                 handle_stobj (cfg, bblock, ins, sp [1], ip, 
4305                                                               mono_class_from_mono_type (field->type), FALSE, FALSE);
4306                                         } else
4307                                                 MONO_ADD_INS (bblock, store);
4308                                 }
4309                         } else {
4310                                 if ((klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) || klass->contextbound) {
4311                                         /* fixme: we need to inline that call somehow */
4312                                         MonoMethod *ldfld_wrapper = mono_marshal_get_ldfld_wrapper (field->type); 
4313                                         MonoInst *iargs [4];
4314                                         int temp;
4315                                         
4316                                         iargs [0] = sp [0];
4317                                         NEW_CLASSCONST (cfg, iargs [1], klass);
4318                                         NEW_FIELDCONST (cfg, iargs [2], field);
4319                                         NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
4320                                         if (cfg->opt & MONO_OPT_INLINE) {
4321                                                 costs = inline_method (cfg, ldfld_wrapper, ldfld_wrapper->signature, bblock, 
4322                                                                        iargs, ip, real_offset, dont_inline, &ebblock);
4323                                                 g_assert (costs > 0);
4324                                                       
4325                                                 ip += 5;
4326                                                 real_offset += 5;
4327
4328                                                 GET_BBLOCK (cfg, bbhash, bblock, ip);
4329                                                 ebblock->next_bb = bblock;
4330                                                 link_bblock (cfg, ebblock, bblock);
4331
4332                                                 temp = iargs [0]->inst_i0->inst_c0;
4333
4334                                                 if (*ip == CEE_LDFLDA) {
4335                                                         /* not sure howto handle this */
4336                                                         NEW_TEMPLOADA (cfg, *sp, temp);
4337                                                 } else {
4338                                                         NEW_TEMPLOAD (cfg, *sp, temp);
4339                                                 }
4340                                                 sp++;
4341
4342                                                 /* indicates start of a new block, and triggers a load of
4343                                                    all stack arguments at bb boundarie */
4344                                                 bblock = ebblock;
4345                                                 
4346                                                 inline_costs += costs;
4347                                                 break;
4348                                         } else {
4349                                                 temp = mono_emit_method_call_spilled (cfg, bblock, ldfld_wrapper, ldfld_wrapper->signature, iargs, ip, NULL);
4350                                                 if (*ip == CEE_LDFLDA) {
4351                                                         /* not sure howto handle this */
4352                                                         NEW_TEMPLOADA (cfg, *sp, temp);
4353                                                 } else {
4354                                                         NEW_TEMPLOAD (cfg, *sp, temp);
4355                                                 }
4356                                                 sp++;
4357                                         }
4358                                 } else {
4359                                         NEW_ICONST (cfg, offset_ins, foffset);
4360                                         MONO_INST_NEW (cfg, ins, CEE_ADD);
4361                                         ins->cil_code = ip;
4362                                         ins->inst_left = *sp;
4363                                         ins->inst_right = offset_ins;
4364                                         ins->type = STACK_MP;
4365
4366                                         if (*ip == CEE_LDFLDA) {
4367                                                 *sp++ = ins;
4368                                         } else {
4369                                                 MonoInst *load;
4370                                                 MONO_INST_NEW (cfg, load, mono_type_to_ldind (field->type));
4371                                                 type_to_eval_stack_type (field->type, load);
4372                                                 load->cil_code = ip;
4373                                                 load->inst_left = ins;
4374                                                 load->flags |= ins_flag;
4375                                                 ins_flag = 0;
4376                                                 *sp++ = load;
4377                                         }
4378                                 }
4379                         }
4380                         ip += 5;
4381                         break;
4382                 }
4383                 case CEE_LDSFLD:
4384                 case CEE_LDSFLDA:
4385                 case CEE_STSFLD: {
4386                         MonoClassField *field;
4387                         gpointer addr = NULL;
4388
4389                         CHECK_OPSIZE (5);
4390                         token = read32 (ip + 1);
4391
4392                         field = mono_field_from_token (image, token, &klass);
4393                         if (field->parent->gen_params)
4394                                 field = get_generic_field_inst (field, method->klass, &klass);
4395                         else if (field->parent->generic_inst && method->klass->generic_inst)
4396                                 field = inflate_generic_field (field, method->klass, &klass);
4397                         mono_class_init (klass);
4398
4399                         handle_loaded_temps (cfg, bblock, stack_start, sp);
4400
4401                         if (cfg->domain->special_static_fields)
4402                                 addr = g_hash_table_lookup (cfg->domain->special_static_fields, field);
4403
4404                         if ((cfg->opt & MONO_OPT_SHARED) || (mono_compile_aot && addr)) {
4405                                 int temp;
4406                                 MonoInst *iargs [2];
4407                                 g_assert (field->parent);
4408                                 NEW_TEMPLOAD (cfg, iargs [0], mono_get_domainvar (cfg)->inst_c0);
4409                                 NEW_FIELDCONST (cfg, iargs [1], field);
4410                                 temp = mono_emit_jit_icall (cfg, bblock, mono_class_static_field_address, iargs, ip);
4411                                 NEW_TEMPLOAD (cfg, ins, temp);
4412                         } else {
4413                                 MonoVTable *vtable;
4414                                 vtable = mono_class_vtable (cfg->domain, klass);
4415                                 if (!addr) {
4416                                         if ((!vtable->initialized || mono_compile_aot) && !(klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) && mono_class_needs_cctor_run (klass, method)) {
4417                                                 guint8 *tramp = mono_create_class_init_trampoline (vtable);
4418                                                 mono_emit_native_call (cfg, bblock, tramp, 
4419                                                                                            helper_sig_class_init_trampoline,
4420                                                                                            NULL, ip, FALSE);
4421                                                 if (cfg->verbose_level > 2)
4422                                                         g_print ("class %s.%s needs init call for %s\n", klass->name_space, klass->name, field->name);
4423                                         } else {
4424                                                 if (cfg->run_cctors)
4425                                                         mono_runtime_class_init (vtable);
4426                                         }
4427                                         addr = (char*)vtable->data + field->offset;
4428
4429                                         if (mono_compile_aot)
4430                                                 NEW_SFLDACONST (cfg, ins, field);
4431                                         else
4432                                                 NEW_PCONST (cfg, ins, addr);
4433                                         ins->cil_code = ip;
4434                                 } else {
4435                                         /* 
4436                                          * insert call to mono_threads_get_static_data (GPOINTER_TO_UINT (addr)) 
4437                                          * This could be later optimized to do just a couple of
4438                                          * memory dereferences with constant offsets.
4439                                          */
4440                                         int temp;
4441                                         MonoInst *iargs [1];
4442                                         NEW_ICONST (cfg, iargs [0], GPOINTER_TO_UINT (addr));
4443                                         temp = mono_emit_jit_icall (cfg, bblock, mono_get_special_static_data, iargs, ip);
4444                                         NEW_TEMPLOAD (cfg, ins, temp);
4445                                 }
4446                         }
4447
4448                         /* FIXME: mark instructions for use in SSA */
4449                         if (*ip == CEE_LDSFLDA) {
4450                                 *sp++ = ins;
4451                         } else if (*ip == CEE_STSFLD) {
4452                                 MonoInst *store;
4453                                 CHECK_STACK (1);
4454                                 sp--;
4455                                 MONO_INST_NEW (cfg, store, mono_type_to_stind (field->type));
4456                                 store->cil_code = ip;
4457                                 store->inst_left = ins;
4458                                 store->inst_right = sp [0];
4459                                 store->flags |= ins_flag;
4460                                 ins_flag = 0;
4461
4462                                 if (store->opcode == CEE_STOBJ) {
4463                                         handle_stobj (cfg, bblock, ins, sp [0], ip, mono_class_from_mono_type (field->type), FALSE, FALSE);
4464                                 } else
4465                                         MONO_ADD_INS (bblock, store);
4466                         } else {
4467                                 gboolean is_const = FALSE;
4468                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
4469                                 if (!((cfg->opt & MONO_OPT_SHARED) || mono_compile_aot) && 
4470                                     vtable->initialized && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY)) {
4471                                         gpointer addr = (char*)vtable->data + field->offset;
4472                                         /* g_print ("RO-FIELD %s.%s:%s\n", klass->name_space, klass->name, field->name);*/
4473                                         is_const = TRUE;
4474                                         switch (field->type->type) {
4475                                         case MONO_TYPE_BOOLEAN:
4476                                         case MONO_TYPE_U1:
4477                                                 NEW_ICONST (cfg, *sp, *((guint8 *)addr));
4478                                                 sp++;
4479                                                 break;
4480                                         case MONO_TYPE_I1:
4481                                                 NEW_ICONST (cfg, *sp, *((gint8 *)addr));
4482                                                 sp++;
4483                                                 break;                                          
4484                                         case MONO_TYPE_CHAR:
4485                                         case MONO_TYPE_U2:
4486                                                 NEW_ICONST (cfg, *sp, *((guint16 *)addr));
4487                                                 sp++;
4488                                                 break;
4489                                         case MONO_TYPE_I2:
4490                                                 NEW_ICONST (cfg, *sp, *((gint16 *)addr));
4491                                                 sp++;
4492                                                 break;
4493                                                 break;
4494                                         case MONO_TYPE_I4:
4495                                                 NEW_ICONST (cfg, *sp, *((gint32 *)addr));
4496                                                 sp++;
4497                                                 break;                                          
4498                                         case MONO_TYPE_U4:
4499                                                 NEW_ICONST (cfg, *sp, *((guint32 *)addr));
4500                                                 sp++;
4501                                                 break;
4502                                         case MONO_TYPE_I:
4503                                         case MONO_TYPE_U:
4504                                         case MONO_TYPE_STRING:
4505                                         case MONO_TYPE_OBJECT:
4506                                         case MONO_TYPE_CLASS:
4507                                         case MONO_TYPE_SZARRAY:
4508                                         case MONO_TYPE_PTR:
4509                                         case MONO_TYPE_FNPTR:
4510                                         case MONO_TYPE_ARRAY:
4511                                                 NEW_PCONST (cfg, *sp, *((gpointer *)addr));
4512                                                 type_to_eval_stack_type (field->type, *sp);
4513                                                 sp++;
4514                                                 break;
4515                                         case MONO_TYPE_I8:
4516                                         case MONO_TYPE_U8:
4517                                                 MONO_INST_NEW (cfg, *sp, OP_I8CONST);
4518                                                 sp [0]->type = STACK_I8;
4519                                                 sp [0]->inst_l = *((gint64 *)addr);
4520                                                 sp++;
4521                                                 break;
4522                                         case MONO_TYPE_R4:
4523                                         case MONO_TYPE_R8:
4524                                         case MONO_TYPE_VALUETYPE:
4525                                         default:
4526                                                 is_const = FALSE;
4527                                                 break;
4528                                         }
4529                                 }
4530
4531                                 if (!is_const) {
4532                                         MonoInst *load;
4533                                         CHECK_STACK_OVF (1);
4534                                         MONO_INST_NEW (cfg, load, mono_type_to_ldind (field->type));
4535                                         type_to_eval_stack_type (field->type, load);
4536                                         load->cil_code = ip;
4537                                         load->inst_left = ins;
4538                                         *sp++ = load;
4539                                         load->flags |= ins_flag;
4540                                         ins_flag = 0;
4541                                         /* fixme: dont see the problem why this does not work */
4542                                         //cfg->disable_aot = TRUE;
4543                                 }
4544                         }
4545                         ip += 5;
4546                         break;
4547                 }
4548                 case CEE_STOBJ:
4549                         CHECK_STACK (2);
4550                         sp -= 2;
4551                         CHECK_OPSIZE (5);
4552                         token = read32 (ip + 1);
4553                         if (method->wrapper_type != MONO_WRAPPER_NONE)
4554                                 klass = mono_method_get_wrapper_data (method, token);
4555                         else
4556                                 klass = mono_class_get (image, token);
4557                         mono_class_init (klass);
4558                         if (klass->byval_arg.type == MONO_TYPE_VAR)
4559                                 klass = TYPE_PARAM_TO_CLASS (klass->byval_arg.data.generic_param->num);
4560                         else if (klass->byval_arg.type == MONO_TYPE_MVAR)
4561                                 klass = MTYPE_PARAM_TO_CLASS (klass->byval_arg.data.generic_param->num);
4562                         n = mono_type_to_stind (&klass->byval_arg);
4563                         if (n == CEE_STOBJ) {
4564                                 handle_stobj (cfg, bblock, sp [0], sp [1], ip, klass, FALSE, FALSE);
4565                         } else {
4566                                 /* FIXME: should check item at sp [1] is compatible with the type of the store. */
4567                                 MonoInst *store;
4568                                 MONO_INST_NEW (cfg, store, n);
4569                                 store->cil_code = ip;
4570                                 store->inst_left = sp [0];
4571                                 store->inst_right = sp [1];
4572                                 store->flags |= ins_flag;
4573                                 MONO_ADD_INS (bblock, store);
4574                         }
4575                         ins_flag = 0;
4576                         ip += 5;
4577                         inline_costs += 1;
4578                         break;
4579                 case CEE_BOX: {
4580                         MonoInst *iargs [2];
4581                         MonoInst *load, *vtoffset, *add, *val, *vstore;
4582                         int temp;
4583                         CHECK_STACK (1);
4584                         --sp;
4585                         val = *sp;
4586                         CHECK_OPSIZE (5);
4587                         token = read32 (ip + 1);
4588                         if (method->wrapper_type != MONO_WRAPPER_NONE)
4589                                 klass = mono_method_get_wrapper_data (method, token);
4590                         else
4591                                 klass = mono_class_get (image, token);
4592                         mono_class_init (klass);
4593                         if (klass->byval_arg.type == MONO_TYPE_VAR)
4594                                 klass = TYPE_PARAM_TO_CLASS (klass->byval_arg.data.generic_param->num);
4595                         else if (klass->byval_arg.type == MONO_TYPE_MVAR)
4596                                 klass = MTYPE_PARAM_TO_CLASS (klass->byval_arg.data.generic_param->num);
4597
4598                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
4599                                 *sp++ = val;
4600                                 ip += 5;
4601                                 break;
4602                         }
4603                         /* much like NEWOBJ */
4604                         if (cfg->opt & MONO_OPT_SHARED) {
4605                                 NEW_DOMAINCONST (cfg, iargs [0]);
4606                                 NEW_CLASSCONST (cfg, iargs [1], klass);
4607
4608                                 temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
4609                         } else {
4610                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
4611                                 NEW_VTABLECONST (cfg, iargs [0], vtable);
4612                                 if (klass->has_finalize || (cfg->prof_options & MONO_PROFILE_ALLOCATIONS))
4613                                         temp = mono_emit_jit_icall (cfg, bblock, mono_object_new_specific, iargs, ip);
4614                                 else
4615                                         temp = mono_emit_jit_icall (cfg, bblock, mono_object_new_fast, iargs, ip);
4616                         }
4617                         NEW_TEMPLOAD (cfg, load, temp);
4618                         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
4619                         MONO_INST_NEW (cfg, add, CEE_ADD);
4620                         add->inst_left = load;
4621                         add->inst_right = vtoffset;
4622                         add->cil_code = ip;
4623                         add->klass = klass;
4624                         MONO_INST_NEW (cfg, vstore, CEE_STIND_I);
4625                         vstore->opcode = mono_type_to_stind (&klass->byval_arg);
4626                         vstore->cil_code = ip;
4627                         vstore->inst_left = add;
4628                         vstore->inst_right = val;
4629
4630                         if (vstore->opcode == CEE_STOBJ) {
4631                                 handle_stobj (cfg, bblock, add, val, ip, klass, FALSE, FALSE);
4632                         } else
4633                                 MONO_ADD_INS (bblock, vstore);
4634
4635                         NEW_TEMPLOAD (cfg, load, temp);
4636                         *sp++ = load;
4637                         ip += 5;
4638                         inline_costs += 1;
4639                         break;
4640                 }
4641                 case CEE_NEWARR:
4642                         CHECK_STACK (1);
4643                         MONO_INST_NEW (cfg, ins, *ip);
4644                         ins->cil_code = ip;
4645                         --sp;
4646
4647                         CHECK_OPSIZE (5);
4648                         token = read32 (ip + 1);
4649
4650                         /* allocate the domainvar - becaus this is used in decompose_foreach */
4651                         if (cfg->opt & MONO_OPT_SHARED)
4652                                 mono_get_domainvar (cfg);
4653                         
4654                         if (method->wrapper_type != MONO_WRAPPER_NONE)
4655                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
4656                         else
4657                                 klass = mono_class_get (image, token);
4658
4659                         mono_class_init (klass);
4660                         if (klass->byval_arg.type == MONO_TYPE_VAR)
4661                                 klass = TYPE_PARAM_TO_CLASS (klass->byval_arg.data.generic_param->num);
4662                         else if (klass->byval_arg.type == MONO_TYPE_MVAR)
4663                                 klass = MTYPE_PARAM_TO_CLASS (klass->byval_arg.data.generic_param->num);
4664                         ins->inst_newa_class = klass;
4665                         ins->inst_newa_len = *sp;
4666                         ins->type = STACK_OBJ;
4667                         ip += 5;
4668                         *sp++ = ins;
4669                         /* 
4670                          * we store the object so calls to create the array are not interleaved
4671                          * with the arguments of other calls.
4672                          */
4673                         if (1) {
4674                                 MonoInst *store, *temp, *load;
4675                                 --sp;
4676                                 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
4677                                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
4678                                 store->cil_code = ins->cil_code;
4679                                 MONO_ADD_INS (bblock, store);
4680                                 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
4681                                 load->cil_code = ins->cil_code;
4682                                 *sp++ = load;
4683                         }
4684                         inline_costs += 1;
4685                         break;
4686                 case CEE_LDLEN:
4687                         CHECK_STACK (1);
4688                         MONO_INST_NEW (cfg, ins, *ip);
4689                         ins->cil_code = ip++;
4690                         --sp;
4691                         ins->inst_left = *sp;
4692                         ins->type = STACK_PTR;
4693                         *sp++ = ins;
4694                         break;
4695                 case CEE_LDELEMA:
4696                         CHECK_STACK (2);
4697                         sp -= 2;
4698                         CHECK_OPSIZE (5);
4699
4700                         if (method->wrapper_type != MONO_WRAPPER_NONE)
4701                                 klass = (MonoClass*)mono_method_get_wrapper_data (method, read32 (ip + 1));
4702                         else
4703                                 klass = mono_class_get (image, read32 (ip + 1));
4704                         mono_class_init (klass);
4705                         if (klass->byval_arg.type == MONO_TYPE_VAR)
4706                                 klass = TYPE_PARAM_TO_CLASS (klass->byval_arg.data.generic_param->num);
4707                         else if (klass->byval_arg.type == MONO_TYPE_MVAR)
4708                                 klass = MTYPE_PARAM_TO_CLASS (klass->byval_arg.data.generic_param->num);
4709                         NEW_LDELEMA (cfg, ins, sp, klass);
4710                         ins->cil_code = ip;
4711                         *sp++ = ins;
4712                         ip += 5;
4713                         break;
4714                 case CEE_LDELEM: {
4715                         MonoInst *load;
4716                         CHECK_STACK (2);
4717                         sp -= 2;
4718                         CHECK_OPSIZE (5);
4719                         token = read32 (ip + 1);
4720                         klass = mono_class_get (image, token);
4721                         mono_class_init (klass);
4722                         if (klass->byval_arg.type == MONO_TYPE_VAR)
4723                                 klass = TYPE_PARAM_TO_CLASS (klass->byval_arg.data.generic_param->num);
4724                         else if (klass->byval_arg.type == MONO_TYPE_MVAR)
4725                                 klass = MTYPE_PARAM_TO_CLASS (klass->byval_arg.data.generic_param->num);
4726                         NEW_LDELEMA (cfg, load, sp, klass);
4727                         load->cil_code = ip;
4728                         MONO_INST_NEW (cfg, ins, mono_type_to_ldind (&klass->byval_arg));
4729                         ins->cil_code = ip;
4730                         ins->inst_left = load;
4731                         *sp++ = ins;
4732                         type_to_eval_stack_type (&klass->byval_arg, ins);
4733                         ip += 5;
4734                         break;
4735                 }
4736                 case CEE_LDELEM_I1:
4737                 case CEE_LDELEM_U1:
4738                 case CEE_LDELEM_I2:
4739                 case CEE_LDELEM_U2:
4740                 case CEE_LDELEM_I4:
4741                 case CEE_LDELEM_U4:
4742                 case CEE_LDELEM_I8:
4743                 case CEE_LDELEM_I:
4744                 case CEE_LDELEM_R4:
4745                 case CEE_LDELEM_R8:
4746                 case CEE_LDELEM_REF: {
4747                         MonoInst *load;
4748                         /*
4749                          * translate to:
4750                          * ldind.x (ldelema (array, index))
4751                          * ldelema does the bounds check
4752                          */
4753                         CHECK_STACK (2);
4754                         sp -= 2;
4755                         klass = array_access_to_klass (*ip);
4756                         NEW_LDELEMA (cfg, load, sp, klass);
4757                         load->cil_code = ip;
4758                         MONO_INST_NEW (cfg, ins, ldelem_to_ldind [*ip - CEE_LDELEM_I1]);
4759                         ins->cil_code = ip;
4760                         ins->inst_left = load;
4761                         *sp++ = ins;
4762                         ins->type = ldind_type [ins->opcode - CEE_LDIND_I1];
4763                         ++ip;
4764                         break;
4765                 }
4766                 case CEE_STELEM_I:
4767                 case CEE_STELEM_I1:
4768                 case CEE_STELEM_I2:
4769                 case CEE_STELEM_I4:
4770                 case CEE_STELEM_I8:
4771                 case CEE_STELEM_R4:
4772                 case CEE_STELEM_R8: {
4773                         MonoInst *load;
4774                         /*
4775                          * translate to:
4776                          * stind.x (ldelema (array, index), val)
4777                          * ldelema does the bounds check
4778                          */
4779                         CHECK_STACK (3);
4780                         sp -= 3;
4781                         klass = array_access_to_klass (*ip);
4782                         NEW_LDELEMA (cfg, load, sp, klass);
4783                         load->cil_code = ip;
4784                         MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
4785                         ins->cil_code = ip;
4786                         ins->inst_left = load;
4787                         ins->inst_right = sp [2];
4788                         ++ip;
4789                         handle_loaded_temps (cfg, bblock, stack_start, sp);
4790                         MONO_ADD_INS (bblock, ins);
4791                         inline_costs += 1;
4792                         break;
4793                 }
4794                 case CEE_STELEM: {
4795                         MonoInst *load;
4796                         /*
4797                          * translate to:
4798                          * stind.x (ldelema (array, index), val)
4799                          * ldelema does the bounds check
4800                          */
4801                         CHECK_STACK (3);
4802                         sp -= 3;
4803                         CHECK_OPSIZE (5);
4804                         token = read32 (ip + 1);
4805                         klass = mono_class_get (image, token);
4806                         mono_class_init (klass);
4807                         if (klass->byval_arg.type == MONO_TYPE_VAR)
4808                                 klass = TYPE_PARAM_TO_CLASS (klass->byval_arg.data.generic_param->num);
4809                         else if (klass->byval_arg.type == MONO_TYPE_MVAR)
4810                                 klass = MTYPE_PARAM_TO_CLASS (klass->byval_arg.data.generic_param->num);
4811                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
4812                                 MonoInst *iargs [3];
4813                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4814
4815                                 iargs [2] = sp [2];
4816                                 iargs [1] = sp [1];
4817                                 iargs [0] = sp [0];
4818                         
4819                                 mono_emit_jit_icall (cfg, bblock, helper_stelem_ref, iargs, ip);
4820                         } else {
4821                                 NEW_LDELEMA (cfg, load, sp, klass);
4822                                 load->cil_code = ip;
4823                                 MONO_INST_NEW (cfg, ins, mono_type_to_stind (&klass->byval_arg));
4824                                 ins->cil_code = ip;
4825                                 ins->inst_left = load;
4826                                 ins->inst_right = sp [2];
4827                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4828                                 MONO_ADD_INS (bblock, ins);
4829                         }
4830                         ip += 5;
4831                         inline_costs += 1;
4832                         break;
4833                 }
4834                 case CEE_STELEM_REF: {
4835                         MonoInst *iargs [3];
4836
4837                         CHECK_STACK (3);
4838                         sp -= 3;
4839
4840                         handle_loaded_temps (cfg, bblock, stack_start, sp);
4841
4842                         iargs [2] = sp [2];
4843                         iargs [1] = sp [1];
4844                         iargs [0] = sp [0];
4845                         
4846                         mono_emit_jit_icall (cfg, bblock, helper_stelem_ref, iargs, ip);
4847
4848                         /*
4849                         MonoInst *group;
4850                         NEW_GROUP (cfg, group, sp [0], sp [1]);
4851                         MONO_INST_NEW (cfg, ins, CEE_STELEM_REF);
4852                         ins->cil_code = ip;
4853                         ins->inst_left = group;
4854                         ins->inst_right = sp [2];
4855                         MONO_ADD_INS (bblock, ins);
4856                         */
4857
4858                         ++ip;
4859                         inline_costs += 1;
4860                         break;
4861                 }
4862                 case CEE_CKFINITE: {
4863                         MonoInst *store, *temp;
4864                         CHECK_STACK (1);
4865
4866                         /* this instr. can throw exceptions as side effect,
4867                          * so we cant eliminate dead code which contains CKFINITE opdodes.
4868                          * Spilling to memory makes sure that we always perform
4869                          * this check */
4870
4871                         
4872                         MONO_INST_NEW (cfg, ins, CEE_CKFINITE);
4873                         ins->cil_code = ip;
4874                         ins->inst_left = sp [-1];
4875                         temp = mono_compile_create_var (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL);
4876
4877                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
4878                         store->cil_code = ip;
4879                         MONO_ADD_INS (bblock, store);
4880
4881                         NEW_TEMPLOAD (cfg, sp [-1], temp->inst_c0);
4882                        
4883                         ++ip;
4884                         break;
4885                 }
4886                 case CEE_REFANYVAL:
4887                         CHECK_STACK (1);
4888                         MONO_INST_NEW (cfg, ins, *ip);
4889                         --sp;
4890                         CHECK_OPSIZE (5);
4891                         klass = mono_class_get (image, read32 (ip + 1));
4892                         mono_class_init (klass);
4893                         if (klass->byval_arg.type == MONO_TYPE_VAR)
4894                                 klass = TYPE_PARAM_TO_CLASS (klass->byval_arg.data.generic_param->num);
4895                         else if (klass->byval_arg.type == MONO_TYPE_MVAR)
4896                                 klass = MTYPE_PARAM_TO_CLASS (klass->byval_arg.data.generic_param->num);
4897                         ins->type = STACK_MP;
4898                         ins->inst_left = *sp;
4899                         ins->klass = klass;
4900                         ins->inst_newa_class = klass;
4901                         ins->cil_code = ip;
4902                         ip += 5;
4903                         *sp++ = ins;
4904                         break;
4905                 case CEE_MKREFANY: {
4906                         MonoInst *loc, *klassconst;
4907
4908                         CHECK_STACK (1);
4909                         MONO_INST_NEW (cfg, ins, *ip);
4910                         --sp;
4911                         CHECK_OPSIZE (5);
4912                         klass = mono_class_get (image, read32 (ip + 1));
4913                         mono_class_init (klass);
4914                         if (klass->byval_arg.type == MONO_TYPE_VAR)
4915                                 klass = TYPE_PARAM_TO_CLASS (klass->byval_arg.data.generic_param->num);
4916                         else if (klass->byval_arg.type == MONO_TYPE_MVAR)
4917                                 klass = MTYPE_PARAM_TO_CLASS (klass->byval_arg.data.generic_param->num);
4918                         ins->cil_code = ip;
4919
4920                         loc = mono_compile_create_var (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL);
4921                         NEW_TEMPLOADA (cfg, ins->inst_right, loc->inst_c0);
4922
4923                         NEW_PCONST (cfg, klassconst, klass);
4924                         NEW_GROUP (cfg, ins->inst_left, *sp, klassconst);
4925                         
4926                         MONO_ADD_INS (bblock, ins);
4927
4928                         NEW_TEMPLOAD (cfg, *sp, loc->inst_c0);
4929                         ++sp;
4930                         ip += 5;
4931                         break;
4932                 }
4933                 case CEE_LDTOKEN: {
4934                         gpointer handle;
4935                         MonoClass *handle_class;
4936
4937                         CHECK_STACK_OVF (1);
4938
4939                         CHECK_OPSIZE (5);
4940                         n = read32 (ip + 1);
4941
4942                         handle = mono_ldtoken (image, n, &handle_class);
4943                         mono_class_init (handle_class);
4944
4945                         if (cfg->opt & MONO_OPT_SHARED) {
4946                                 int temp;
4947                                 MonoInst *res, *store, *addr, *vtvar, *iargs [2];
4948
4949                                 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL); 
4950
4951                                 NEW_IMAGECONST (cfg, iargs [0], image);
4952                                 NEW_ICONST (cfg, iargs [1], n);
4953                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldtoken_wrapper, iargs, ip);
4954                                 NEW_TEMPLOAD (cfg, res, temp);
4955                                 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
4956                                 NEW_INDSTORE (cfg, store, addr, res, &mono_defaults.int_class->byval_arg);
4957                                 MONO_ADD_INS (bblock, store);
4958                                 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
4959                         } else {
4960                                 if ((ip [5] == CEE_CALL) && (cmethod = mini_get_method (image, read32 (ip + 6), method)) &&
4961                                                 (cmethod->klass == mono_defaults.monotype_class->parent) &&
4962                                                 (strcmp (cmethod->name, "GetTypeFromHandle") == 0)) {
4963                                         MonoClass *tclass = mono_class_from_mono_type (handle);
4964                                         mono_class_init (tclass);
4965                                         if (mono_compile_aot)
4966                                                 NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, image, n);
4967                                         else
4968                                                 NEW_PCONST (cfg, ins, mono_type_get_object (cfg->domain, handle));
4969                                         ins->type = STACK_OBJ;
4970                                         ins->klass = cmethod->klass;
4971                                         ip += 5;
4972                                 } else {
4973                                         if (mono_compile_aot)
4974                                                 NEW_LDTOKENCONST (cfg, ins, image, n);
4975                                         else
4976                                                 NEW_PCONST (cfg, ins, handle);
4977                                         ins->type = STACK_VTYPE;
4978                                         ins->klass = handle_class;
4979                                 }
4980                         }
4981
4982                         *sp++ = ins;
4983                         ip += 5;
4984                         break;
4985                 }
4986                 case CEE_CONV_U2:
4987                 case CEE_CONV_U1:
4988                 case CEE_CONV_I:
4989                         CHECK_STACK (1);
4990                         ADD_UNOP (*ip);
4991                         ip++;
4992                         break;
4993                 case CEE_ADD_OVF:
4994                 case CEE_ADD_OVF_UN:
4995                 case CEE_MUL_OVF:
4996                 case CEE_MUL_OVF_UN:
4997                 case CEE_SUB_OVF:
4998                 case CEE_SUB_OVF_UN:
4999                         CHECK_STACK (2);
5000                         ADD_BINOP (*ip);
5001                         ip++;
5002                         break;
5003                 case CEE_ENDFINALLY:
5004                         /* FIXME: check stack state */
5005                         MONO_INST_NEW (cfg, ins, *ip);
5006                         MONO_ADD_INS (bblock, ins);
5007                         ins->cil_code = ip++;
5008                         start_new_bblock = 1;
5009                         break;
5010                 case CEE_LEAVE:
5011                 case CEE_LEAVE_S: {
5012                         GList *handlers;
5013                         if (*ip == CEE_LEAVE) {
5014                                 CHECK_OPSIZE (5);
5015                                 target = ip + 5 + (gint32)read32(ip + 1);
5016                         } else {
5017                                 CHECK_OPSIZE (2);
5018                                 target = ip + 2 + (signed char)(ip [1]);
5019                         }
5020
5021                         /* empty the stack */
5022                         while (sp != stack_start) {
5023                                 MONO_INST_NEW (cfg, ins, CEE_POP);
5024                                 ins->cil_code = ip;
5025                                 sp--;
5026                                 ins->inst_i0 = *sp;
5027                                 MONO_ADD_INS (bblock, ins);
5028                         }
5029
5030                         /* 
5031                          * If this leave statement is in a catch block, check for a
5032                          * pending exception, and rethrow it if necessary.
5033                          */
5034                         for (i = 0; i < header->num_clauses; ++i) {
5035                                 MonoExceptionClause *clause = &header->clauses [i];
5036                                 if (MONO_OFFSET_IN_HANDLER (clause, ip - header->code)) {
5037                                         int temp;
5038
5039                                         temp = mono_emit_jit_icall (cfg, bblock, mono_thread_get_pending_exception, NULL, ip);
5040                                         NEW_TEMPLOAD (cfg, *sp, temp);
5041
5042                                         MONO_INST_NEW (cfg, ins, OP_THROW_OR_NULL);
5043                                         ins->inst_left = *sp;
5044                                         ins->cil_code = ip;
5045                                         MONO_ADD_INS (bblock, ins);
5046                                 }
5047                         }
5048
5049                         /* fixme: call fault handler ? */
5050
5051                         if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
5052                                 GList *tmp;
5053                                 for (tmp = handlers; tmp; tmp = tmp->next) {
5054                                         tblock = tmp->data;
5055                                         link_bblock (cfg, bblock, tblock);
5056                                         MONO_INST_NEW (cfg, ins, OP_CALL_HANDLER);
5057                                         ins->cil_code = ip;
5058                                         ins->inst_target_bb = tblock;
5059                                         MONO_ADD_INS (bblock, ins);
5060                                 }
5061                                 g_list_free (handlers);
5062                         } 
5063
5064                         MONO_INST_NEW (cfg, ins, CEE_BR);
5065                         ins->cil_code = ip;
5066                         MONO_ADD_INS (bblock, ins);
5067                         GET_BBLOCK (cfg, bbhash, tblock, target);
5068                         link_bblock (cfg, bblock, tblock);
5069                         CHECK_BBLOCK (target, ip, tblock);
5070                         ins->inst_target_bb = tblock;
5071                         start_new_bblock = 1;
5072
5073                         if (*ip == CEE_LEAVE)
5074                                 ip += 5;
5075                         else
5076                                 ip += 2;
5077
5078                         break;
5079                 }
5080                 case CEE_STIND_I:
5081                         CHECK_STACK (2);
5082                         MONO_INST_NEW (cfg, ins, *ip);
5083                         sp -= 2;
5084                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5085                         MONO_ADD_INS (bblock, ins);
5086                         ins->cil_code = ip++;
5087                         ins->inst_i0 = sp [0];
5088                         ins->inst_i1 = sp [1];
5089                         inline_costs += 1;
5090                         break;
5091                 case CEE_CONV_U:
5092                         CHECK_STACK (1);
5093                         ADD_UNOP (*ip);
5094                         ip++;
5095                         break;
5096                 /* trampoline mono specific opcodes */
5097                 case MONO_CUSTOM_PREFIX: {
5098
5099                         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
5100
5101                         CHECK_OPSIZE (2);
5102                         switch (ip [1]) {
5103
5104                         case CEE_MONO_FUNC1: {
5105                                 int temp;
5106                                 gpointer func = NULL;
5107                                 CHECK_STACK (1);
5108                                 sp--;
5109
5110                                 CHECK_OPSIZE (3);
5111                                 switch (ip [2]) {
5112                                 case MONO_MARSHAL_CONV_STR_LPWSTR:
5113                                         func = mono_string_to_utf16;
5114                                         break;
5115                                 case MONO_MARSHAL_CONV_LPWSTR_STR:
5116                                         func = mono_string_from_utf16;
5117                                         break;
5118                                 case MONO_MARSHAL_CONV_LPSTR_STR:
5119                                         func = mono_string_new_wrapper;
5120                                         break;
5121                                 case MONO_MARSHAL_CONV_STR_LPTSTR:
5122                                 case MONO_MARSHAL_CONV_STR_LPSTR:
5123                                         func = mono_string_to_utf8;
5124                                         break;
5125                                 case MONO_MARSHAL_CONV_STR_BSTR:
5126                                         func = mono_string_to_bstr;
5127                                         break;
5128                                 case MONO_MARSHAL_CONV_STR_TBSTR:
5129                                 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
5130                                         func = mono_string_to_ansibstr;
5131                                         break;
5132                                 case MONO_MARSHAL_CONV_SB_LPSTR:
5133                                 case MONO_MARSHAL_CONV_SB_LPTSTR:
5134                                         func = mono_string_builder_to_utf8;
5135                                         break;
5136                                 case MONO_MARSHAL_CONV_SB_LPWSTR:
5137                                         func = mono_string_builder_to_utf16;
5138                                         break;
5139                                 case MONO_MARSHAL_CONV_ARRAY_SAVEARRAY:
5140                                         func = mono_array_to_savearray;
5141                                         break;
5142                                 case MONO_MARSHAL_CONV_ARRAY_LPARRAY:
5143                                         func = mono_array_to_lparray;
5144                                         break;
5145                                 case MONO_MARSHAL_CONV_DEL_FTN:
5146                                         func = mono_delegate_to_ftnptr;
5147                                         break;
5148                                 case MONO_MARSHAL_CONV_STRARRAY_STRLPARRAY:
5149                                         func = mono_marshal_string_array;
5150                                         break;
5151                                 default:
5152                                         g_warning ("unknown conversion %d\n", ip [2]);
5153                                         g_assert_not_reached ();
5154                                 }
5155
5156                                 temp = mono_emit_jit_icall (cfg, bblock, func, sp, ip);
5157                                 NEW_TEMPLOAD (cfg, *sp, temp);
5158                                 sp++;
5159
5160                                 ip += 3;
5161                                 inline_costs += 10 * num_calls++;
5162                                 break;
5163                         }
5164                         case CEE_MONO_PROC2: {
5165                                 gpointer func = NULL;
5166                                 CHECK_STACK (2);
5167                                 sp -= 2;
5168
5169                                 CHECK_OPSIZE (3);
5170                                 switch (ip [2]) {
5171                                 case MONO_MARSHAL_CONV_LPSTR_SB:
5172                                 case MONO_MARSHAL_CONV_LPTSTR_SB:
5173                                         func = mono_string_utf8_to_builder;
5174                                         break;
5175                                 case MONO_MARSHAL_CONV_LPWSTR_SB:
5176                                         func = mono_string_utf16_to_builder;
5177                                         break;
5178                                 case MONO_MARSHAL_FREE_ARRAY:
5179                                         func = mono_marshal_free_array;
5180                                         break;
5181                                 default:
5182                                         g_assert_not_reached ();
5183                                 }
5184
5185                                 mono_emit_jit_icall (cfg, bblock, func, sp, ip);
5186                                 ip += 3;
5187                                 inline_costs += 10 * num_calls++;
5188                                 break;
5189                         }
5190                         case CEE_MONO_PROC3: {
5191                                 gpointer func = NULL;
5192                                 CHECK_STACK (3);
5193                                 sp -= 3;
5194
5195                                 CHECK_OPSIZE (3);
5196                                 switch (ip [2]) {
5197                                 case MONO_MARSHAL_CONV_STR_BYVALSTR:
5198                                         func = mono_string_to_byvalstr;
5199                                         break;
5200                                 case MONO_MARSHAL_CONV_STR_BYVALWSTR:
5201                                         func = mono_string_to_byvalwstr;
5202                                         break;
5203                                 default:
5204                                         g_assert_not_reached ();
5205                                 }
5206
5207                                 mono_emit_jit_icall (cfg, bblock, func, sp, ip);
5208                                 ip += 3;
5209                                 inline_costs += 10 * num_calls++;
5210                                 break;
5211                         }
5212                         case CEE_MONO_FREE:
5213                                 CHECK_STACK (1);
5214                                 sp -= 1;
5215                                 mono_emit_jit_icall (cfg, bblock, g_free, sp, ip);
5216                                 ip += 2;
5217                                 inline_costs += 10 * num_calls++;
5218                                 break;
5219                         case CEE_MONO_LDPTR:
5220                                 CHECK_STACK_OVF (1);
5221                                 CHECK_OPSIZE (6);
5222                                 token = read32 (ip + 2);
5223                                 NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
5224                                 ins->cil_code = ip;
5225                                 *sp++ = ins;
5226                                 ip += 6;
5227                                 inline_costs += 10 * num_calls++;
5228                                 break;
5229                         case CEE_MONO_VTADDR:
5230                                 CHECK_STACK (1);
5231                                 --sp;
5232                                 MONO_INST_NEW (cfg, ins, OP_VTADDR);
5233                                 ins->cil_code = ip;
5234                                 ins->type = STACK_MP;
5235                                 ins->inst_left = *sp;
5236                                 *sp++ = ins;
5237                                 ip += 2;
5238                                 break;
5239                         case CEE_MONO_NEWOBJ: {
5240                                 MonoInst *iargs [2];
5241                                 int temp;
5242                                 CHECK_STACK_OVF (1);
5243                                 CHECK_OPSIZE (6);
5244                                 token = read32 (ip + 2);
5245                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
5246                                 mono_class_init (klass);
5247                                 NEW_DOMAINCONST (cfg, iargs [0]);
5248                                 NEW_CLASSCONST (cfg, iargs [1], klass);
5249                                 temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
5250                                 NEW_TEMPLOAD (cfg, *sp, temp);
5251                                 sp++;
5252                                 ip += 6;
5253                                 inline_costs += 10 * num_calls++;
5254                                 break;
5255                         }
5256                         case CEE_MONO_OBJADDR:
5257                                 CHECK_STACK (1);
5258                                 --sp;
5259                                 MONO_INST_NEW (cfg, ins, OP_OBJADDR);
5260                                 ins->cil_code = ip;
5261                                 ins->type = STACK_MP;
5262                                 ins->inst_left = *sp;
5263                                 *sp++ = ins;
5264                                 ip += 2;
5265                                 break;
5266                         case CEE_MONO_LDNATIVEOBJ:
5267                                 CHECK_STACK (1);
5268                                 CHECK_OPSIZE (6);
5269                                 token = read32 (ip + 2);
5270                                 klass = mono_method_get_wrapper_data (method, token);
5271                                 g_assert (klass->valuetype);
5272                                 mono_class_init (klass);
5273                                 NEW_INDLOAD (cfg, ins, sp [-1], &klass->byval_arg);
5274                                 sp [-1] = ins;
5275                                 ip += 6;
5276                                 break;
5277                         case CEE_MONO_RETOBJ:
5278                                 g_assert (cfg->ret);
5279                                 g_assert (method->signature->pinvoke); 
5280                                 CHECK_STACK (1);
5281                                 --sp;
5282                                 
5283                                 CHECK_OPSIZE (6);
5284                                 token = read32 (ip + 2);    
5285                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
5286
5287                                 NEW_RETLOADA (cfg, ins);
5288                                 handle_stobj (cfg, bblock, ins, *sp, ip, klass, FALSE, TRUE);
5289                                 
5290                                 if (sp != stack_start)
5291                                         goto unverified;
5292                                 
5293                                 MONO_INST_NEW (cfg, ins, CEE_BR);
5294                                 ins->cil_code = ip;
5295                                 ins->inst_target_bb = end_bblock;
5296                                 MONO_ADD_INS (bblock, ins);
5297                                 link_bblock (cfg, bblock, end_bblock);
5298                                 start_new_bblock = 1;
5299                                 ip += 6;
5300                                 break;
5301                         case CEE_MONO_CISINST:
5302                         case CEE_MONO_CCASTCLASS: {
5303                                 int token;
5304                                 CHECK_STACK (1);
5305                                 --sp;
5306                                 CHECK_OPSIZE (6);
5307                                 token = read32 (ip + 2);
5308                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
5309                                 MONO_INST_NEW (cfg, ins, (ip [1] == CEE_MONO_CISINST) ? OP_CISINST : OP_CCASTCLASS);
5310                                 ins->type = STACK_I4;
5311                                 ins->inst_left = *sp;
5312                                 ins->inst_newa_class = klass;
5313                                 ins->cil_code = ip;
5314                                 *sp++ = ins;
5315                                 ip += 6;
5316                                 break;
5317                         }
5318                         default:
5319                                 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
5320                                 break;
5321                         }
5322                         break;
5323                 }
5324                 case CEE_PREFIX1: {
5325                         CHECK_OPSIZE (2);
5326                         switch (ip [1]) {
5327                         case CEE_ARGLIST: {
5328                                 /* somewhat similar to LDTOKEN */
5329                                 MonoInst *addr, *vtvar;
5330                                 CHECK_STACK_OVF (1);
5331                                 vtvar = mono_compile_create_var (cfg, &mono_defaults.argumenthandle_class->byval_arg, OP_LOCAL); 
5332
5333                                 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
5334                                 addr->cil_code = ip;
5335                                 MONO_INST_NEW (cfg, ins, OP_ARGLIST);
5336                                 ins->cil_code = ip;
5337                                 ins->inst_left = addr;
5338                                 MONO_ADD_INS (bblock, ins);
5339                                 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
5340                                 ins->cil_code = ip;
5341                                 *sp++ = ins;
5342                                 ip += 2;
5343                                 break;
5344                         }
5345                         case CEE_CEQ:
5346                         case CEE_CGT:
5347                         case CEE_CGT_UN:
5348                         case CEE_CLT:
5349                         case CEE_CLT_UN: {
5350                                 MonoInst *cmp;
5351                                 CHECK_STACK (2);
5352                                 /*
5353                                  * The following transforms:
5354                                  *    CEE_CEQ    into OP_CEQ
5355                                  *    CEE_CGT    into OP_CGT
5356                                  *    CEE_CGT_UN into OP_CGT_UN
5357                                  *    CEE_CLT    into OP_CLT
5358                                  *    CEE_CLT_UN into OP_CLT_UN
5359                                  */
5360                                 MONO_INST_NEW (cfg, cmp, 256 + ip [1]);
5361                                 
5362                                 MONO_INST_NEW (cfg, ins, cmp->opcode);
5363                                 sp -= 2;
5364                                 cmp->inst_i0 = sp [0];
5365                                 cmp->inst_i1 = sp [1];
5366                                 cmp->cil_code = ip;
5367                                 type_from_op (cmp);
5368                                 CHECK_TYPE (cmp);
5369                                 cmp->opcode = OP_COMPARE;
5370                                 ins->cil_code = ip;
5371                                 ins->type = STACK_I4;
5372                                 ins->inst_i0 = cmp;
5373                                 *sp++ = ins;
5374                                 ip += 2;
5375                                 break;
5376                         }
5377                         case CEE_LDFTN: {
5378                                 MonoInst *argconst;
5379                                 int temp;
5380
5381                                 CHECK_STACK_OVF (1);
5382                                 CHECK_OPSIZE (6);
5383                                 n = read32 (ip + 2);
5384                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
5385                                         cmethod = mono_method_get_wrapper_data (method, n);
5386                                 else {
5387                                         cmethod = mini_get_method (image, n, method);
5388                                 }
5389
5390                                 mono_class_init (cmethod->klass);
5391                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
5392
5393                                 NEW_METHODCONST (cfg, argconst, cmethod);
5394                                 if (method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED)
5395                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn, &argconst, ip);
5396                                 else
5397                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn_nosync, &argconst, ip);
5398                                 NEW_TEMPLOAD (cfg, *sp, temp);
5399                                 sp ++;
5400                                 
5401                                 ip += 6;
5402                                 inline_costs += 10 * num_calls++;
5403                                 break;
5404                         }
5405                         case CEE_LDVIRTFTN: {
5406                                 MonoInst *args [2];
5407                                 int temp;
5408
5409                                 CHECK_STACK (1);
5410                                 CHECK_OPSIZE (6);
5411                                 n = read32 (ip + 2);
5412                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
5413                                         cmethod = mono_method_get_wrapper_data (method, n);
5414                                 else
5415                                         cmethod = mini_get_method (image, n, method);
5416
5417                                 mono_class_init (cmethod->klass);
5418                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
5419
5420                                 --sp;
5421                                 args [0] = *sp;
5422                                 NEW_METHODCONST (cfg, args [1], cmethod);
5423                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldvirtfn, args, ip);
5424                                 NEW_TEMPLOAD (cfg, *sp, temp);
5425                                 sp ++;
5426
5427                                 ip += 6;
5428                                 inline_costs += 10 * num_calls++;
5429                                 break;
5430                         }
5431                         case CEE_LDARG:
5432                                 CHECK_STACK_OVF (1);
5433                                 CHECK_OPSIZE (4);
5434                                 n = read16 (ip + 2);
5435                                 CHECK_ARG (n);
5436                                 NEW_ARGLOAD (cfg, ins, n);
5437                                 ins->cil_code = ip;
5438                                 *sp++ = ins;
5439                                 ip += 4;
5440                                 break;
5441                         case CEE_LDARGA:
5442                                 CHECK_STACK_OVF (1);
5443                                 CHECK_OPSIZE (4);
5444                                 n = read16 (ip + 2);
5445                                 CHECK_ARG (n);
5446                                 NEW_ARGLOADA (cfg, ins, n);
5447                                 ins->cil_code = ip;
5448                                 *sp++ = ins;
5449                                 ip += 4;
5450                                 break;
5451                         case CEE_STARG:
5452                                 CHECK_STACK (1);
5453                                 --sp;
5454                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
5455                                 CHECK_OPSIZE (4);
5456                                 n = read16 (ip + 2);
5457                                 CHECK_ARG (n);
5458                                 NEW_ARGSTORE (cfg, ins, n, *sp);
5459                                 ins->cil_code = ip;
5460                                 if (ins->opcode == CEE_STOBJ) {
5461                                         NEW_ARGLOADA (cfg, ins, n);
5462                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
5463                                 } else
5464                                         MONO_ADD_INS (bblock, ins);
5465                                 ip += 4;
5466                                 break;
5467                         case CEE_LDLOC:
5468                                 CHECK_STACK_OVF (1);
5469                                 CHECK_OPSIZE (4);
5470                                 n = read16 (ip + 2);
5471                                 CHECK_LOCAL (n);
5472                                 NEW_LOCLOAD (cfg, ins, n);
5473                                 ins->cil_code = ip;
5474                                 *sp++ = ins;
5475                                 ip += 4;
5476                                 break;
5477                         case CEE_LDLOCA:
5478                                 CHECK_STACK_OVF (1);
5479                                 CHECK_OPSIZE (4);
5480                                 n = read16 (ip + 2);
5481                                 CHECK_LOCAL (n);
5482                                 NEW_LOCLOADA (cfg, ins, n);
5483                                 ins->cil_code = ip;
5484                                 *sp++ = ins;
5485                                 ip += 4;
5486                                 break;
5487                         case CEE_STLOC:
5488                                 CHECK_STACK (1);
5489                                 --sp;
5490                                 CHECK_OPSIZE (4);
5491                                 n = read16 (ip + 2);
5492                                 CHECK_LOCAL (n);
5493                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
5494                                 NEW_LOCSTORE (cfg, ins, n, *sp);
5495                                 ins->cil_code = ip;
5496                                 if (ins->opcode == CEE_STOBJ) {
5497                                         NEW_LOCLOADA (cfg, ins, n);
5498                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
5499                                 } else
5500                                         MONO_ADD_INS (bblock, ins);
5501                                 ip += 4;
5502                                 inline_costs += 1;
5503                                 break;
5504                         case CEE_LOCALLOC:
5505                                 CHECK_STACK (1);
5506                                 --sp;
5507                                 if (sp != stack_start) 
5508                                         goto unverified;
5509                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
5510                                 ins->inst_left = *sp;
5511                                 ins->cil_code = ip;
5512
5513                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
5514                                 if (header->init_locals)
5515                                         ins->flags |= MONO_INST_INIT;
5516
5517                                 *sp++ = ins;
5518                                 ip += 2;
5519                                 /* FIXME: set init flag if locals init is set in this method */
5520                                 break;
5521                         case CEE_ENDFILTER: {
5522                                 MonoExceptionClause *clause, *nearest;
5523                                 int cc, nearest_num;
5524
5525                                 CHECK_STACK (1);
5526                                 --sp;
5527                                 if ((sp != stack_start) || (sp [0]->type != STACK_I4)) 
5528                                         goto unverified;
5529                                 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
5530                                 ins->inst_left = *sp;
5531                                 ins->cil_code = ip;
5532                                 MONO_ADD_INS (bblock, ins);
5533                                 start_new_bblock = 1;
5534                                 ip += 2;
5535
5536                                 nearest = NULL;
5537                                 nearest_num = 0;
5538                                 for (cc = 0; cc < header->num_clauses; ++cc) {
5539                                         clause = &header->clauses [cc];
5540                                         if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
5541                                             (!nearest || (clause->token_or_filter > nearest->token_or_filter))) {
5542                                                 nearest = clause;
5543                                                 nearest_num = cc;
5544                                         }
5545                                 }
5546                                 g_assert (nearest);
5547                                 filter_lengths [nearest_num] = (ip - header->code) -  nearest->token_or_filter;
5548
5549                                 break;
5550                         }
5551                         case CEE_UNALIGNED_:
5552                                 ins_flag |= MONO_INST_UNALIGNED;
5553                                 /* FIXME: record alignment? we can assume 1 for now */
5554                                 CHECK_OPSIZE (3);
5555                                 ip += 3;
5556                                 break;
5557                         case CEE_VOLATILE_:
5558                                 ins_flag |= MONO_INST_VOLATILE;
5559                                 ip += 2;
5560                                 break;
5561                         case CEE_TAIL_:
5562                                 ins_flag |= MONO_INST_TAILCALL;
5563                                 /* Can't inline tail calls at this time */
5564                                 inline_costs += 100000;
5565                                 ip += 2;
5566                                 break;
5567                         case CEE_INITOBJ:
5568                                 CHECK_STACK (1);
5569                                 --sp;
5570                                 CHECK_OPSIZE (6);
5571                                 token = read32 (ip + 2);
5572                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
5573                                         klass = mono_method_get_wrapper_data (method, token);
5574                                 else
5575                                         klass = mono_class_get (image, token);
5576                                 if (klass->byval_arg.type == MONO_TYPE_VAR)
5577                                         klass = TYPE_PARAM_TO_CLASS (klass->byval_arg.data.generic_param->num);
5578                                 else if (klass->byval_arg.type == MONO_TYPE_MVAR)
5579                                         klass = MTYPE_PARAM_TO_CLASS (klass->byval_arg.data.generic_param->num);
5580
5581                                 if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
5582                                         MonoInst *store, *load;
5583                                         NEW_PCONST (cfg, load, NULL);
5584                                         load->cil_code = ip;
5585                                         load->type = STACK_OBJ;
5586                                         MONO_INST_NEW (cfg, store, CEE_STIND_REF);
5587                                         store->cil_code = ip;
5588                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5589                                         MONO_ADD_INS (bblock, store);
5590                                         store->inst_i0 = sp [0];
5591                                         store->inst_i1 = load;
5592                                 } else {
5593                                         handle_initobj (cfg, bblock, *sp, NULL, klass, stack_start, sp);
5594                                 }
5595                                 ip += 6;
5596                                 inline_costs += 1;
5597                                 break;
5598                         case CEE_CONSTRAINED_:
5599                                 /* FIXME: implement */
5600                                 CHECK_OPSIZE (6);
5601                                 token = read32 (ip + 2);
5602                                 ip += 6;
5603                                 break;
5604                         case CEE_CPBLK:
5605                         case CEE_INITBLK: {
5606                                 MonoInst *iargs [3];
5607                                 CHECK_STACK (3);
5608                                 sp -= 3;
5609                                 if ((cfg->opt & MONO_OPT_INTRINS) && (ip [1] == CEE_CPBLK) && (sp [2]->opcode == OP_ICONST) && ((n = sp [2]->inst_c0) <= sizeof (gpointer) * 5)) {
5610                                         MonoInst *copy;
5611                                         MONO_INST_NEW (cfg, copy, OP_MEMCPY);
5612                                         copy->inst_left = sp [0];
5613                                         copy->inst_right = sp [1];
5614                                         copy->cil_code = ip;
5615                                         copy->unused = n;
5616                                         MONO_ADD_INS (bblock, copy);
5617                                         ip += 2;
5618                                         break;
5619                                 }
5620                                 iargs [0] = sp [0];
5621                                 iargs [1] = sp [1];
5622                                 iargs [2] = sp [2];
5623                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
5624                                 if (ip [1] == CEE_CPBLK) {
5625                                         mono_emit_jit_icall (cfg, bblock, helper_memcpy, iargs, ip);
5626                                 } else {
5627                                         mono_emit_jit_icall (cfg, bblock, helper_memset, iargs, ip);
5628                                 }
5629                                 ip += 2;
5630                                 inline_costs += 1;
5631                                 break;
5632                         }
5633                         case CEE_NO_:
5634                                 CHECK_OPSIZE (3);
5635                                 if (ip [2] & 0x1)
5636                                         ins_flag |= MONO_INST_NOTYPECHECK;
5637                                 if (ip [2] & 0x2)
5638                                         ins_flag |= MONO_INST_NORANGECHECK;
5639                                 /* we ignore the no-nullcheck for now since we
5640                                  * really do it explicitly only when doing callvirt->call
5641                                  */
5642                                 ip += 3;
5643                                 break;
5644                         case CEE_RETHROW: {
5645                                 MonoInst *load;
5646                                 /* FIXME: check we are in a catch handler */
5647                                 NEW_TEMPLOAD (cfg, load, cfg->exvar->inst_c0);
5648                                 load->cil_code = ip;
5649                                 MONO_INST_NEW (cfg, ins, CEE_THROW);
5650                                 ins->inst_left = load;
5651                                 ins->cil_code = ip;
5652                                 MONO_ADD_INS (bblock, ins);
5653                                 sp = stack_start;
5654                                 start_new_bblock = 1;
5655                                 ip += 2;
5656                                 break;
5657                         }
5658                         case CEE_SIZEOF:
5659                                 CHECK_STACK_OVF (1);
5660                                 CHECK_OPSIZE (6);
5661                                 token = read32 (ip + 2);
5662                                 /* FIXXME: handle generics. */
5663                                 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC) {
5664                                         MonoType *type = mono_type_create_from_typespec (image, token);
5665                                         token = mono_type_size (type, &align);
5666                                 } else {
5667                                         MonoClass *szclass = mono_class_get (image, token);
5668                                         mono_class_init (szclass);
5669                                         token = mono_class_value_size (szclass, &align);
5670                                 }
5671                                 NEW_ICONST (cfg, ins, token);
5672                                 ins->cil_code = ip;
5673                                 *sp++= ins;
5674                                 ip += 6;
5675                                 break;
5676                         case CEE_REFANYTYPE:
5677                                 CHECK_STACK (1);
5678                                 MONO_INST_NEW (cfg, ins, ip [1]);
5679                                 --sp;
5680                                 ins->type = STACK_MP;
5681                                 ins->inst_left = *sp;
5682                                 ins->type = STACK_VTYPE;
5683                                 ins->klass = mono_defaults.typehandle_class;
5684                                 ins->cil_code = ip;
5685                                 ip += 2;
5686                                 *sp++ = ins;
5687                                 break;
5688                         case CEE_READONLY_:
5689                                 ip += 2;
5690                                 break;
5691                         default:
5692                                 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
5693                         }
5694                         break;
5695                 }
5696                 default:
5697                         g_error ("opcode 0x%02x not handled", *ip);
5698                 }
5699         }
5700         if (start_new_bblock != 1)
5701                 goto unverified;
5702
5703         bblock->cil_length = ip - bblock->cil_code;
5704         bblock->next_bb = end_bblock;
5705         link_bblock (cfg, bblock, end_bblock);
5706
5707         if (cfg->method == method && cfg->domainvar) {
5708                 MonoCallInst *call;
5709                 MonoInst *store;
5710
5711                 MONO_INST_NEW_CALL (cfg, call, CEE_CALL);
5712                 call->signature = helper_sig_domain_get;
5713                 call->inst.type = STACK_PTR;
5714                 call->fptr = mono_domain_get;
5715                 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, (MonoInst*)call);
5716                 
5717                 MONO_ADD_INS (init_localsbb, store);
5718         }
5719
5720         if (header->init_locals) {
5721                 MonoInst *store;
5722                 for (i = 0; i < header->num_locals; ++i) {
5723                         int t = header->locals [i]->type;
5724                         if (t == MONO_TYPE_VALUETYPE && header->locals [i]->data.klass->enumtype)
5725                                 t = header->locals [i]->data.klass->enum_basetype->type;
5726                         /* FIXME: use initobj for valuetypes, handle pointers, long, float. */
5727                         if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
5728                                 NEW_ICONST (cfg, ins, 0);
5729                                 NEW_LOCSTORE (cfg, store, i, ins);
5730                                 MONO_ADD_INS (init_localsbb, store);
5731                         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
5732                                 MONO_INST_NEW (cfg, ins, OP_I8CONST);
5733                                 ins->type = STACK_I8;
5734                                 ins->inst_l = 0;
5735                                 NEW_LOCSTORE (cfg, store, i, ins);
5736                                 MONO_ADD_INS (init_localsbb, store);
5737                         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
5738                                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
5739                                 ins->type = STACK_R8;
5740                                 ins->inst_p0 = (void*)&r8_0;
5741                                 NEW_LOCSTORE (cfg, store, i, ins);
5742                                 MONO_ADD_INS (init_localsbb, store);
5743                         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF)) {
5744                                 NEW_LOCLOADA (cfg, ins, i);
5745                                 handle_initobj (cfg, init_localsbb, ins, NULL, mono_class_from_mono_type (header->locals [i]), NULL, NULL);
5746                                 break;
5747                         } else {
5748                                 NEW_PCONST (cfg, ins, NULL);
5749                                 NEW_LOCSTORE (cfg, store, i, ins);
5750                                 MONO_ADD_INS (init_localsbb, store);
5751                         }
5752                 }
5753         }
5754
5755         
5756         /* resolve backward branches in the middle of an existing basic block */
5757         for (tmp = bb_recheck; tmp; tmp = tmp->next) {
5758                 bblock = tmp->data;
5759                 /*g_print ("need recheck in %s at IL_%04x\n", method->name, bblock->cil_code - header->code);*/
5760                 tblock = find_previous (bbhash, start_bblock, bblock->cil_code);
5761                 if (tblock != start_bblock) {
5762                         int l;
5763                         split_bblock (cfg, tblock, bblock);
5764                         l = bblock->cil_code - header->code;
5765                         bblock->cil_length = tblock->cil_length - l;
5766                         tblock->cil_length = l;
5767                 } else {
5768                         g_print ("recheck failed.\n");
5769                 }
5770         }
5771
5772         /*
5773          * we compute regions here, because the length of filter clauses is not known in advance.
5774          * It is computed in the CEE_ENDFILTER case in the above switch statement
5775          */
5776         if (cfg->method == method) {
5777                 MonoBasicBlock *bb;
5778                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5779                         bb->region = mono_find_block_region (cfg, bb->real_offset, filter_lengths);
5780                         if (cfg->spvars)
5781                                 mono_create_spvar_for_region (cfg, bb->region);
5782                         if (cfg->verbose_level > 2)
5783                                 g_print ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
5784                 }
5785         } else {
5786                 g_hash_table_destroy (bbhash);
5787         }
5788
5789         dont_inline = g_list_remove (dont_inline, method);
5790         return inline_costs;
5791
5792  inline_failure:
5793         if (cfg->method != method) 
5794                 g_hash_table_destroy (bbhash);
5795         dont_inline = g_list_remove (dont_inline, method);
5796         return -1;
5797
5798  unverified:
5799         if (cfg->method != method) 
5800                 g_hash_table_destroy (bbhash);
5801         g_error ("Invalid IL code at IL%04x in %s: %s\n", ip - header->code, 
5802                  mono_method_full_name (method, TRUE), mono_disasm_code_one (NULL, method, ip, NULL));
5803         dont_inline = g_list_remove (dont_inline, method);
5804         return -1;
5805 }
5806
5807 void
5808 mono_print_tree (MonoInst *tree) {
5809         int arity;
5810
5811         if (!tree)
5812                 return;
5813
5814         arity = mono_burg_arity [tree->opcode];
5815
5816         printf (" %s%s", arity?"(":"",  mono_inst_name (tree->opcode));
5817
5818         switch (tree->opcode) {
5819         case OP_ICONST:
5820                 printf ("[%d]", tree->inst_c0);
5821                 break;
5822         case OP_I8CONST:
5823                 printf ("[%lld]", tree->inst_l);
5824                 break;
5825         case OP_R8CONST:
5826                 printf ("[%f]", *(double*)tree->inst_p0);
5827                 break;
5828         case OP_R4CONST:
5829                 printf ("[%f]", *(float*)tree->inst_p0);
5830                 break;
5831         case OP_ARG:
5832         case OP_LOCAL:
5833                 printf ("[%d]", tree->inst_c0);
5834                 break;
5835         case OP_REGOFFSET:
5836                 if (tree->inst_offset < 0)
5837                         printf ("[-0x%x(%s)]", -tree->inst_offset, mono_arch_regname (tree->inst_basereg));
5838                 else
5839                         printf ("[0x%x(%s)]", tree->inst_offset, mono_arch_regname (tree->inst_basereg));
5840                 break;
5841         case OP_REGVAR:
5842                 printf ("[%s]", mono_arch_regname (tree->dreg));
5843                 break;
5844         case CEE_NEWARR:
5845                 printf ("[%s]",  tree->inst_newa_class->name);
5846                 mono_print_tree (tree->inst_newa_len);
5847                 break;
5848         case CEE_CALL:
5849         case CEE_CALLVIRT:
5850         case OP_FCALL:
5851         case OP_FCALLVIRT:
5852         case OP_LCALL:
5853         case OP_LCALLVIRT:
5854         case OP_VCALL:
5855         case OP_VCALLVIRT:
5856         case OP_VOIDCALL:
5857         case OP_VOIDCALLVIRT: {
5858                 MonoCallInst *call = (MonoCallInst*)tree;
5859                 if (call->method)
5860                         printf ("[%s]", call->method->name);
5861                 break;
5862         }
5863         case OP_PHI: {
5864                 int i;
5865                 printf ("[%d (", tree->inst_c0);
5866                 for (i = 0; i < tree->inst_phi_args [0]; i++) {
5867                         if (i)
5868                                 printf (", ");
5869                         printf ("%d", tree->inst_phi_args [i + 1]);
5870                 }
5871                 printf (")]");
5872                 break;
5873         }
5874         case OP_RENAME:
5875         case OP_RETARG:
5876         case CEE_NOP:
5877         case CEE_JMP:
5878         case CEE_BREAK:
5879                 break;
5880         case OP_LOAD_MEMBASE:
5881         case OP_LOADI4_MEMBASE:
5882         case OP_LOADU4_MEMBASE:
5883         case OP_LOADU1_MEMBASE:
5884         case OP_LOADI1_MEMBASE:
5885         case OP_LOADU2_MEMBASE:
5886         case OP_LOADI2_MEMBASE:
5887                 printf ("[%s] <- [%s + 0x%x]", mono_arch_regname (tree->dreg), mono_arch_regname (tree->inst_basereg), tree->inst_offset);
5888                 break;
5889         case CEE_BR:
5890                 printf ("[B%d]", tree->inst_target_bb->block_num);
5891                 break;
5892         case CEE_SWITCH:
5893         case CEE_ISINST:
5894         case CEE_CASTCLASS:
5895         case OP_OUTARG:
5896         case OP_CALL_REG:
5897         case OP_FCALL_REG:
5898         case OP_LCALL_REG:
5899         case OP_VCALL_REG:
5900         case OP_VOIDCALL_REG:
5901                 mono_print_tree (tree->inst_left);
5902                 break;
5903         case CEE_BNE_UN:
5904         case CEE_BEQ:
5905         case CEE_BLT:
5906         case CEE_BLT_UN:
5907         case CEE_BGT:
5908         case CEE_BGT_UN:
5909         case CEE_BGE:
5910         case CEE_BGE_UN:
5911         case CEE_BLE:
5912         case CEE_BLE_UN:
5913                 printf ("[B%dB%d]", tree->inst_true_bb->block_num, tree->inst_false_bb->block_num);
5914                 mono_print_tree (tree->inst_left);
5915                 break;
5916         default:
5917                 if (arity) {
5918                         mono_print_tree (tree->inst_left);
5919                         if (arity > 1)
5920                                 mono_print_tree (tree->inst_right);
5921                 }
5922                 break;
5923         }
5924
5925         if (arity)
5926                 printf (")");
5927 }
5928
5929 void
5930 mono_print_tree_nl (MonoInst *tree)
5931 {
5932         mono_print_tree (tree);
5933         printf ("\n");
5934 }
5935
5936 static void
5937 create_helper_signature (void)
5938 {
5939         /* FIXME: set call conv */
5940         /* MonoArray * mono_array_new (MonoDomain *domain, MonoClass *klass, gint32 len) */
5941         helper_sig_newarr = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
5942         helper_sig_newarr->params [0] = helper_sig_newarr->params [1] = &mono_defaults.int_class->byval_arg;
5943         helper_sig_newarr->ret = &mono_defaults.object_class->byval_arg;
5944         helper_sig_newarr->params [2] = &mono_defaults.int32_class->byval_arg;
5945         helper_sig_newarr->pinvoke = 1;
5946
5947         /* MonoArray * mono_array_new_specific (MonoVTable *vtable, guint32 len) */
5948         helper_sig_newarr_specific = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
5949         helper_sig_newarr_specific->params [0] = &mono_defaults.int_class->byval_arg;
5950         helper_sig_newarr_specific->params [1] = &mono_defaults.int32_class->byval_arg;
5951         helper_sig_newarr_specific->ret = &mono_defaults.object_class->byval_arg;
5952         helper_sig_newarr_specific->pinvoke = 1;
5953
5954         /* MonoObject * mono_object_new (MonoDomain *domain, MonoClass *klass) */
5955         helper_sig_object_new = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
5956         helper_sig_object_new->params [0] = helper_sig_object_new->params [1] = &mono_defaults.int_class->byval_arg;
5957         helper_sig_object_new->ret = &mono_defaults.object_class->byval_arg;
5958         helper_sig_object_new->pinvoke = 1;
5959
5960         /* MonoObject * mono_object_new_specific (MonoVTable *vtable) */
5961         helper_sig_object_new_specific = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
5962         helper_sig_object_new_specific->params [0] = &mono_defaults.int_class->byval_arg;
5963         helper_sig_object_new_specific->ret = &mono_defaults.object_class->byval_arg;
5964         helper_sig_object_new_specific->pinvoke = 1;
5965
5966         /* void* mono_method_compile (MonoMethod*) */
5967         helper_sig_compile = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
5968         helper_sig_compile->params [0] = helper_sig_compile->ret = &mono_defaults.int_class->byval_arg;
5969         helper_sig_compile->pinvoke = 1;
5970
5971         /* void* mono_ldvirtfn (MonoObject *, MonoMethod*) */
5972         helper_sig_compile_virt = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
5973         helper_sig_compile_virt->params [0] = &mono_defaults.object_class->byval_arg;
5974         helper_sig_compile_virt->params [1] = helper_sig_compile_virt->ret = &mono_defaults.int_class->byval_arg;
5975         helper_sig_compile_virt->pinvoke = 1;
5976
5977         /* MonoString* mono_ldstr (MonoDomain *domain, MonoImage *image, guint32 str_index) */
5978         helper_sig_ldstr = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
5979         helper_sig_ldstr->params [0] = helper_sig_ldstr->params [1] = &mono_defaults.int_class->byval_arg;
5980         helper_sig_ldstr->params [2] = &mono_defaults.int32_class->byval_arg;
5981         helper_sig_ldstr->ret = &mono_defaults.object_class->byval_arg;
5982         helper_sig_ldstr->pinvoke = 1;
5983
5984         /* MonoDomain *mono_domain_get (void) */
5985         helper_sig_domain_get = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
5986         helper_sig_domain_get->ret = &mono_defaults.int_class->byval_arg;
5987         helper_sig_domain_get->pinvoke = 1;
5988
5989         /* void* stelem_ref (MonoArray *, int index, MonoObject *) */
5990         helper_sig_stelem_ref = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
5991         helper_sig_stelem_ref->params [0] = &mono_defaults.array_class->byval_arg;
5992         helper_sig_stelem_ref->params [1] = &mono_defaults.int32_class->byval_arg;
5993         helper_sig_stelem_ref->params [2] = &mono_defaults.object_class->byval_arg;
5994         helper_sig_stelem_ref->ret = &mono_defaults.void_class->byval_arg;
5995         helper_sig_stelem_ref->pinvoke = 1;
5996
5997         /* void* stelem_ref_check (MonoArray *, MonoObject *) */
5998         helper_sig_stelem_ref_check = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
5999         helper_sig_stelem_ref_check->params [0] = &mono_defaults.array_class->byval_arg;
6000         helper_sig_stelem_ref_check->params [1] = &mono_defaults.object_class->byval_arg;
6001         helper_sig_stelem_ref_check->ret = &mono_defaults.void_class->byval_arg;
6002         helper_sig_stelem_ref_check->pinvoke = 1;
6003
6004         /* long amethod (long, long) */
6005         helper_sig_long_long_long = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
6006         helper_sig_long_long_long->params [0] = helper_sig_long_long_long->params [1] = 
6007                 &mono_defaults.int64_class->byval_arg;
6008         helper_sig_long_long_long->ret = &mono_defaults.int64_class->byval_arg;
6009         helper_sig_long_long_long->pinvoke = 1;
6010
6011         /* object  amethod (intptr) */
6012         helper_sig_obj_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6013         helper_sig_obj_ptr->params [0] = &mono_defaults.int_class->byval_arg;
6014         helper_sig_obj_ptr->ret = &mono_defaults.object_class->byval_arg;
6015         helper_sig_obj_ptr->pinvoke = 1;
6016
6017         /* void amethod (intptr) */
6018         helper_sig_void_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6019         helper_sig_void_ptr->params [0] = &mono_defaults.int_class->byval_arg;
6020         helper_sig_void_ptr->ret = &mono_defaults.void_class->byval_arg;
6021         helper_sig_void_ptr->pinvoke = 1;
6022
6023         /* void amethod (MonoObject *obj) */
6024         helper_sig_void_obj = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6025         helper_sig_void_obj->params [0] = &mono_defaults.object_class->byval_arg;
6026         helper_sig_void_obj->ret = &mono_defaults.void_class->byval_arg;
6027         helper_sig_void_obj->pinvoke = 1;
6028
6029         /* intptr amethod (void) */
6030         helper_sig_ptr_void = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
6031         helper_sig_ptr_void->ret = &mono_defaults.int_class->byval_arg;
6032         helper_sig_ptr_void->pinvoke = 1;
6033
6034         /* object amethod (void) */
6035         helper_sig_obj_void = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
6036         helper_sig_obj_void->ret = &mono_defaults.object_class->byval_arg;
6037         helper_sig_obj_void->pinvoke = 1;
6038
6039         /* void  amethod (intptr, intptr) */
6040         helper_sig_void_ptr_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
6041         helper_sig_void_ptr_ptr->params [0] = &mono_defaults.int_class->byval_arg;
6042         helper_sig_void_ptr_ptr->params [1] = &mono_defaults.int_class->byval_arg;
6043         helper_sig_void_ptr_ptr->ret = &mono_defaults.void_class->byval_arg;
6044         helper_sig_void_ptr_ptr->pinvoke = 1;
6045
6046         /* void  amethod (intptr, intptr, intptr) */
6047         helper_sig_void_ptr_ptr_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
6048         helper_sig_void_ptr_ptr_ptr->params [0] = &mono_defaults.int_class->byval_arg;
6049         helper_sig_void_ptr_ptr_ptr->params [1] = &mono_defaults.int_class->byval_arg;
6050         helper_sig_void_ptr_ptr_ptr->params [2] = &mono_defaults.int_class->byval_arg;
6051         helper_sig_void_ptr_ptr_ptr->ret = &mono_defaults.void_class->byval_arg;
6052         helper_sig_void_ptr_ptr_ptr->pinvoke = 1;
6053
6054         /* intptr  amethod (intptr, intptr) */
6055         helper_sig_ptr_ptr_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
6056         helper_sig_ptr_ptr_ptr->params [0] = &mono_defaults.int_class->byval_arg;
6057         helper_sig_ptr_ptr_ptr->params [1] = &mono_defaults.int_class->byval_arg;
6058         helper_sig_ptr_ptr_ptr->ret = &mono_defaults.int_class->byval_arg;
6059         helper_sig_ptr_ptr_ptr->pinvoke = 1;
6060
6061         /* IntPtr  amethod (object) */
6062         helper_sig_ptr_obj = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6063         helper_sig_ptr_obj->params [0] = &mono_defaults.object_class->byval_arg;
6064         helper_sig_ptr_obj->ret = &mono_defaults.int_class->byval_arg;
6065         helper_sig_ptr_obj->pinvoke = 1;
6066
6067         /* IntPtr  amethod (int) */
6068         helper_sig_ptr_int = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6069         helper_sig_ptr_int->params [0] = &mono_defaults.int32_class->byval_arg;
6070         helper_sig_ptr_int->ret = &mono_defaults.int_class->byval_arg;
6071         helper_sig_ptr_int->pinvoke = 1;
6072
6073         /* long amethod (long, guint32) */
6074         helper_sig_long_long_int = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
6075         helper_sig_long_long_int->params [0] = &mono_defaults.int64_class->byval_arg;
6076         helper_sig_long_long_int->params [1] = &mono_defaults.int32_class->byval_arg;
6077         helper_sig_long_long_int->ret = &mono_defaults.int64_class->byval_arg;
6078         helper_sig_long_long_int->pinvoke = 1;
6079
6080         /* ulong amethod (double) */
6081         helper_sig_ulong_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6082         helper_sig_ulong_double->params [0] = &mono_defaults.double_class->byval_arg;
6083         helper_sig_ulong_double->ret = &mono_defaults.uint64_class->byval_arg;
6084         helper_sig_ulong_double->pinvoke = 1;
6085
6086         /* long amethod (double) */
6087         helper_sig_long_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6088         helper_sig_long_double->params [0] = &mono_defaults.double_class->byval_arg;
6089         helper_sig_long_double->ret = &mono_defaults.int64_class->byval_arg;
6090         helper_sig_long_double->pinvoke = 1;
6091
6092         /* double amethod (long) */
6093         helper_sig_double_long = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6094         helper_sig_double_long->params [0] = &mono_defaults.int64_class->byval_arg;
6095         helper_sig_double_long->ret = &mono_defaults.double_class->byval_arg;
6096         helper_sig_double_long->pinvoke = 1;
6097
6098         /* double amethod (int) */
6099         helper_sig_double_int = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6100         helper_sig_double_int->params [0] = &mono_defaults.int32_class->byval_arg;
6101         helper_sig_double_int->ret = &mono_defaults.double_class->byval_arg;
6102         helper_sig_double_int->pinvoke = 1;
6103
6104         /* float amethod (long) */
6105         helper_sig_float_long = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6106         helper_sig_float_long->params [0] = &mono_defaults.int64_class->byval_arg;
6107         helper_sig_float_long->ret = &mono_defaults.single_class->byval_arg;
6108         helper_sig_float_long->pinvoke = 1;
6109
6110         /* double amethod (double, double) */
6111         helper_sig_double_double_double = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
6112         helper_sig_double_double_double->params [0] = &mono_defaults.double_class->byval_arg;
6113         helper_sig_double_double_double->params [1] = &mono_defaults.double_class->byval_arg;
6114         helper_sig_double_double_double->ret = &mono_defaults.double_class->byval_arg;
6115         helper_sig_double_double_double->pinvoke = 1;
6116
6117         /* uint amethod (double) */
6118         helper_sig_uint_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6119         helper_sig_uint_double->params [0] = &mono_defaults.double_class->byval_arg;
6120         helper_sig_uint_double->ret = &mono_defaults.uint32_class->byval_arg;
6121         helper_sig_uint_double->pinvoke = 1;
6122
6123         /* int amethod (double) */
6124         helper_sig_int_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6125         helper_sig_int_double->params [0] = &mono_defaults.double_class->byval_arg;
6126         helper_sig_int_double->ret = &mono_defaults.int32_class->byval_arg;
6127         helper_sig_int_double->pinvoke = 1;
6128
6129         /* void  initobj (intptr, int size) */
6130         helper_sig_initobj = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
6131         helper_sig_initobj->params [0] = &mono_defaults.int_class->byval_arg;
6132         helper_sig_initobj->params [1] = &mono_defaults.int32_class->byval_arg;
6133         helper_sig_initobj->ret = &mono_defaults.void_class->byval_arg;
6134         helper_sig_initobj->pinvoke = 1;
6135
6136         /* void  memcpy (intptr, intptr, int size) */
6137         helper_sig_memcpy = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
6138         helper_sig_memcpy->params [0] = &mono_defaults.int_class->byval_arg;
6139         helper_sig_memcpy->params [1] = &mono_defaults.int_class->byval_arg;
6140         helper_sig_memcpy->params [2] = &mono_defaults.int32_class->byval_arg;
6141         helper_sig_memcpy->ret = &mono_defaults.void_class->byval_arg;
6142         helper_sig_memcpy->pinvoke = 1;
6143
6144         /* void  memset (intptr, int val, int size) */
6145         helper_sig_memset = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
6146         helper_sig_memset->params [0] = &mono_defaults.int_class->byval_arg;
6147         helper_sig_memset->params [1] = &mono_defaults.int32_class->byval_arg;
6148         helper_sig_memset->params [2] = &mono_defaults.int32_class->byval_arg;
6149         helper_sig_memset->ret = &mono_defaults.void_class->byval_arg;
6150         helper_sig_memset->pinvoke = 1;
6151
6152         helper_sig_class_init_trampoline = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
6153         helper_sig_class_init_trampoline->ret = &mono_defaults.void_class->byval_arg;
6154         helper_sig_class_init_trampoline->pinvoke = 1;  
6155 }
6156
6157 static GHashTable *jit_icall_hash_name = NULL;
6158 static GHashTable *jit_icall_hash_addr = NULL;
6159
6160 MonoJitICallInfo *
6161 mono_find_jit_icall_by_name (const char *name)
6162 {
6163         g_assert (jit_icall_hash_name);
6164
6165         //printf ("lookup addr %s %p\n", name, g_hash_table_lookup (jit_icall_hash_name, name));
6166         return g_hash_table_lookup (jit_icall_hash_name, name);
6167 }
6168
6169 MonoJitICallInfo *
6170 mono_find_jit_icall_by_addr (gconstpointer addr)
6171 {
6172         g_assert (jit_icall_hash_addr);
6173
6174         return g_hash_table_lookup (jit_icall_hash_addr, (gpointer)addr);
6175 }
6176
6177 gconstpointer
6178 mono_icall_get_wrapper (MonoJitICallInfo* callinfo)
6179 {
6180         char *name;
6181         MonoMethod *wrapper;
6182         
6183         if (callinfo->wrapper)
6184                 return callinfo->wrapper;
6185         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
6186         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func);
6187         /* Must be domain neutral since there is only one copy */
6188         callinfo->wrapper = mono_jit_compile_method_with_opt (wrapper, default_opt | MONO_OPT_SHARED);
6189
6190         g_hash_table_insert (jit_icall_hash_addr, (gpointer)callinfo->wrapper, callinfo);
6191
6192         g_free (name);
6193         return callinfo->wrapper;
6194 }
6195
6196 MonoJitICallInfo *
6197 mono_register_jit_icall (gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean is_save)
6198 {
6199         MonoJitICallInfo *info;
6200         
6201         g_assert (func);
6202         g_assert (name);
6203
6204         if (!jit_icall_hash_name) {
6205                 jit_icall_hash_name = g_hash_table_new (g_str_hash, g_str_equal);
6206                 jit_icall_hash_addr = g_hash_table_new (NULL, NULL);
6207         }
6208
6209         if (g_hash_table_lookup (jit_icall_hash_name, name)) {
6210                 g_warning ("jit icall already defined \"%s\"\n", name);
6211                 g_assert_not_reached ();
6212         }
6213
6214         info = g_new (MonoJitICallInfo, 1);
6215         
6216         info->name = name;
6217         info->func = func;
6218         info->sig = sig;
6219
6220         if (is_save
6221 #ifdef MONO_USE_EXC_TABLES
6222             || mono_arch_has_unwind_info (func)
6223 #endif
6224             ) {
6225                 info->wrapper = func;
6226         } else {
6227                 info->wrapper = NULL;
6228         }
6229
6230         g_hash_table_insert (jit_icall_hash_name, (gpointer)info->name, info);
6231         g_hash_table_insert (jit_icall_hash_addr, (gpointer)func, info);
6232
6233         return info;
6234 }
6235
6236 gpointer
6237 mono_create_class_init_trampoline (MonoVTable *vtable)
6238 {
6239         gpointer code;
6240
6241         /* previously created trampoline code */
6242         mono_domain_lock (vtable->domain);
6243         code = 
6244                 mono_g_hash_table_lookup (vtable->domain->class_init_trampoline_hash,
6245                                                                   vtable);
6246         mono_domain_unlock (vtable->domain);
6247         if (code)
6248                 return code;
6249
6250         code = mono_arch_create_class_init_trampoline (vtable);
6251
6252         /* store trampoline address */
6253         mono_domain_lock (vtable->domain);
6254         mono_g_hash_table_insert (vtable->domain->class_init_trampoline_hash,
6255                                                           vtable, code);
6256         mono_domain_unlock (vtable->domain);
6257
6258         EnterCriticalSection (&trampoline_hash_mutex);
6259         if (!class_init_hash_addr)
6260                 class_init_hash_addr = g_hash_table_new (NULL, NULL);
6261         g_hash_table_insert (class_init_hash_addr, code, vtable);
6262         LeaveCriticalSection (&trampoline_hash_mutex);
6263
6264         return code;
6265 }
6266
6267 gpointer
6268 mono_create_jump_trampoline (MonoDomain *domain, MonoMethod *method, 
6269                                                          gboolean add_sync_wrapper)
6270 {
6271         MonoJitInfo *ji;
6272         gpointer code;
6273
6274         if (add_sync_wrapper && method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
6275                 return mono_create_jump_trampoline (domain, mono_marshal_get_synchronized_wrapper (method), FALSE);
6276
6277         code = mono_jit_find_compiled_method (domain, method);
6278         if (code)
6279                 return code;
6280
6281         EnterCriticalSection (&trampoline_hash_mutex);
6282
6283         if (jump_trampoline_hash) {
6284                 code = g_hash_table_lookup (jump_trampoline_hash, method);
6285                 if (code) {
6286                         LeaveCriticalSection (&trampoline_hash_mutex);
6287                         return code;
6288                 }
6289         }
6290
6291         ji = mono_arch_create_jump_trampoline (method);
6292
6293         /*
6294          * mono_delegate_ctor needs to find the method metadata from the 
6295          * trampoline address, so we save it here.
6296          */
6297
6298         mono_jit_info_table_add (mono_root_domain, ji);
6299
6300         if (!jump_trampoline_hash)
6301                 jump_trampoline_hash = g_hash_table_new (NULL, NULL);
6302         g_hash_table_insert (jump_trampoline_hash, method, ji->code_start);
6303
6304         LeaveCriticalSection (&trampoline_hash_mutex);
6305
6306         return ji->code_start;
6307 }
6308
6309 MonoVTable*
6310 mono_find_class_init_trampoline_by_addr (gconstpointer addr)
6311 {
6312         MonoVTable *res;
6313
6314         EnterCriticalSection (&trampoline_hash_mutex);
6315         if (class_init_hash_addr)
6316                 res = g_hash_table_lookup (class_init_hash_addr, addr);
6317         else
6318                 res = NULL;
6319         LeaveCriticalSection (&trampoline_hash_mutex);
6320         return res;
6321 }
6322
6323 void
6324 mono_register_opcode_emulation (int opcode, const char *name, MonoMethodSignature *sig, gpointer func, gboolean no_throw)
6325 {
6326         MonoJitICallInfo *info;
6327
6328         if (!emul_opcode_map)
6329                 emul_opcode_map = g_new0 (MonoJitICallInfo*, OP_LAST + 1);
6330
6331         g_assert (!sig->hasthis);
6332         g_assert (sig->param_count < 3);
6333
6334         info = mono_register_jit_icall (func, name, sig, no_throw);
6335
6336         emul_opcode_map [opcode] = info;
6337 }
6338
6339 static void
6340 decompose_foreach (MonoInst *tree, gpointer data) 
6341 {
6342         static MonoJitICallInfo *newarr_info = NULL;
6343         static MonoJitICallInfo *newarr_specific_info = NULL;
6344         MonoJitICallInfo *info;
6345         int i;
6346
6347         switch (tree->opcode) {
6348         case CEE_NEWARR: {
6349                 MonoCompile *cfg = data;
6350                 MonoInst *iargs [3];
6351
6352                 if (!newarr_info) {
6353                         newarr_info = mono_find_jit_icall_by_addr (mono_array_new);
6354                         g_assert (newarr_info);
6355                         newarr_specific_info = mono_find_jit_icall_by_addr (mono_array_new_specific);
6356                         g_assert (newarr_specific_info);
6357                 }
6358
6359                 if (cfg->opt & MONO_OPT_SHARED) {
6360                         NEW_DOMAINCONST (cfg, iargs [0]);
6361                         NEW_CLASSCONST (cfg, iargs [1], tree->inst_newa_class);
6362                         iargs [2] = tree->inst_newa_len;
6363
6364                         info = newarr_info;
6365                 }
6366                 else {
6367                         MonoVTable *vtable = mono_class_vtable (cfg->domain, mono_array_class_get (tree->inst_newa_class, 1));
6368
6369                         NEW_VTABLECONST (cfg, iargs [0], vtable);
6370                         iargs [1] = tree->inst_newa_len;
6371
6372                         info = newarr_specific_info;
6373                 }
6374
6375                 mono_emulate_opcode (cfg, tree, iargs, info);
6376
6377                 /* Need to decompose arguments after the the opcode is decomposed */
6378                 for (i = 0; i < info->sig->param_count; ++i)
6379                         dec_foreach (iargs [i], cfg);
6380                 break;
6381         }
6382
6383         default:
6384                 break;
6385         }
6386 }
6387
6388 void
6389 mono_inst_foreach (MonoInst *tree, MonoInstFunc func, gpointer data) {
6390
6391         switch (mono_burg_arity [tree->opcode]) {
6392         case 0: break;
6393         case 1: 
6394                 mono_inst_foreach (tree->inst_left, func, data);
6395                 break;
6396         case 2: 
6397                 mono_inst_foreach (tree->inst_left, func, data);
6398                 mono_inst_foreach (tree->inst_right, func, data);
6399                 break;
6400         default:
6401                 g_assert_not_reached ();
6402         }
6403         func (tree, data);
6404 }
6405
6406 G_GNUC_UNUSED
6407 static void
6408 mono_print_bb_code (MonoBasicBlock *bb) {
6409         if (bb->code) {
6410                 MonoInst *c = bb->code;
6411                 while (c) {
6412                         mono_print_tree (c);
6413                         g_print ("\n");
6414                         c = c->next;
6415                 }
6416         }
6417 }
6418
6419 static void
6420 print_dfn (MonoCompile *cfg) {
6421         int i, j;
6422         char *code;
6423         MonoBasicBlock *bb;
6424
6425         g_print ("IR code for method %s\n", mono_method_full_name (cfg->method, TRUE));
6426
6427         for (i = 0; i < cfg->num_bblocks; ++i) {
6428                 bb = cfg->bblocks [i];
6429                 if (bb->cil_code) {
6430                         char* code1, *code2;
6431                         code1 = mono_disasm_code_one (NULL, cfg->method, bb->cil_code, NULL);
6432                         if (bb->last_ins->cil_code)
6433                                 code2 = mono_disasm_code_one (NULL, cfg->method, bb->last_ins->cil_code, NULL);
6434                         else
6435                                 code2 = g_strdup ("");
6436
6437                         code1 [strlen (code1) - 1] = 0;
6438                         code = g_strdup_printf ("%s -> %s", code1, code2);
6439                         g_free (code1);
6440                         g_free (code2);
6441                 } else
6442                         code = g_strdup ("\n");
6443                 g_print ("\nBB%d DFN%d (len: %d): %s", bb->block_num, i, bb->cil_length, code);
6444                 if (bb->code) {
6445                         MonoInst *c = bb->code;
6446                         while (c) {
6447                                 mono_print_tree (c);
6448                                 g_print ("\n");
6449                                 c = c->next;
6450                         }
6451                 } else {
6452
6453                 }
6454
6455                 g_print ("\tprev:");
6456                 for (j = 0; j < bb->in_count; ++j) {
6457                         g_print (" BB%d", bb->in_bb [j]->block_num);
6458                 }
6459                 g_print ("\t\tsucc:");
6460                 for (j = 0; j < bb->out_count; ++j) {
6461                         g_print (" BB%d", bb->out_bb [j]->block_num);
6462                 }
6463                 g_print ("\n\tidom: BB%d\n", bb->idom? bb->idom->block_num: -1);
6464
6465                 if (bb->idom)
6466                         g_assert (mono_bitset_test_fast (bb->dominators, bb->idom->dfn));
6467
6468                 if (bb->dominators)
6469                         mono_blockset_print (cfg, bb->dominators, "\tdominators", bb->idom? bb->idom->dfn: -1);
6470                 if (bb->dfrontier)
6471                         mono_blockset_print (cfg, bb->dfrontier, "\tdfrontier", -1);
6472                 g_free (code);
6473         }
6474
6475         g_print ("\n");
6476 }
6477
6478 void
6479 mono_bblock_add_inst (MonoBasicBlock *bb, MonoInst *inst)
6480 {
6481         inst->next = NULL;
6482         if (bb->last_ins) {
6483                 g_assert (bb->code);
6484                 bb->last_ins->next = inst;
6485                 bb->last_ins = inst;
6486         } else {
6487                 bb->last_ins = bb->code = inst;
6488         }
6489 }
6490
6491 void
6492 mono_destroy_compile (MonoCompile *cfg)
6493 {
6494         //mono_mempool_stats (cfg->mempool);
6495         g_hash_table_destroy (cfg->bb_hash);
6496         if (cfg->rs)
6497                 mono_regstate_free (cfg->rs);
6498         if (cfg->spvars)
6499                 g_hash_table_destroy (cfg->spvars);
6500         mono_mempool_destroy (cfg->mempool);
6501         g_list_free (cfg->ldstr_list);
6502
6503         g_free (cfg->varinfo);
6504         g_free (cfg->vars);
6505         g_free (cfg);
6506 }
6507
6508 MonoLMF **
6509 mono_get_lmf_addr (void)
6510 {
6511         MonoJitTlsData *jit_tls;
6512
6513         if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
6514                 return &jit_tls->lmf;
6515
6516         g_assert_not_reached ();
6517         return NULL;
6518 }
6519
6520 /**
6521  * mono_thread_abort:
6522  * @obj: exception object
6523  *
6524  * abort the thread, print exception information and stack trace
6525  */
6526 static void
6527 mono_thread_abort (MonoObject *obj)
6528 {
6529         /* MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id); */
6530         
6531         /* handle_remove should be eventually called for this thread, too
6532         g_free (jit_tls);*/
6533
6534         ExitThread (-1);
6535 }
6536
6537 static void*
6538 setup_jit_tls_data (gpointer stack_start, gpointer abort_func)
6539 {
6540         MonoJitTlsData *jit_tls;
6541         MonoLMF *lmf;
6542
6543         jit_tls = g_new0 (MonoJitTlsData, 1);
6544
6545         TlsSetValue (mono_jit_tls_id, jit_tls);
6546
6547         jit_tls->abort_func = abort_func;
6548         jit_tls->end_of_stack = stack_start;
6549
6550         lmf = g_new0 (MonoLMF, 1);
6551         lmf->ebp = -1;
6552
6553         jit_tls->lmf = jit_tls->first_lmf = lmf;
6554
6555         mono_arch_setup_jit_tls_data (jit_tls);
6556
6557         return jit_tls;
6558 }
6559
6560 static void
6561 mono_thread_start_cb (guint32 tid, gpointer stack_start, gpointer func)
6562 {
6563         MonoThread *thread;
6564         void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort);
6565         thread = mono_thread_current ();
6566         if (thread)
6567                 thread->jit_data = jit_tls;
6568 }
6569
6570 void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
6571
6572 static void
6573 mono_thread_abort_dummy (MonoObject *obj)
6574 {
6575   if (mono_thread_attach_aborted_cb)
6576     mono_thread_attach_aborted_cb (obj);
6577   else
6578     mono_thread_abort (obj);
6579 }
6580
6581 static void
6582 mono_thread_attach_cb (guint32 tid, gpointer stack_start)
6583 {
6584         MonoThread *thread;
6585         void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort_dummy);
6586         thread = mono_thread_current ();
6587         if (thread)
6588                 thread->jit_data = jit_tls;
6589 }
6590
6591 static void
6592 mini_thread_cleanup (MonoThread *thread)
6593 {
6594         MonoJitTlsData *jit_tls = thread->jit_data;
6595
6596         if (jit_tls) {
6597                 mono_arch_free_jit_tls_data (jit_tls);
6598                 g_free (jit_tls->first_lmf);
6599                 g_free (jit_tls);
6600                 thread->jit_data = NULL;
6601         }
6602 }
6603
6604 void
6605 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
6606 {
6607         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
6608
6609         ji->ip.i = ip;
6610         ji->type = type;
6611         ji->data.target = target;
6612         ji->next = cfg->patch_info;
6613
6614         cfg->patch_info = ji;
6615 }
6616
6617 void
6618 mono_remove_patch_info (MonoCompile *cfg, int ip)
6619 {
6620         MonoJumpInfo **ji = &cfg->patch_info;
6621
6622         while (*ji) {
6623                 if ((*ji)->ip.i == ip)
6624                         *ji = (*ji)->next;
6625                 else
6626                         ji = &((*ji)->next);
6627         }
6628 }
6629
6630 static void
6631 dec_foreach (MonoInst *tree, MonoCompile *cfg) {
6632         MonoJitICallInfo *info;
6633
6634         decompose_foreach (tree, cfg);
6635
6636         switch (mono_burg_arity [tree->opcode]) {
6637         case 0: break;
6638         case 1: 
6639                 dec_foreach (tree->inst_left, cfg);
6640
6641                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
6642                         MonoInst *iargs [2];
6643                 
6644                         iargs [0] = tree->inst_left;
6645
6646                         mono_emulate_opcode (cfg, tree, iargs, info);
6647                         return;
6648                 }
6649
6650                 break;
6651         case 2:
6652 #ifdef MONO_ARCH_BIGMUL_INTRINS
6653                 if (tree->opcode == OP_LMUL
6654                                 && (cfg->opt & MONO_OPT_INTRINS)
6655                                 && (tree->inst_left->opcode == CEE_CONV_I8 
6656                                         || tree->inst_left->opcode == CEE_CONV_U8)
6657                                 && tree->inst_left->inst_left->type == STACK_I4
6658                                 && (tree->inst_right->opcode == CEE_CONV_I8 
6659                                         || tree->inst_right->opcode == CEE_CONV_U8)
6660                                 && tree->inst_right->inst_left->type == STACK_I4) {
6661                         tree->opcode = (tree->inst_left->opcode == CEE_CONV_I8 ? OP_BIGMUL: OP_BIGMUL_UN);
6662                         tree->inst_left = tree->inst_left->inst_left;
6663                         tree->inst_right = tree->inst_right->inst_left;
6664                         dec_foreach (tree, cfg);
6665                 } else 
6666 #endif
6667                         if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
6668                         MonoInst *iargs [2];
6669                 
6670                         iargs [0] = tree->inst_i0;
6671                         iargs [1] = tree->inst_i1;
6672                 
6673                         mono_emulate_opcode (cfg, tree, iargs, info);
6674
6675                         dec_foreach (iargs [0], cfg);
6676                         dec_foreach (iargs [1], cfg);
6677                         return;
6678                 } else {
6679                         dec_foreach (tree->inst_left, cfg);
6680                         dec_foreach (tree->inst_right, cfg);
6681                 }
6682                 break;
6683         default:
6684                 g_assert_not_reached ();
6685         }
6686 }
6687
6688 static void
6689 decompose_pass (MonoCompile *cfg) {
6690         MonoBasicBlock *bb;
6691
6692         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
6693                 MonoInst *tree;
6694                 cfg->cbb = bb;
6695                 cfg->prev_ins = NULL;
6696                 for (tree = cfg->cbb->code; tree; tree = tree->next) {
6697                         dec_foreach (tree, cfg);
6698                         cfg->prev_ins = tree;
6699                 }
6700         }
6701 }
6702
6703 static void
6704 nullify_basic_block (MonoBasicBlock *bb) 
6705 {
6706         bb->in_count = 0;
6707         bb->out_count = 0;
6708         bb->in_bb = NULL;
6709         bb->out_bb = NULL;
6710         bb->next_bb = NULL;
6711         bb->code = bb->last_ins = NULL;
6712         bb->cil_code = NULL;
6713 }
6714
6715 static void 
6716 replace_out_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
6717 {
6718         int i;
6719
6720         for (i = 0; i < bb->out_count; i++) {
6721                 MonoBasicBlock *ob = bb->out_bb [i];
6722                 if (ob == orig) {
6723                         if (!repl) {
6724                                 if (bb->out_count > 1) {
6725                                         bb->out_bb [i] = bb->out_bb [bb->out_count - 1];
6726                                 }
6727                                 bb->out_count--;
6728                         } else {
6729                                 bb->out_bb [i] = repl;
6730                         }
6731                 }
6732         }
6733 }
6734
6735 static void 
6736 replace_in_block (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl)
6737 {
6738         int i;
6739
6740         for (i = 0; i < bb->in_count; i++) {
6741                 MonoBasicBlock *ib = bb->in_bb [i];
6742                 if (ib == orig) {
6743                         if (!repl) {
6744                                 if (bb->in_count > 1) {
6745                                         bb->in_bb [i] = bb->in_bb [bb->in_count - 1];
6746                                 }
6747                                 bb->in_count--;
6748                         } else {
6749                                 bb->in_bb [i] = repl;
6750                         }
6751                 }
6752         }
6753 }
6754
6755 static void 
6756 replace_basic_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
6757 {
6758         int i, j;
6759
6760         for (i = 0; i < bb->out_count; i++) {
6761                 MonoBasicBlock *ob = bb->out_bb [i];
6762                 for (j = 0; j < ob->in_count; j++) {
6763                         if (ob->in_bb [j] == orig) {
6764                                 ob->in_bb [j] = repl;
6765                         }
6766                 }
6767         }
6768
6769 }
6770
6771
6772 static void
6773 merge_basic_blocks (MonoBasicBlock *bb, MonoBasicBlock *bbn) 
6774 {
6775         bb->out_count = bbn->out_count;
6776         bb->out_bb = bbn->out_bb;
6777
6778         replace_basic_block (bb, bbn, bb);
6779
6780         if (bb->last_ins) {
6781                 if (bbn->code) {
6782                         bb->last_ins->next = bbn->code;
6783                         bb->last_ins = bbn->last_ins;
6784                 }
6785         } else {
6786                 bb->code = bbn->code;
6787                 bb->last_ins = bbn->last_ins;
6788         }
6789         bb->next_bb = bbn->next_bb;
6790         nullify_basic_block (bbn);
6791 }
6792
6793 /*
6794  * Optimizes the branches on the Control Flow Graph
6795  *
6796  */
6797 static void
6798 optimize_branches (MonoCompile *cfg)
6799 {
6800         int i, changed = FALSE;
6801         MonoBasicBlock *bb, *bbn;
6802         guint32 niterations;
6803
6804         /*
6805          * Some crazy loops could cause the code below to go into an infinite
6806          * loop, see bug #53003 for an example. To prevent this, we put an upper
6807          * bound on the number of iterations.
6808          */
6809         niterations = 1000;
6810         do {
6811                 changed = FALSE;
6812                 niterations --;
6813
6814                 /* we skip the entry block (exit is handled specially instead ) */
6815                 for (bb = cfg->bb_entry->next_bb; bb; bb = bb->next_bb) {
6816
6817                         /* dont touch code inside exception clauses */
6818                         if (bb->region != -1)
6819                                 continue;
6820
6821                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
6822                                 if (cfg->verbose_level > 2)
6823                                         g_print ("nullify block triggered %d\n", bbn->block_num);
6824
6825                                 bb->next_bb = bbn->next_bb;
6826
6827                                 for (i = 0; i < bbn->out_count; i++)
6828                                         replace_in_block (bbn->out_bb [i], bbn, NULL);
6829
6830                                 nullify_basic_block (bbn);                      
6831                                 changed = TRUE;
6832                         }
6833
6834                         if (bb->out_count == 1) {
6835                                 bbn = bb->out_bb [0];
6836
6837                                 /* conditional branches where true and false targets are the same can be also replaced with CEE_BR */
6838                                 if (bb->last_ins && MONO_IS_COND_BRANCH (bb->last_ins->opcode)) {
6839                                         bb->last_ins->opcode = CEE_BR;
6840                                         bb->last_ins->inst_target_bb = bb->last_ins->inst_true_bb;
6841                                         changed = TRUE;
6842                                         if (cfg->verbose_level > 2)
6843                                                 g_print ("cond branch removal triggered in %d %d\n", bb->block_num, bb->out_count);
6844                                 }
6845
6846                                 if (bb->region == bbn->region && bb->next_bb == bbn) {
6847                                         /* the block are in sequence anyway ... */
6848
6849                                         /* branches to the following block can be removed */
6850                                         if (bb->last_ins && bb->last_ins->opcode == CEE_BR) {
6851                                                 bb->last_ins->opcode = CEE_NOP;
6852                                                 changed = TRUE;
6853                                                 if (cfg->verbose_level > 2)
6854                                                         g_print ("br removal triggered %d -> %d\n", bb->block_num, bbn->block_num);
6855                                         }
6856
6857                                         if (bbn->in_count == 1) {
6858
6859                                                 if (bbn != cfg->bb_exit) {
6860                                                         if (cfg->verbose_level > 2)
6861                                                                 g_print ("block merge triggered %d -> %d\n", bb->block_num, bbn->block_num);
6862                                                         merge_basic_blocks (bb, bbn);
6863                                                         changed = TRUE;
6864                                                 }
6865
6866                                                 //mono_print_bb_code (bb);
6867                                         }
6868                                 }                               
6869                         }
6870                 }
6871         } while (changed && (niterations > 0));
6872
6873         niterations = 1000;
6874         do {
6875                 changed = FALSE;
6876                 niterations --;
6877
6878                 /* we skip the entry block (exit is handled specially instead ) */
6879                 for (bb = cfg->bb_entry->next_bb; bb; bb = bb->next_bb) {
6880
6881                         /* dont touch code inside exception clauses */
6882                         if (bb->region != -1)
6883                                 continue;
6884
6885                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
6886                                 if (cfg->verbose_level > 2) {
6887                                         g_print ("nullify block triggered %d\n", bbn->block_num);
6888                                 }
6889                                 bb->next_bb = bbn->next_bb;
6890
6891                                 for (i = 0; i < bbn->out_count; i++)
6892                                         replace_in_block (bbn->out_bb [i], bbn, NULL);
6893
6894                                 nullify_basic_block (bbn);                      
6895                                 changed = TRUE;
6896                                 break;
6897                         }
6898
6899
6900                         if (bb->out_count == 1) {
6901                                 bbn = bb->out_bb [0];
6902
6903                                 if (bb->last_ins && bb->last_ins->opcode == CEE_BR) {
6904                                         bbn = bb->last_ins->inst_target_bb;
6905                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR &&
6906                                             bbn->code->inst_target_bb->region == bb->region) {
6907                                                 
6908                                                 if (cfg->verbose_level > 2)
6909                                                         g_print ("in %s branch to branch triggered %d -> %d\n", cfg->method->name, 
6910                                                                  bb->block_num, bbn->block_num);
6911                                                 
6912                                                 replace_basic_block (bb, bb->out_bb [0], bbn->code->inst_target_bb);
6913                                                 bb->last_ins->inst_target_bb = bbn->code->inst_target_bb;
6914                                                 changed = TRUE;
6915                                                 break;
6916                                         }
6917                                 }
6918                         } else if (bb->out_count == 2) {
6919                                 if (bb->last_ins && MONO_IS_COND_BRANCH (bb->last_ins->opcode)) {
6920                                         bbn = bb->last_ins->inst_true_bb;
6921                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR &&
6922                                             bbn->code->inst_target_bb->region == bb->region) {
6923                                                 if (cfg->verbose_level > 2)             
6924                                                         g_print ("cbranch1 to branch triggered %d -> (%d) %d (0x%02x)\n", 
6925                                                                  bb->block_num, bbn->block_num, bbn->code->inst_target_bb->block_num, 
6926                                                                  bbn->code->opcode);
6927
6928                                                 bb->last_ins->inst_true_bb = bbn->code->inst_target_bb;
6929
6930                                                 replace_in_block (bbn, bb, NULL);
6931                                                 if (!bbn->in_count)
6932                                                         replace_in_block (bbn->code->inst_target_bb, bbn, bb);
6933                                                 replace_out_block (bb, bbn, bbn->code->inst_target_bb);
6934
6935                                                 link_bblock (cfg, bb, bbn->code->inst_target_bb);
6936
6937                                                 changed = TRUE;
6938                                                 break;
6939                                         }
6940
6941                                         bbn = bb->last_ins->inst_false_bb;
6942                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR &&
6943                                             bbn->code->inst_target_bb->region == bb->region) {
6944                                                 if (cfg->verbose_level > 2)
6945                                                         g_print ("cbranch2 to branch triggered %d -> (%d) %d (0x%02x)\n", 
6946                                                                  bb->block_num, bbn->block_num, bbn->code->inst_target_bb->block_num, 
6947                                                                  bbn->code->opcode);
6948
6949                                                 bb->last_ins->inst_false_bb = bbn->code->inst_target_bb;
6950
6951                                                 replace_in_block (bbn, bb, NULL);
6952                                                 if (!bbn->in_count)
6953                                                         replace_in_block (bbn->code->inst_target_bb, bbn, bb);
6954                                                 replace_out_block (bb, bbn, bbn->code->inst_target_bb);
6955
6956                                                 link_bblock (cfg, bb, bbn->code->inst_target_bb);
6957
6958                                                 changed = TRUE;
6959                                                 break;
6960                                         }
6961                                 }
6962                         }
6963                 }
6964         } while (changed && (niterations > 0));
6965
6966 }
6967
6968 static void
6969 mono_compile_create_vars (MonoCompile *cfg)
6970 {
6971         MonoMethodSignature *sig;
6972         MonoMethodHeader *header;
6973         int i;
6974
6975         header = ((MonoMethodNormal *)cfg->method)->header;
6976
6977         sig = cfg->method->signature;
6978         
6979         if (!MONO_TYPE_IS_VOID (sig->ret)) {
6980                 cfg->ret = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
6981                 cfg->ret->opcode = OP_RETARG;
6982                 cfg->ret->inst_vtype = sig->ret;
6983                 cfg->ret->klass = mono_class_from_mono_type (sig->ret);
6984         }
6985         if (cfg->verbose_level > 2)
6986                 g_print ("creating vars\n");
6987
6988         if (sig->hasthis)
6989                 mono_compile_create_var (cfg, &cfg->method->klass->this_arg, OP_ARG);
6990
6991         for (i = 0; i < sig->param_count; ++i)
6992                 mono_compile_create_var (cfg, sig->params [i], OP_ARG);
6993
6994         cfg->locals_start = cfg->num_varinfo;
6995
6996         if (cfg->verbose_level > 2)
6997                 g_print ("creating locals\n");
6998         for (i = 0; i < header->num_locals; ++i)
6999                 mono_compile_create_var (cfg, header->locals [i], OP_LOCAL);
7000         if (cfg->verbose_level > 2)
7001                 g_print ("locals done\n");
7002 }
7003
7004 void
7005 mono_print_code (MonoCompile *cfg)
7006 {
7007         MonoBasicBlock *bb;
7008         
7009         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7010                 MonoInst *tree = bb->code;      
7011
7012                 if (!tree)
7013                         continue;
7014                 
7015                 g_print ("CODE BLOCK %d (nesting %d):\n", bb->block_num, bb->nesting);
7016
7017                 for (; tree; tree = tree->next) {
7018                         mono_print_tree (tree);
7019                         g_print ("\n");
7020                 }
7021
7022                 if (bb->last_ins)
7023                         bb->last_ins->next = NULL;
7024         }
7025 }
7026
7027 extern const char * const mono_burg_rule_string [];
7028
7029 static void
7030 emit_state (MonoCompile *cfg, MBState *state, int goal)
7031 {
7032         MBState *kids [10];
7033         int ern = mono_burg_rule (state, goal);
7034         const guint16 *nts = mono_burg_nts [ern];
7035         MBEmitFunc emit;
7036
7037         //g_print ("rule: %s\n", mono_burg_rule_string [ern]);
7038         switch (goal) {
7039         case MB_NTERM_reg:
7040                 //if (state->reg2)
7041                 //      state->reg1 = state->reg2; /* chain rule */
7042                 //else
7043                 state->reg1 = mono_regstate_next_int (cfg->rs);
7044                 //g_print ("alloc symbolic R%d (reg2: R%d) in block %d\n", state->reg1, state->reg2, cfg->cbb->block_num);
7045                 break;
7046         case MB_NTERM_lreg:
7047                 state->reg1 = mono_regstate_next_int (cfg->rs);
7048                 state->reg2 = mono_regstate_next_int (cfg->rs);
7049                 break;
7050         case MB_NTERM_freg:
7051                 state->reg1 = mono_regstate_next_float (cfg->rs);
7052                 break;
7053         default:
7054                 /* do nothing */
7055                 break;
7056         }
7057         if (nts [0]) {
7058                 mono_burg_kids (state, ern, kids);
7059
7060                 emit_state (cfg, kids [0], nts [0]);
7061                 if (nts [1]) {
7062                         emit_state (cfg, kids [1], nts [1]);
7063                         if (nts [2]) {
7064                                 g_assert (!nts [3]);
7065                                 emit_state (cfg, kids [2], nts [2]);
7066                         }
7067                 }
7068         }
7069
7070 //      g_print ("emit: %s (%p)\n", mono_burg_rule_string [ern], state);
7071         if ((emit = mono_burg_func [ern]))
7072                 emit (state, state->tree, cfg); 
7073 }
7074
7075 #define DEBUG_SELECTION
7076
7077 static void 
7078 mini_select_instructions (MonoCompile *cfg)
7079 {
7080         static int reverse_map [] = {
7081                 CEE_BNE_UN, CEE_BLT, CEE_BLE, CEE_BGT, CEE_BGE,
7082                 CEE_BEQ, CEE_BLT_UN, CEE_BLE_UN, CEE_BGT_UN, CEE_BGE_UN
7083         };
7084         static int reverse_fmap [] = {
7085                 OP_FBNE_UN, OP_FBLT, OP_FBLE, OP_FBGT, OP_FBGE,
7086                 OP_FBEQ, OP_FBLT_UN, OP_FBLE_UN, OP_FBGT_UN, OP_FBGE_UN
7087         };
7088         static int reverse_lmap [] = {
7089                 OP_LBNE_UN, OP_LBLT, OP_LBLE, OP_LBGT, OP_LBGE,
7090                 OP_LBEQ, OP_LBLT_UN, OP_LBLE_UN, OP_LBGT_UN, OP_LBGE_UN
7091         };
7092
7093         MonoBasicBlock *bb;
7094         
7095         cfg->state_pool = mono_mempool_new ();
7096         cfg->rs = mono_regstate_new ();
7097
7098         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7099                 if (bb->last_ins && MONO_IS_COND_BRANCH (bb->last_ins->opcode) &&
7100                     bb->next_bb != bb->last_ins->inst_false_bb) {
7101
7102                         if (bb->next_bb ==  bb->last_ins->inst_true_bb) {
7103                                 MonoBasicBlock *tmp =  bb->last_ins->inst_true_bb;
7104                                 bb->last_ins->inst_true_bb = bb->last_ins->inst_false_bb;
7105                                 bb->last_ins->inst_false_bb = tmp;
7106                                 
7107                                 if (bb->last_ins->opcode >= CEE_BEQ && bb->last_ins->opcode <= CEE_BLT_UN) {
7108                                         bb->last_ins->opcode = reverse_map [bb->last_ins->opcode - CEE_BEQ];
7109                                 } else if (bb->last_ins->opcode >= OP_FBEQ && bb->last_ins->opcode <= OP_FBLT_UN) {
7110                                         bb->last_ins->opcode = reverse_fmap [bb->last_ins->opcode - OP_FBEQ];
7111                                 } else if (bb->last_ins->opcode >= OP_LBEQ && bb->last_ins->opcode <= OP_LBLT_UN) {
7112                                         bb->last_ins->opcode = reverse_lmap [bb->last_ins->opcode - OP_LBEQ];
7113                                 }
7114                         } else {                        
7115                                 MonoInst *inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
7116                                 inst->opcode = CEE_BR;
7117                                 inst->inst_target_bb = bb->last_ins->inst_false_bb;
7118                                 mono_bblock_add_inst (bb, inst);
7119                         }
7120                 }
7121         }
7122
7123 #ifdef DEBUG_SELECTION
7124         if (cfg->verbose_level >= 4) {
7125         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7126                 MonoInst *tree = bb->code;      
7127                 g_print ("DUMP BLOCK %d:\n", bb->block_num);
7128                 if (!tree)
7129                         continue;
7130                 for (; tree; tree = tree->next) {
7131                         mono_print_tree (tree);
7132                         g_print ("\n");
7133                 }
7134         }
7135         }
7136 #endif
7137
7138         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7139                 MonoInst *tree = bb->code, *next;       
7140                 MBState *mbstate;
7141
7142                 if (!tree)
7143                         continue;
7144                 bb->code = NULL;
7145                 bb->last_ins = NULL;
7146                 
7147                 cfg->cbb = bb;
7148                 mono_regstate_reset (cfg->rs);
7149
7150 #ifdef DEBUG_SELECTION
7151                 if (cfg->verbose_level >= 3)
7152                         g_print ("LABEL BLOCK %d:\n", bb->block_num);
7153 #endif
7154                 for (; tree; tree = next) {
7155                         next = tree->next;
7156 #ifdef DEBUG_SELECTION
7157                         if (cfg->verbose_level >= 3) {
7158                                 mono_print_tree (tree);
7159                                 g_print ("\n");
7160                         }
7161 #endif
7162
7163                         if (!(mbstate = mono_burg_label (tree, cfg))) {
7164                                 g_warning ("unable to label tree %p", tree);
7165                                 mono_print_tree (tree);
7166                                 g_print ("\n");                         
7167                                 g_assert_not_reached ();
7168                         }
7169                         emit_state (cfg, mbstate, MB_NTERM_stmt);
7170                 }
7171                 bb->max_ireg = cfg->rs->next_vireg;
7172                 bb->max_freg = cfg->rs->next_vfreg;
7173
7174                 if (bb->last_ins)
7175                         bb->last_ins->next = NULL;
7176
7177                 mono_mempool_empty (cfg->state_pool); 
7178         }
7179         mono_mempool_destroy (cfg->state_pool); 
7180 }
7181
7182 void
7183 mono_codegen (MonoCompile *cfg)
7184 {
7185         MonoJumpInfo *patch_info;
7186         MonoBasicBlock *bb;
7187         int i, max_epilog_size;
7188         guint8 *code;
7189
7190         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7191                 cfg->spill_count = 0;
7192                 /* we reuse dfn here */
7193                 /* bb->dfn = bb_count++; */
7194                 mono_arch_local_regalloc (cfg, bb);
7195         }
7196
7197         if (cfg->prof_options & MONO_PROFILE_COVERAGE)
7198                 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, cfg->num_bblocks);
7199
7200         code = mono_arch_emit_prolog (cfg);
7201
7202         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
7203                 code = mono_arch_instrument_prolog (cfg, mono_profiler_method_enter, code, FALSE);
7204
7205         cfg->code_len = code - cfg->native_code;
7206         cfg->prolog_end = cfg->code_len;
7207
7208         mono_debug_open_method (cfg);
7209
7210         /* emit code all basic blocks */
7211         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7212                 bb->native_offset = cfg->code_len;
7213                 mono_arch_output_basic_block (cfg, bb);
7214         }
7215         cfg->bb_exit->native_offset = cfg->code_len;
7216
7217         code = cfg->native_code + cfg->code_len;
7218
7219         max_epilog_size = mono_arch_max_epilog_size (cfg);
7220
7221         /* we always allocate code in cfg->domain->code_mp to increase locality */
7222         cfg->code_size = cfg->code_len + max_epilog_size;
7223         /* fixme: align to MONO_ARCH_CODE_ALIGNMENT */
7224         code = mono_code_manager_reserve (cfg->domain->code_mp, cfg->code_size);
7225         memcpy (code, cfg->native_code, cfg->code_len);
7226         g_free (cfg->native_code);
7227         cfg->native_code = code;
7228         code = cfg->native_code + cfg->code_len;
7229   
7230         /* g_assert (((int)cfg->native_code & (MONO_ARCH_CODE_ALIGNMENT - 1)) == 0); */
7231
7232         cfg->epilog_begin = cfg->code_len;
7233
7234         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
7235                 code = mono_arch_instrument_epilog (cfg, mono_profiler_method_leave, code, FALSE);
7236
7237         cfg->code_len = code - cfg->native_code;
7238
7239         mono_arch_emit_epilog (cfg);
7240
7241         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7242                 switch (patch_info->type) {
7243                 case MONO_PATCH_INFO_ABS: {
7244                         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (patch_info->data.target);
7245                         if (info) {
7246                                 //printf ("TEST %s %p\n", info->name, patch_info->data.target);
7247                                 if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && 
7248                                         strstr (cfg->method->name, info->name))
7249                                         /*
7250                                          * This is an icall wrapper, and this is a call to the
7251                                          * wrapped function.
7252                                          */
7253                                         ;
7254                                 else {
7255                                         patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
7256                                         patch_info->data.name = info->name;
7257                                 }
7258                         }
7259                         else {
7260                                 MonoVTable *vtable = mono_find_class_init_trampoline_by_addr (patch_info->data.target);
7261                                 if (vtable) {
7262                                         patch_info->type = MONO_PATCH_INFO_CLASS_INIT;
7263                                         patch_info->data.klass = vtable->klass;
7264                                 }
7265                         }
7266                         break;
7267                 }
7268                 case MONO_PATCH_INFO_SWITCH: {
7269                         gpointer *table = mono_code_manager_reserve (cfg->domain->code_mp, sizeof (gpointer) * patch_info->table_size);
7270                         patch_info->ip.i = patch_info->ip.label->inst_c0;
7271                         for (i = 0; i < patch_info->table_size; i++) {
7272                                 table [i] = (gpointer)patch_info->data.table [i]->native_offset;
7273                         }
7274                         patch_info->data.target = table;
7275                         break;
7276                 }
7277                 default:
7278                         /* do nothing */
7279                         break;
7280                 }
7281         }
7282        
7283         if (cfg->verbose_level > 0)
7284                 g_print ("Method %s emitted at %p to %p [%s]\n", 
7285                                  mono_method_full_name (cfg->method, TRUE), 
7286                                  cfg->native_code, cfg->native_code + cfg->code_len, cfg->domain->friendly_name);
7287
7288         mono_arch_patch_code (cfg->method, cfg->domain, cfg->native_code, cfg->patch_info, cfg->run_cctors);
7289
7290         mono_code_manager_commit (cfg->domain->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
7291         mono_arch_flush_icache (cfg->native_code, cfg->code_len);
7292
7293         mono_debug_close_method (cfg);
7294 }
7295
7296 static void
7297 mono_cprop_copy_values (MonoCompile *cfg, MonoInst *tree, MonoInst **acp)
7298 {
7299         MonoInst *cp;
7300         int arity;
7301
7302         if (tree->ssa_op == MONO_SSA_LOAD && (tree->inst_i0->opcode == OP_LOCAL || tree->inst_i0->opcode == OP_ARG) && 
7303             (cp = acp [tree->inst_i0->inst_c0]) && !tree->inst_i0->flags) {
7304
7305                 if (cp->opcode == OP_ICONST) {
7306                         if (cfg->opt & MONO_OPT_CONSPROP) {
7307                                 //{ static int c = 0; printf ("CCOPY %d %d %s\n", c++, cp->inst_c0, mono_method_full_name (cfg->method, TRUE)); }
7308                                 *tree = *cp;
7309                         }
7310                 } else {
7311                         if (tree->inst_i0->inst_vtype->type == cp->inst_vtype->type) {
7312                                 if (cfg->opt & MONO_OPT_COPYPROP) {
7313                                         //{ static int c = 0; printf ("VCOPY %d\n", ++c); }
7314                                         tree->inst_i0 = cp;
7315                                 } 
7316                         }
7317                 } 
7318         } else {
7319                 arity = mono_burg_arity [tree->opcode];
7320
7321                 if (arity) {
7322                         mono_cprop_copy_values (cfg, tree->inst_i0, acp);
7323                         if (cfg->opt & MONO_OPT_CFOLD)
7324                                 mono_constant_fold_inst (tree, NULL); 
7325                         /* The opcode may have changed */
7326                         if (mono_burg_arity [tree->opcode] > 1) {
7327                                 mono_cprop_copy_values (cfg, tree->inst_i1, acp);
7328                                 if (cfg->opt & MONO_OPT_CFOLD)
7329                                         mono_constant_fold_inst (tree, NULL); 
7330                         }
7331                         mono_constant_fold_inst (tree, NULL); 
7332                 }
7333         }
7334 }
7335
7336 static void
7337 mono_cprop_invalidate_values (MonoInst *tree, MonoInst **acp, int acp_size)
7338 {
7339         int arity;
7340
7341         switch (tree->opcode) {
7342         case CEE_STIND_I:
7343         case CEE_STIND_I1:
7344         case CEE_STIND_I2:
7345         case CEE_STIND_I4:
7346         case CEE_STIND_REF:
7347         case CEE_STIND_I8:
7348         case CEE_STIND_R4:
7349         case CEE_STIND_R8:
7350         case CEE_STOBJ:
7351                 if (tree->ssa_op == MONO_SSA_NOP) {
7352                         memset (acp, 0, sizeof (MonoInst *) * acp_size);
7353                         return;
7354                 }
7355
7356                 break;
7357         case CEE_CALL:
7358         case OP_CALL_REG:
7359         case CEE_CALLVIRT:
7360         case OP_LCALL_REG:
7361         case OP_LCALLVIRT:
7362         case OP_LCALL:
7363         case OP_FCALL_REG:
7364         case OP_FCALLVIRT:
7365         case OP_FCALL:
7366         case OP_VCALL_REG:
7367         case OP_VCALLVIRT:
7368         case OP_VCALL:
7369         case OP_VOIDCALL_REG:
7370         case OP_VOIDCALLVIRT:
7371         case OP_VOIDCALL: {
7372                 MonoCallInst *call = (MonoCallInst *)tree;
7373                 MonoMethodSignature *sig = call->signature;
7374                 int i, byref = FALSE;
7375
7376                 for (i = 0; i < sig->param_count; i++) {
7377                         if (sig->params [i]->byref) {
7378                                 byref = TRUE;
7379                                 break;
7380                         }
7381                 }
7382
7383                 if (byref)
7384                         memset (acp, 0, sizeof (MonoInst *) * acp_size);
7385
7386                 return;
7387         }
7388         default:
7389                 break;
7390         }
7391
7392         arity = mono_burg_arity [tree->opcode];
7393
7394         switch (arity) {
7395         case 0:
7396                 break;
7397         case 1:
7398                 mono_cprop_invalidate_values (tree->inst_i0, acp, acp_size);
7399                 break;
7400         case 2:
7401                 mono_cprop_invalidate_values (tree->inst_i0, acp, acp_size);
7402                 mono_cprop_invalidate_values (tree->inst_i1, acp, acp_size);
7403                 break;
7404         default:
7405                 g_assert_not_reached ();
7406         }
7407 }
7408
7409 static void
7410 mono_local_cprop_bb (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst **acp, int acp_size)
7411 {
7412         MonoInst *tree = bb->code;      
7413         int i;
7414
7415         if (!tree)
7416                 return;
7417
7418         for (; tree; tree = tree->next) {
7419
7420                 mono_cprop_copy_values (cfg, tree, acp);
7421
7422                 mono_cprop_invalidate_values (tree, acp, acp_size);
7423
7424                 if (tree->ssa_op == MONO_SSA_STORE  && 
7425                     (tree->inst_i0->opcode == OP_LOCAL || tree->inst_i0->opcode == OP_ARG)) {
7426                         MonoInst *i1 = tree->inst_i1;
7427
7428                         acp [tree->inst_i0->inst_c0] = NULL;
7429
7430                         for (i = 0; i < acp_size; i++) {
7431                                 if (acp [i] && acp [i]->opcode != OP_ICONST && 
7432                                     acp [i]->inst_c0 == tree->inst_i0->inst_c0) {
7433                                         acp [i] = NULL;
7434                                 }
7435                         }
7436
7437                         if (i1->opcode == OP_ICONST) {
7438                                 acp [tree->inst_i0->inst_c0] = i1;
7439                                 //printf ("DEF1 BB%d %d\n", bb->block_num,tree->inst_i0->inst_c0);
7440                         }
7441                         if (i1->ssa_op == MONO_SSA_LOAD && 
7442                             (i1->inst_i0->opcode == OP_LOCAL || i1->inst_i0->opcode == OP_ARG) &&
7443                             (i1->inst_i0->inst_c0 != tree->inst_i0->inst_c0)) {
7444                                 acp [tree->inst_i0->inst_c0] = i1->inst_i0;
7445                                 //printf ("DEF2 BB%d %d %d\n", bb->block_num,tree->inst_i0->inst_c0,i1->inst_i0->inst_c0);
7446                         }
7447                 }
7448
7449                 /*
7450                   if (tree->opcode == CEE_BEQ) {
7451                   g_assert (tree->inst_i0->opcode == OP_COMPARE);
7452                   if (tree->inst_i0->inst_i0->opcode == OP_ICONST &&
7453                   tree->inst_i0->inst_i1->opcode == OP_ICONST) {
7454                   
7455                   tree->opcode = CEE_BR;
7456                   if (tree->inst_i0->inst_i0->opcode == tree->inst_i0->inst_i1->opcode) {
7457                   tree->inst_target_bb = tree->inst_true_bb;
7458                   } else {
7459                   tree->inst_target_bb = tree->inst_false_bb;
7460                   }
7461                   }
7462                   }
7463                 */
7464         }
7465 }
7466
7467 static void
7468 mono_local_cprop (MonoCompile *cfg)
7469 {
7470         MonoBasicBlock *bb;
7471         MonoInst **acp;
7472
7473         acp = alloca (sizeof (MonoInst *) * cfg->num_varinfo);
7474
7475         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7476                 memset (acp, 0, sizeof (MonoInst *) * cfg->num_varinfo);
7477                 mono_local_cprop_bb (cfg, bb, acp, cfg->num_varinfo);
7478         }
7479 }
7480
7481 MonoCompile*
7482 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gboolean run_cctors, int parts)
7483 {
7484         MonoMethodHeader *header = ((MonoMethodNormal *)method)->header;
7485         guint8 *ip = (guint8 *)header->code;
7486         MonoCompile *cfg;
7487         MonoJitInfo *jinfo;
7488         int dfn = 0, i, code_size_ratio;
7489
7490         mono_jit_stats.methods_compiled++;
7491         if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)
7492                 mono_profiler_method_jit (method);
7493
7494         cfg = g_new0 (MonoCompile, 1);
7495         cfg->method = method;
7496         cfg->mempool = mono_mempool_new ();
7497         cfg->opt = opts;
7498         cfg->prof_options = mono_profiler_get_events ();
7499         cfg->run_cctors = run_cctors;
7500         cfg->bb_hash = g_hash_table_new (NULL, NULL);
7501         cfg->domain = domain;
7502         cfg->verbose_level = mini_verbose;
7503         cfg->intvars = mono_mempool_alloc0 (cfg->mempool, sizeof (guint16) * STACK_MAX * 
7504                                             ((MonoMethodNormal *)method)->header->max_stack);
7505
7506         if (cfg->verbose_level > 2)
7507                 g_print ("converting method %s\n", mono_method_full_name (method, TRUE));
7508
7509         /*
7510          * create MonoInst* which represents arguments and local variables
7511          */
7512         mono_compile_create_vars (cfg);
7513
7514         if ((i = mono_method_to_ir (cfg, method, NULL, NULL, cfg->locals_start, NULL, NULL, NULL, 0, FALSE)) < 0) {
7515                 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
7516                         mono_profiler_method_end_jit (method, MONO_PROFILE_FAILED);
7517                 mono_destroy_compile (cfg);
7518                 return NULL;
7519         }
7520
7521         mono_jit_stats.basic_blocks += cfg->num_bblocks;
7522         mono_jit_stats.max_basic_blocks = MAX (cfg->num_bblocks, mono_jit_stats.max_basic_blocks);
7523
7524         if (cfg->num_varinfo > 2000) {
7525                 /* 
7526                  * we disable some optimizations if there are too many variables
7527                  * because JIT time may become too expensive. The actual number needs 
7528                  * to be tweaked and eventually the non-linear algorithms should be fixed.
7529                  */
7530                 cfg->opt &= ~ (MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP);
7531                 cfg->disable_ssa = TRUE;
7532         }
7533         /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/
7534
7535         /* Depth-first ordering on basic blocks */
7536         cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
7537
7538         if (cfg->opt & MONO_OPT_BRANCH)
7539                 optimize_branches (cfg);
7540
7541         df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
7542         if (cfg->num_bblocks != dfn + 1) {
7543                 MonoBasicBlock *bb;
7544
7545                 cfg->num_bblocks = dfn + 1;
7546
7547                 if (!header->clauses) {
7548                         /* remove unreachable code, because the code in them may be 
7549                          * inconsistent  (access to dead variables for example) */
7550                         for (bb = cfg->bb_entry; bb;) {
7551                                 MonoBasicBlock *bbn = bb->next_bb;
7552
7553                                 if (bbn && bbn->region == -1 && !bbn->dfn) {
7554                                         if (cfg->verbose_level > 1)
7555                                                 g_print ("found unreachabel code in BB%d\n", bbn->block_num);
7556                                         bb->next_bb = bbn->next_bb;
7557                                         nullify_basic_block (bbn);                      
7558                                 } else {
7559                                         bb = bb->next_bb;
7560                                 }
7561                         }
7562                 }
7563         }
7564
7565         if (cfg->opt & MONO_OPT_LOOP) {
7566                 mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM);
7567                 mono_compute_natural_loops (cfg);
7568         }
7569
7570         /* after method_to_ir */
7571         if (parts == 1)
7572                 return cfg;
7573
7574 //#define DEBUGSSA "logic_run"
7575 #define DEBUGSSA_CLASS "Tests"
7576 #ifdef DEBUGSSA
7577
7578         if (!header->num_clauses && !cfg->disable_ssa) {
7579                 mono_local_cprop (cfg);
7580                 mono_ssa_compute (cfg);
7581         }
7582 #else 
7583
7584         /* fixme: add all optimizations which requires SSA */
7585         if (cfg->opt & (MONO_OPT_DEADCE)) {
7586                 if (!(cfg->comp_done & MONO_COMP_SSA) && !header->num_clauses && !cfg->disable_ssa) {
7587                         mono_local_cprop (cfg);
7588                         mono_ssa_compute (cfg);
7589
7590                         if (cfg->verbose_level >= 2) {
7591                                 print_dfn (cfg);
7592                         }
7593                 }
7594         }
7595 #endif
7596
7597         /* after SSA translation */
7598         if (parts == 2)
7599                 return cfg;
7600
7601         if ((cfg->opt & MONO_OPT_CONSPROP) ||  (cfg->opt & MONO_OPT_COPYPROP)) {
7602                 if (cfg->comp_done & MONO_COMP_SSA) {
7603                         mono_ssa_cprop (cfg);
7604                 } else {
7605                         mono_local_cprop (cfg);
7606                 }
7607         }
7608
7609         if (cfg->comp_done & MONO_COMP_SSA) {                   
7610                 mono_ssa_deadce (cfg);
7611
7612                 //mono_ssa_strength_reduction (cfg);
7613
7614                 mono_ssa_remove (cfg);
7615
7616                 if (cfg->opt & MONO_OPT_BRANCH)
7617                         optimize_branches (cfg);
7618         }
7619
7620         /* after SSA removal */
7621         if (parts == 3)
7622                 return cfg;
7623
7624         decompose_pass (cfg);
7625
7626         if (cfg->opt & MONO_OPT_LINEARS) {
7627                 GList *vars, *regs;
7628
7629                 /* fixme: maybe we can avoid to compute livenesss here if already computed ? */
7630                 cfg->comp_done &= ~MONO_COMP_LIVENESS;
7631                 if (!(cfg->comp_done & MONO_COMP_LIVENESS))
7632                         mono_analyze_liveness (cfg);
7633
7634                 if ((vars = mono_arch_get_allocatable_int_vars (cfg))) {
7635                         regs = mono_arch_get_global_int_regs (cfg);
7636                         mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs);
7637                 }
7638         }
7639
7640         //mono_print_code (cfg);
7641
7642        //print_dfn (cfg);
7643         
7644         /* variables are allocated after decompose, since decompose could create temps */
7645         mono_arch_allocate_vars (cfg);
7646
7647         if (cfg->opt & MONO_OPT_CFOLD)
7648                 mono_constant_fold (cfg);
7649
7650         mini_select_instructions (cfg);
7651
7652         mono_codegen (cfg);
7653         if (cfg->verbose_level >= 2) {
7654                 char *id =  mono_method_full_name (cfg->method, FALSE);
7655                 mono_disassemble_code (cfg->native_code, cfg->code_len, id + 3);
7656                 g_free (id);
7657         }
7658         
7659         jinfo = mono_mempool_alloc0 (cfg->domain->mp, sizeof (MonoJitInfo));
7660
7661         jinfo = g_new0 (MonoJitInfo, 1);
7662         jinfo->method = method;
7663         jinfo->code_start = cfg->native_code;
7664         jinfo->code_size = cfg->code_len;
7665         jinfo->used_regs = cfg->used_int_regs;
7666         jinfo->domain_neutral = (cfg->opt & MONO_OPT_SHARED) != 0;
7667
7668         if (header->num_clauses) {
7669                 int i;
7670
7671                 jinfo->exvar_offset = cfg->exvar? cfg->exvar->inst_offset: 0;
7672                 jinfo->num_clauses = header->num_clauses;
7673                 jinfo->clauses = mono_mempool_alloc0 (cfg->domain->mp, 
7674                         sizeof (MonoJitExceptionInfo) * header->num_clauses);
7675
7676                 for (i = 0; i < header->num_clauses; i++) {
7677                         MonoExceptionClause *ec = &header->clauses [i];
7678                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
7679                         MonoBasicBlock *tblock;
7680
7681                         ei->flags = ec->flags;
7682
7683                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
7684                                 tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->token_or_filter);
7685                                 g_assert (tblock);
7686                                 ei->data.filter = cfg->native_code + tblock->native_offset;
7687                         } else {
7688                                 ei->data.token = ec->token_or_filter;
7689                         }
7690
7691                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->try_offset);
7692                         g_assert (tblock);
7693                         ei->try_start = cfg->native_code + tblock->native_offset;
7694                         g_assert (tblock->native_offset);
7695                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->try_offset + ec->try_len);
7696                         g_assert (tblock);
7697                         ei->try_end = cfg->native_code + tblock->native_offset;
7698                         g_assert (tblock->native_offset);
7699                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->handler_offset);
7700                         g_assert (tblock);
7701                         ei->handler_start = cfg->native_code + tblock->native_offset;
7702                 }
7703         }
7704
7705         cfg->jit_info = jinfo;
7706
7707         mono_jit_info_table_add (cfg->domain, jinfo);
7708
7709         /* collect statistics */
7710         mono_jit_stats.allocated_code_size += cfg->code_len;
7711         code_size_ratio = cfg->code_len;
7712         if (code_size_ratio > mono_jit_stats.biggest_method_size) {
7713                         mono_jit_stats.biggest_method_size = code_size_ratio;
7714                         mono_jit_stats.biggest_method = method;
7715         }
7716         code_size_ratio = (code_size_ratio * 100) / ((MonoMethodNormal *)method)->header->code_size;
7717         if (code_size_ratio > mono_jit_stats.max_code_size_ratio) {
7718                 mono_jit_stats.max_code_size_ratio = code_size_ratio;
7719                 mono_jit_stats.max_ratio_method = method;
7720         }
7721         mono_jit_stats.native_code_size += cfg->code_len;
7722
7723         if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
7724                 mono_profiler_method_end_jit (method, MONO_PROFILE_OK);
7725
7726         return cfg;
7727 }
7728
7729 static gpointer
7730 mono_jit_compile_method_inner (MonoMethod *method)
7731 {
7732         /* FIXME: later copy the code from mono */
7733         MonoDomain *target_domain, *domain = mono_domain_get ();
7734         MonoCompile *cfg;
7735         GHashTable *jit_code_hash;
7736         gpointer code;
7737         guint32 opt;
7738
7739         opt = default_opt;
7740
7741         if (opt & MONO_OPT_SHARED)
7742                 target_domain = mono_root_domain;
7743         else 
7744                 target_domain = domain;
7745
7746         jit_code_hash = target_domain->jit_code_hash;
7747
7748 #ifdef MONO_USE_AOT_COMPILER
7749         if (!mono_compile_aot && (opt & MONO_OPT_AOT)) {
7750                 MonoJitInfo *info;
7751
7752                 mono_domain_lock (domain);
7753
7754                 mono_class_init (method->klass);
7755                 if ((info = mono_aot_get_method (domain, method))) {
7756
7757                         g_hash_table_insert (domain->jit_code_hash, method, info);
7758
7759                         mono_domain_unlock (domain);
7760
7761                         /* make sure runtime_init is called */
7762                         mono_runtime_class_init (mono_class_vtable (domain, method->klass));
7763
7764                         return info->code_start;
7765                 }
7766
7767                 mono_domain_unlock (domain);
7768         }
7769 #endif
7770
7771         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
7772             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
7773                 MonoMethod *nm;
7774
7775                 if (!method->addr) {
7776                         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7777                                 method->addr = mono_lookup_internal_call (method);
7778                         else
7779                                 if (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)
7780                                         mono_lookup_pinvoke_call (method, NULL, NULL);
7781                 }
7782 #ifdef MONO_USE_EXC_TABLES
7783                 if (mono_method_blittable (method)) {
7784                         return method->addr;
7785                 } else {
7786 #endif
7787                         nm = mono_marshal_get_native_wrapper (method);
7788                         return mono_compile_method (nm);
7789
7790                         //if (mono_debug_format != MONO_DEBUG_FORMAT_NONE) 
7791                         //mono_debug_add_wrapper (method, nm);
7792 #ifdef MONO_USE_EXC_TABLES
7793                 }
7794 #endif
7795         } else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
7796                 const char *name = method->name;
7797                 MonoMethod *nm;
7798
7799                 if (method->klass->parent == mono_defaults.multicastdelegate_class) {
7800                         if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
7801                                 /* FIXME: uhm, we need a wrapper to handle exceptions? */
7802                                 return (gpointer)mono_delegate_ctor;
7803                         } else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
7804                                 nm = mono_marshal_get_delegate_invoke (method);
7805                                 return mono_jit_compile_method (nm);
7806                         } else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
7807                                 nm = mono_marshal_get_delegate_begin_invoke (method);
7808                                 return mono_jit_compile_method (nm);
7809                         } else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
7810                                 nm = mono_marshal_get_delegate_end_invoke (method);
7811                                 return mono_jit_compile_method (nm);
7812                         }
7813                 }
7814                 return NULL;
7815         }
7816
7817         cfg = mini_method_compile (method, opt, target_domain, TRUE, 0);
7818         code = cfg->native_code;
7819
7820         g_hash_table_insert (jit_code_hash, method, cfg->jit_info);
7821
7822         mono_destroy_compile (cfg);
7823
7824         if (target_domain->jump_target_hash) {
7825                 MonoJumpInfo patch_info;
7826                 GSList *list, *tmp;
7827                 list = g_hash_table_lookup (target_domain->jump_target_hash, method);
7828                 if (list) {
7829                         patch_info.next = NULL;
7830                         patch_info.ip.i = 0;
7831                         patch_info.type = MONO_PATCH_INFO_METHOD_JUMP;
7832                         patch_info.data.method = method;
7833                         g_hash_table_remove (target_domain->jump_target_hash, method);
7834                 }
7835                 for (tmp = list; tmp; tmp = tmp->next)
7836                         mono_arch_patch_code (NULL, target_domain, tmp->data, &patch_info, TRUE);
7837                 g_slist_free (list);
7838         }
7839         /* make sure runtime_init is called */
7840         mono_runtime_class_init (mono_class_vtable (target_domain, method->klass));
7841
7842         return code;
7843 }
7844
7845 static gpointer
7846 mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt)
7847 {
7848         /* FIXME: later copy the code from mono */
7849         MonoDomain *target_domain, *domain = mono_domain_get ();
7850         MonoJitInfo *info;
7851         gpointer code;
7852
7853         if (default_opt & MONO_OPT_SHARED)
7854                 target_domain = mono_root_domain;
7855         else 
7856                 target_domain = domain;
7857
7858         mono_domain_lock (target_domain);
7859
7860         if ((info = g_hash_table_lookup (target_domain->jit_code_hash, method))) {
7861                 /* We can't use a domain specific method in another domain */
7862                 if (! ((domain != target_domain) && !info->domain_neutral)) {
7863                         mono_domain_unlock (target_domain);
7864                         mono_jit_stats.methods_lookups++;
7865                         return info->code_start;
7866                 }
7867         }
7868
7869         code = mono_jit_compile_method_inner (method);
7870
7871         mono_domain_unlock (target_domain);
7872
7873         return code;
7874 }
7875
7876 static gpointer
7877 mono_jit_compile_method (MonoMethod *method)
7878 {
7879         return mono_jit_compile_method_with_opt (method, default_opt);
7880 }
7881
7882 static gpointer
7883 mono_jit_find_compiled_method (MonoDomain *domain, MonoMethod *method)
7884 {
7885         MonoDomain *target_domain;
7886         MonoJitInfo *info;
7887
7888         if (default_opt & MONO_OPT_SHARED)
7889                 target_domain = mono_root_domain;
7890         else 
7891                 target_domain = domain;
7892
7893         mono_domain_lock (target_domain);
7894
7895         if ((info = g_hash_table_lookup (target_domain->jit_code_hash, method))) {
7896                 /* We can't use a domain specific method in another domain */
7897                 if (! ((domain != target_domain) && !info->domain_neutral)) {
7898                         mono_domain_unlock (target_domain);
7899                         mono_jit_stats.methods_lookups++;
7900                         return info->code_start;
7901                 }
7902         }
7903
7904         mono_domain_unlock (target_domain);
7905
7906         return NULL;
7907 }
7908
7909 /**
7910  * mono_jit_runtime_invoke:
7911  * @method: the method to invoke
7912  * @obj: this pointer
7913  * @params: array of parameter values.
7914  * @exc: used to catch exceptions objects
7915  */
7916 static MonoObject*
7917 mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
7918 {
7919         MonoMethod *invoke;
7920         MonoObject *(*runtime_invoke) (MonoObject *this, void **params, MonoObject **exc);
7921
7922         if (obj == NULL && !(method->flags & METHOD_ATTRIBUTE_STATIC) && !method->string_ctor && (method->wrapper_type == 0)) {
7923                 g_warning ("Ignoring invocation of an instance method on a NULL instance.\n");
7924                 return NULL;
7925         }
7926
7927         invoke = mono_marshal_get_runtime_invoke (method);
7928         runtime_invoke = mono_jit_compile_method (invoke);
7929         return runtime_invoke (obj, params, exc);
7930 }
7931
7932 #ifdef PLATFORM_WIN32
7933 #define GET_CONTEXT \
7934         struct sigcontext *ctx = (struct sigcontext*)_dummy;
7935 #else
7936 #ifdef __sparc
7937 #define GET_CONTEXT \
7938     void *ctx = context;
7939 #else
7940 #define GET_CONTEXT \
7941         void **_p = (void **)&_dummy; \
7942         struct sigcontext *ctx = (struct sigcontext *)++_p;
7943 #endif
7944 #endif
7945
7946 #ifdef MONO_ARCH_USE_SIGACTION
7947 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy, siginfo_t *info, void *context)
7948 #else
7949 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy)
7950 #endif
7951
7952 static void
7953 SIG_HANDLER_SIGNATURE (sigfpe_signal_handler)
7954 {
7955         MonoException *exc;
7956         GET_CONTEXT
7957
7958         exc = mono_get_exception_divide_by_zero ();
7959         
7960         mono_arch_handle_exception (ctx, exc, FALSE);
7961 }
7962
7963 static void
7964 SIG_HANDLER_SIGNATURE (sigill_signal_handler)
7965 {
7966         MonoException *exc;
7967         GET_CONTEXT
7968         exc = mono_get_exception_execution_engine ("SIGILL");
7969         
7970         mono_arch_handle_exception (ctx, exc, FALSE);
7971 }
7972
7973 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
7974
7975 static void
7976 sigsegv_signal_handler (int _dummy, siginfo_t *info, void *context)
7977 {
7978         MonoException *exc;
7979         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
7980         struct sigcontext *ctx = (struct sigcontext *)&(((ucontext_t*)context)->uc_mcontext);
7981
7982         /* Can't allocate memory using Boehm GC on altstack */
7983         if (jit_tls->stack_size && 
7984                 ((guint8*)info->si_addr >= (guint8*)jit_tls->end_of_stack - jit_tls->stack_size) &&
7985                 ((guint8*)info->si_addr < (guint8*)jit_tls->end_of_stack))
7986                 exc = mono_domain_get ()->stack_overflow_ex;
7987         else
7988                 exc = mono_domain_get ()->null_reference_ex;
7989                         
7990         mono_arch_handle_exception (ctx, exc, FALSE);
7991 }
7992
7993 #else
7994
7995 static void
7996 SIG_HANDLER_SIGNATURE (sigsegv_signal_handler)
7997 {
7998         GET_CONTEXT;
7999
8000         mono_arch_handle_exception (ctx, NULL, FALSE);
8001 }
8002
8003 #endif
8004
8005 static void
8006 SIG_HANDLER_SIGNATURE (sigusr1_signal_handler)
8007 {
8008         MonoThread *thread;
8009         GET_CONTEXT
8010         
8011         thread = mono_thread_current ();
8012
8013         thread->abort_exc = mono_get_exception_thread_abort ();        
8014
8015         mono_arch_handle_exception (ctx, thread->abort_exc, FALSE);
8016 }
8017
8018 static void
8019 SIG_HANDLER_SIGNATURE (sigquit_signal_handler)
8020 {
8021        MonoException *exc;
8022        GET_CONTEXT
8023
8024        exc = mono_get_exception_execution_engine ("Interrupted (SIGQUIT).");
8025        
8026        mono_arch_handle_exception (ctx, exc, FALSE);
8027 }
8028
8029 static void
8030 SIG_HANDLER_SIGNATURE (sigint_signal_handler)
8031 {
8032         MonoException *exc;
8033         GET_CONTEXT
8034
8035         exc = mono_get_exception_execution_engine ("Interrupted (SIGINT).");
8036         
8037         mono_arch_handle_exception (ctx, exc, FALSE);
8038 }
8039
8040 static void
8041 add_signal_handler (int signo, gpointer handler)
8042 {
8043         struct sigaction sa;
8044
8045 #ifdef MONO_ARCH_USE_SIGACTION
8046         sa.sa_sigaction = handler;
8047         sigemptyset (&sa.sa_mask);
8048         sa.sa_flags = SA_SIGINFO;
8049 #else
8050         sa.sa_handler = handler;
8051         sigemptyset (&sa.sa_mask);
8052         sa.sa_flags = 0;
8053 #endif
8054         g_assert (sigaction (signo, &sa, NULL) != -1);
8055 }
8056
8057 static void
8058 mono_runtime_install_handlers (void)
8059 {
8060 #ifndef PLATFORM_WIN32
8061         struct sigaction sa;
8062 #endif
8063
8064 #ifdef PLATFORM_WIN32
8065         win32_seh_init();
8066         win32_seh_set_handler(SIGFPE, sigfpe_signal_handler);
8067         win32_seh_set_handler(SIGILL, sigill_signal_handler);
8068         win32_seh_set_handler(SIGSEGV, sigsegv_signal_handler);
8069         if (getenv ("MONO_DEBUG"))
8070                 win32_seh_set_handler(SIGINT, sigint_signal_handler);
8071 #else /* !PLATFORM_WIN32 */
8072
8073         /* libpthreads has its own implementation of sigaction(),
8074          * but it seems to work well with our current exception
8075          * handlers. If not we must call syscall directly instead 
8076          * of sigaction */
8077         
8078         if (getenv ("MONO_DEBUG")) {
8079                 add_signal_handler (SIGINT, sigint_signal_handler);
8080         }
8081
8082         add_signal_handler (SIGFPE, sigfpe_signal_handler);
8083         add_signal_handler (SIGQUIT, sigquit_signal_handler);
8084         add_signal_handler (SIGILL, sigill_signal_handler);
8085         add_signal_handler (mono_thread_get_abort_signal (), sigusr1_signal_handler);
8086
8087         /* catch SIGSEGV */
8088 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
8089         sa.sa_sigaction = sigsegv_signal_handler;
8090         sigemptyset (&sa.sa_mask);
8091         sa.sa_flags = SA_SIGINFO | SA_STACK;
8092         g_assert (sigaction (SIGSEGV, &sa, NULL) != -1);
8093 #else
8094         add_signal_handler (SIGSEGV, sigsegv_signal_handler);
8095 #endif
8096
8097 #endif /* PLATFORM_WIN32 */
8098 }
8099
8100 /* mono_jit_create_remoting_trampoline:
8101  * @method: pointer to the method info
8102  *
8103  * Creates a trampoline which calls the remoting functions. This
8104  * is used in the vtable of transparent proxies.
8105  * 
8106  * Returns: a pointer to the newly created code 
8107  */
8108 static gpointer
8109 mono_jit_create_remoting_trampoline (MonoMethod *method)
8110 {
8111         MonoMethod *nm;
8112         guint8 *addr = NULL;
8113
8114         if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) || 
8115             (method->signature->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class))) {
8116                 nm = mono_marshal_get_remoting_invoke (method);
8117                 addr = mono_compile_method (nm);
8118         } else {
8119                 addr = mono_compile_method (method);
8120         }
8121         return addr;
8122 }
8123
8124 MonoDomain *
8125 mini_init (const char *filename)
8126 {
8127         MonoDomain *domain;
8128
8129         mono_arch_cpu_init ();
8130
8131         if (!g_thread_supported ())
8132                 g_thread_init (NULL);
8133
8134         mono_jit_tls_id = TlsAlloc ();
8135         setup_jit_tls_data ((gpointer)-1, mono_thread_abort);
8136
8137         InitializeCriticalSection (&trampoline_hash_mutex);
8138
8139         mono_burg_init ();
8140
8141         if (default_opt & MONO_OPT_AOT)
8142                 mono_aot_init ();
8143
8144         mono_runtime_install_handlers ();
8145         mono_threads_install_cleanup (mini_thread_cleanup);
8146
8147 #define JIT_TRAMPOLINES_WORK
8148 #ifdef JIT_TRAMPOLINES_WORK
8149         mono_install_compile_method (mono_jit_compile_method);
8150         mono_install_trampoline (mono_arch_create_jit_trampoline);
8151         mono_install_remoting_trampoline (mono_jit_create_remoting_trampoline);
8152 #endif
8153 #define JIT_INVOKE_WORKS
8154 #ifdef JIT_INVOKE_WORKS
8155         mono_install_runtime_invoke (mono_jit_runtime_invoke);
8156         mono_install_handler (mono_arch_get_throw_exception ());
8157 #endif
8158         mono_install_stack_walk (mono_jit_walk_stack);
8159         mono_install_get_config_dir ();
8160
8161         domain = mono_init (filename);
8162         mono_init_icall ();
8163
8164         mono_add_internal_call ("System.Diagnostics.StackFrame::get_frame_info", 
8165                                 ves_icall_get_frame_info);
8166         mono_add_internal_call ("System.Diagnostics.StackTrace::get_trace", 
8167                                 ves_icall_get_trace);
8168         mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers", 
8169                                 mono_runtime_install_handlers);
8170
8171
8172         create_helper_signature ();
8173
8174 #define JIT_CALLS_WORK
8175 #ifdef JIT_CALLS_WORK
8176         /* Needs to be called here since register_jit_icall depends on it */
8177         mono_marshal_init ();
8178
8179         mono_arch_register_lowlevel_calls ();
8180         mono_register_jit_icall (mono_profiler_method_enter, "mono_profiler_method_enter", NULL, TRUE);
8181         mono_register_jit_icall (mono_profiler_method_leave, "mono_profiler_method_leave", NULL, TRUE);
8182         mono_register_jit_icall (mono_trace_enter_method, "mono_trace_enter_method", NULL, TRUE);
8183         mono_register_jit_icall (mono_trace_leave_method, "mono_trace_leave_method", NULL, TRUE);
8184
8185         mono_register_jit_icall (mono_get_lmf_addr, "mono_get_lmf_addr", helper_sig_ptr_void, TRUE);
8186         mono_register_jit_icall (mono_domain_get, "mono_domain_get", helper_sig_domain_get, TRUE);
8187
8188         /* fixme: we cant hanlde vararg methods this way, because the signature is not constant */
8189         //mono_register_jit_icall (ves_array_element_address, "ves_array_element_address", NULL);
8190         //mono_register_jit_icall (mono_array_new_va, "mono_array_new_va", NULL);
8191
8192         mono_register_jit_icall (mono_arch_get_throw_exception (), "mono_arch_throw_exception", helper_sig_void_obj, TRUE);
8193         mono_register_jit_icall (mono_arch_get_throw_exception_by_name (), "mono_arch_throw_exception_by_name", 
8194                                  helper_sig_void_ptr, TRUE);
8195         mono_register_jit_icall (mono_thread_get_pending_exception, "mono_thread_get_pending_exception", helper_sig_obj_void, FALSE);
8196
8197         /* 
8198          * NOTE, NOTE, NOTE, NOTE:
8199          * when adding emulation for some opcodes, remember to also add a dummy
8200          * rule to the burg files, because we need the arity information to be correct.
8201          */
8202         mono_register_opcode_emulation (OP_LMUL, "__emul_lmul", helper_sig_long_long_long, mono_llmult, TRUE);
8203         mono_register_opcode_emulation (OP_LMUL_OVF_UN, "__emul_lmul_ovf_un", helper_sig_long_long_long, mono_llmult_ovf_un, FALSE);
8204         mono_register_opcode_emulation (OP_LMUL_OVF, "__emul_lmul_ovf", helper_sig_long_long_long, mono_llmult_ovf, FALSE);
8205         mono_register_opcode_emulation (OP_LDIV, "__emul_ldiv", helper_sig_long_long_long, mono_lldiv, FALSE);
8206         mono_register_opcode_emulation (OP_LDIV_UN, "__emul_ldiv_un", helper_sig_long_long_long, mono_lldiv_un, FALSE);
8207         mono_register_opcode_emulation (OP_LREM, "__emul_lrem", helper_sig_long_long_long, mono_llrem, FALSE);
8208         mono_register_opcode_emulation (OP_LREM_UN, "__emul_lrem_un", helper_sig_long_long_long, mono_llrem_un, FALSE);
8209
8210         mono_register_opcode_emulation (OP_LSHL, "__emul_lshl", helper_sig_long_long_int, mono_lshl, TRUE);
8211         mono_register_opcode_emulation (OP_LSHR, "__emul_lshr", helper_sig_long_long_int, mono_lshr, TRUE);
8212         mono_register_opcode_emulation (OP_LSHR_UN, "__emul_lshr_un", helper_sig_long_long_int, mono_lshr_un, TRUE);
8213
8214         mono_register_opcode_emulation (OP_FCONV_TO_U8, "__emul_fconv_to_u8", helper_sig_ulong_double, mono_fconv_u8, FALSE);
8215         mono_register_opcode_emulation (OP_FCONV_TO_U4, "__emul_fconv_to_u4", helper_sig_uint_double, mono_fconv_u4, FALSE);
8216         mono_register_opcode_emulation (OP_FCONV_TO_OVF_I8, "__emul_fconv_to_ovf_i8", helper_sig_long_double, mono_fconv_ovf_i8, FALSE);
8217         mono_register_opcode_emulation (OP_FCONV_TO_OVF_U8, "__emul_fconv_to_ovf_u8", helper_sig_ulong_double, mono_fconv_ovf_u8, FALSE);
8218
8219 #ifdef MONO_ARCH_EMULATE_FCONV_TO_I8
8220         mono_register_opcode_emulation (OP_FCONV_TO_I8, "__emul_fconv_to_i8", helper_sig_long_double, mono_fconv_i8, FALSE);
8221 #endif
8222 #ifdef MONO_ARCH_EMULATE_CONV_R8_UN
8223         mono_register_opcode_emulation (CEE_CONV_R_UN, "__emul_conv_r_un", helper_sig_double_int, mono_conv_to_r8_un, FALSE);
8224 #endif
8225 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8
8226         mono_register_opcode_emulation (OP_LCONV_TO_R8, "__emul_lconv_to_r8", helper_sig_double_long, mono_lconv_to_r8, FALSE);
8227 #endif
8228 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R4
8229         mono_register_opcode_emulation (OP_LCONV_TO_R4, "__emul_lconv_to_r4", helper_sig_float_long, mono_lconv_to_r4, FALSE);
8230 #endif
8231 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8_UN
8232         mono_register_opcode_emulation (OP_LCONV_TO_R_UN, "__emul_lconv_to_r8_un", helper_sig_double_long, mono_lconv_to_r8_un, FALSE);
8233 #endif
8234 #ifdef MONO_ARCH_EMULATE_FREM
8235         mono_register_opcode_emulation (OP_FREM, "__emul_frem", helper_sig_double_double_double, fmod, FALSE);
8236 #endif
8237
8238 #if SIZEOF_VOID_P == 4
8239         mono_register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", helper_sig_uint_double, mono_fconv_u4, TRUE);
8240 #else
8241 #warning "fixme: add opcode emulation"
8242 #endif
8243
8244         /* other jit icalls */
8245         mono_register_jit_icall (mono_class_static_field_address , "mono_class_static_field_address", 
8246                                  helper_sig_ptr_ptr_ptr, FALSE);
8247         mono_register_jit_icall (mono_ldtoken_wrapper, "mono_ldtoken_wrapper", helper_sig_ptr_ptr_ptr, FALSE);
8248         mono_register_jit_icall (mono_get_special_static_data, "mono_get_special_static_data", helper_sig_ptr_int, FALSE);
8249         mono_register_jit_icall (mono_ldstr, "mono_ldstr", helper_sig_ldstr, FALSE);
8250         mono_register_jit_icall (helper_memcpy, "helper_memcpy", helper_sig_memcpy, FALSE);
8251         mono_register_jit_icall (helper_memset, "helper_memset", helper_sig_memset, FALSE);
8252         mono_register_jit_icall (helper_initobj, "helper_initobj", helper_sig_initobj, FALSE);
8253         mono_register_jit_icall (helper_stelem_ref, "helper_stelem_ref", helper_sig_stelem_ref, FALSE);
8254         mono_register_jit_icall (helper_stelem_ref_check, "helper_stelem_ref_check", helper_sig_stelem_ref_check, FALSE);
8255         mono_register_jit_icall (mono_object_new, "mono_object_new", helper_sig_object_new, FALSE);
8256         mono_register_jit_icall (mono_object_new_specific, "mono_object_new_specific", helper_sig_object_new_specific, FALSE);
8257         mono_register_jit_icall (mono_object_new_fast, "mono_object_new_fast", helper_sig_object_new_specific, FALSE);
8258         mono_register_jit_icall (mono_array_new, "mono_array_new", helper_sig_newarr, FALSE);
8259         mono_register_jit_icall (mono_array_new_specific, "mono_array_new_specific", helper_sig_newarr_specific, FALSE);
8260         mono_register_jit_icall (mono_string_to_utf16, "mono_string_to_utf16", helper_sig_ptr_obj, FALSE);
8261         mono_register_jit_icall (mono_string_from_utf16, "mono_string_from_utf16", helper_sig_obj_ptr, FALSE);
8262         mono_register_jit_icall (mono_string_new_wrapper, "mono_string_new_wrapper", helper_sig_obj_ptr, FALSE);
8263         mono_register_jit_icall (mono_string_to_utf8, "mono_string_to_utf8", helper_sig_ptr_obj, FALSE);
8264         mono_register_jit_icall (mono_string_to_bstr, "mono_string_to_bstr", helper_sig_ptr_obj, FALSE);
8265         mono_register_jit_icall (mono_string_to_ansibstr, "mono_string_to_ansibstr", helper_sig_ptr_obj, FALSE);
8266         mono_register_jit_icall (mono_string_builder_to_utf8, "mono_string_builder_to_utf8", helper_sig_ptr_obj, FALSE);
8267         mono_register_jit_icall (mono_string_builder_to_utf16, "mono_string_builder_to_utf16", helper_sig_ptr_obj, FALSE);
8268         mono_register_jit_icall (mono_array_to_savearray, "mono_array_to_savearray", helper_sig_ptr_obj, FALSE);
8269         mono_register_jit_icall (mono_array_to_lparray, "mono_array_to_lparray", helper_sig_ptr_obj, FALSE);
8270         mono_register_jit_icall (mono_delegate_to_ftnptr, "mono_delegate_to_ftnptr", helper_sig_ptr_obj, FALSE);
8271         mono_register_jit_icall (mono_marshal_string_array, "mono_marshal_string_array", helper_sig_ptr_obj, FALSE);
8272         mono_register_jit_icall (mono_string_utf8_to_builder, "mono_string_utf8_to_builder", helper_sig_void_ptr_ptr, FALSE);
8273         mono_register_jit_icall (mono_string_utf16_to_builder, "mono_string_utf16_to_builder", helper_sig_void_ptr_ptr, FALSE);
8274         mono_register_jit_icall (mono_marshal_free_array, "mono_marshal_free_array", helper_sig_void_ptr_ptr, FALSE);
8275         mono_register_jit_icall (mono_string_to_byvalstr, "mono_string_to_byvalstr", helper_sig_void_ptr_ptr_ptr, FALSE);
8276         mono_register_jit_icall (mono_string_to_byvalwstr, "mono_string_to_byvalwstr", helper_sig_void_ptr_ptr_ptr, FALSE);
8277         mono_register_jit_icall (g_free, "g_free", helper_sig_void_ptr, FALSE);
8278         mono_register_jit_icall (mono_runtime_class_init, "mono_runtime_class_init", helper_sig_void_ptr, FALSE);
8279         mono_register_jit_icall (mono_ldftn, "mono_ldftn", helper_sig_compile, FALSE);
8280         mono_register_jit_icall (mono_ldftn_nosync, "mono_ldftn_nosync", helper_sig_compile, FALSE);
8281         mono_register_jit_icall (mono_ldvirtfn, "mono_ldvirtfn", helper_sig_compile_virt, FALSE);
8282 #endif
8283
8284 #define JIT_RUNTIME_WORKS
8285 #ifdef JIT_RUNTIME_WORKS
8286         mono_runtime_install_cleanup ((MonoDomainFunc)mini_cleanup);
8287         mono_runtime_init (domain, mono_thread_start_cb, mono_thread_attach_cb);
8288 #endif
8289
8290         mono_thread_attach (domain);
8291         return domain;
8292 }
8293
8294 MonoJitStats mono_jit_stats = {0};
8295
8296 static void 
8297 print_jit_stats (void)
8298 {
8299         if (mono_jit_stats.enabled) {
8300                 g_print ("Mono Jit statistics\n");
8301                 g_print ("Compiled methods:       %ld\n", mono_jit_stats.methods_compiled);
8302                 g_print ("Methods from AOT:       %ld\n", mono_jit_stats.methods_aot);
8303                 g_print ("Methods cache lookup:   %ld\n", mono_jit_stats.methods_lookups);
8304                 g_print ("Method trampolines:     %ld\n", mono_jit_stats.method_trampolines);
8305                 g_print ("Basic blocks:           %ld\n", mono_jit_stats.basic_blocks);
8306                 g_print ("Max basic blocks:       %ld\n", mono_jit_stats.max_basic_blocks);
8307                 g_print ("Allocated vars:         %ld\n", mono_jit_stats.allocate_var);
8308                 g_print ("Analyze stack repeat:   %ld\n", mono_jit_stats.analyze_stack_repeat);
8309                 g_print ("Compiled CIL code size: %ld\n", mono_jit_stats.cil_code_size);
8310                 g_print ("Native code size:       %ld\n", mono_jit_stats.native_code_size);
8311                 g_print ("Max code size ratio:    %.2f (%s::%s)\n", mono_jit_stats.max_code_size_ratio/100.0,
8312                                 mono_jit_stats.max_ratio_method->klass->name, mono_jit_stats.max_ratio_method->name);
8313                 g_print ("Biggest method:         %ld (%s::%s)\n", mono_jit_stats.biggest_method_size,
8314                                 mono_jit_stats.biggest_method->klass->name, mono_jit_stats.biggest_method->name);
8315                 g_print ("Code reallocs:          %ld\n", mono_jit_stats.code_reallocs);
8316                 g_print ("Allocated code size:    %ld\n", mono_jit_stats.allocated_code_size);
8317                 g_print ("Inlineable methods:     %ld\n", mono_jit_stats.inlineable_methods);
8318                 g_print ("Inlined methods:        %ld\n", mono_jit_stats.inlined_methods);
8319                 
8320                 g_print ("\nCreated object count:   %ld\n", mono_stats.new_object_count);
8321                 g_print ("Initialized classes:    %ld\n", mono_stats.initialized_class_count);
8322                 g_print ("Used classes:           %ld\n", mono_stats.used_class_count);
8323                 g_print ("Static data size:       %ld\n", mono_stats.class_static_data_size);
8324                 g_print ("VTable data size:       %ld\n", mono_stats.class_vtable_size);
8325         }
8326 }
8327
8328 void
8329 mini_cleanup (MonoDomain *domain)
8330 {
8331         /* 
8332          * mono_runtime_cleanup() and mono_domain_finalize () need to
8333          * be called early since they need the execution engine still
8334          * fully working (mono_domain_finalize may invoke managed finalizers
8335          * and mono_runtime_cleanup will wait for other threads to finish).
8336          */
8337         mono_domain_finalize (domain, -1);
8338
8339         mono_runtime_cleanup (domain);
8340
8341         mono_profiler_shutdown ();
8342
8343         mono_debug_cleanup ();
8344
8345 #ifdef PLATFORM_WIN32
8346         win32_seh_cleanup();
8347 #endif
8348
8349         mono_domain_free (domain, TRUE);
8350
8351         print_jit_stats ();
8352 }
8353
8354 void
8355 mono_set_defaults (int verbose_level, guint32 opts)
8356 {
8357         mini_verbose = verbose_level;
8358         default_opt = opts;
8359 }
8360
8361 static void
8362 mono_precompile_assembly (MonoAssembly *ass, void *user_data)
8363 {
8364         MonoImage *image = ass->image;
8365         MonoMethod *method;
8366         int i, count = 0;
8367
8368         if (mini_verbose > 0)
8369                 printf ("PRECOMPILE: %s.\n", ass->image->name);
8370
8371         for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8372                 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
8373                 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
8374                         continue;
8375                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
8376                         continue;
8377
8378                 count++;
8379                 if (mini_verbose > 1) {
8380                         char * desc = mono_method_full_name (method, TRUE);
8381                         g_print ("Compiling %d %s\n", count, desc);
8382                         g_free (desc);
8383                 }
8384                 mono_compile_method (method);
8385         }
8386 }
8387
8388 void mono_precompile_assemblies ()
8389 {
8390         mono_assembly_foreach ((GFunc)mono_precompile_assembly, NULL);
8391 }