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