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