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