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