b7acd4ef6d7c889c9e4165ed2a17bb84bb00ed86
[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 #ifdef HAVE_UNISTD_H
14 #include <unistd.h>
15 #endif
16 #include <math.h>
17 #ifdef HAVE_SYS_TIME_H
18 #include <sys/time.h>
19 #endif
20
21 #ifdef PLATFORM_MACOSX
22 #include <mach/mach.h>
23 #include <mach/mach_error.h>
24 #include <mach/exception.h>
25 #include <mach/task.h>
26 #include <pthread.h>
27 #endif
28
29 #ifdef HAVE_VALGRIND_MEMCHECK_H
30 #include <valgrind/memcheck.h>
31 #endif
32
33 #include <mono/metadata/assembly.h>
34 #include <mono/metadata/loader.h>
35 #include <mono/metadata/tabledefs.h>
36 #include <mono/metadata/class.h>
37 #include <mono/metadata/object.h>
38 #include <mono/metadata/exception.h>
39 #include <mono/metadata/opcodes.h>
40 #include <mono/metadata/mono-endian.h>
41 #include <mono/metadata/tokentype.h>
42 #include <mono/metadata/tabledefs.h>
43 #include <mono/metadata/threads.h>
44 #include <mono/metadata/marshal.h>
45 #include <mono/metadata/socket-io.h>
46 #include <mono/metadata/appdomain.h>
47 #include <mono/metadata/debug-helpers.h>
48 #include <mono/io-layer/io-layer.h>
49 #include "mono/metadata/profiler.h"
50 #include <mono/metadata/profiler-private.h>
51 #include <mono/metadata/mono-config.h>
52 #include <mono/metadata/environment.h>
53 #include <mono/metadata/mono-debug.h>
54 #include <mono/metadata/monitor.h>
55 #include <mono/metadata/gc-internal.h>
56 #include <mono/metadata/security-manager.h>
57 #include <mono/metadata/threads-types.h>
58 #include <mono/metadata/rawbuffer.h>
59 #include <mono/metadata/security-core-clr.h>
60 #include <mono/metadata/verify.h>
61 #include <mono/metadata/verify-internals.h>
62 #include <mono/utils/mono-math.h>
63 #include <mono/utils/mono-compiler.h>
64 #include <mono/utils/mono-counters.h>
65 #include <mono/utils/mono-logger.h>
66 #include <mono/utils/mono-mmap.h>
67 #include <mono/utils/dtrace.h>
68
69 #include "mini.h"
70 #include <string.h>
71 #include <ctype.h>
72 #include "inssel.h"
73 #include "trace.h"
74
75 #include "jit-icalls.h"
76
77 #include "aliasing.h"
78
79 #include "debug-mini.h"
80
81 #define BRANCH_COST 100
82 #define INLINE_LENGTH_LIMIT 20
83 #define INLINE_FAILURE do {\
84                 if ((cfg->method != method) && (method->wrapper_type == MONO_WRAPPER_NONE))\
85                         goto inline_failure;\
86         } while (0)
87 #define CHECK_CFG_EXCEPTION do {\
88                 if (cfg->exception_type != MONO_EXCEPTION_NONE)\
89                         goto exception_exit;\
90         } while (0)
91 #define METHOD_ACCESS_FAILURE do {      \
92                 char *method_fname = mono_method_full_name (method, TRUE);      \
93                 char *cil_method_fname = mono_method_full_name (cil_method, TRUE);      \
94                 cfg->exception_type = MONO_EXCEPTION_METHOD_ACCESS;     \
95                 cfg->exception_message = g_strdup_printf ("Method `%s' is inaccessible from method `%s'\n", cil_method_fname, method_fname);    \
96                 g_free (method_fname);  \
97                 g_free (cil_method_fname);      \
98                 goto exception_exit;    \
99         } while (0)
100 #define FIELD_ACCESS_FAILURE do {       \
101                 char *method_fname = mono_method_full_name (method, TRUE);      \
102                 char *field_fname = mono_field_full_name (field);       \
103                 cfg->exception_type = MONO_EXCEPTION_FIELD_ACCESS;      \
104                 cfg->exception_message = g_strdup_printf ("Field `%s' is inaccessible from method `%s'\n", field_fname, method_fname);  \
105                 g_free (method_fname);  \
106                 g_free (field_fname);   \
107                 goto exception_exit;    \
108         } while (0)
109 #define GENERIC_SHARING_FAILURE(opcode) do {            \
110                 if (cfg->generic_sharing_context) {     \
111             if (cfg->verbose_level > 1) \
112                             printf ("sharing failed for method %s.%s.%s/%d opcode %s line %d\n", method->klass->name_space, method->klass->name, method->name, method->signature->param_count, mono_opcode_name ((opcode)), __LINE__); \
113                         cfg->exception_type = MONO_EXCEPTION_GENERIC_SHARING_FAILED;    \
114                         goto exception_exit;    \
115                 }                       \
116         } while (0)
117 #define GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD(opcode) do {                        \
118                 if (method->klass->valuetype)   \
119                         GENERIC_SHARING_FAILURE ((opcode)); \
120         } while (0)
121 #define GET_RGCTX(rgctx, context_used) do {                                             \
122                 MonoInst *this = NULL;                                  \
123                 g_assert (context_used);                                \
124                 GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD(*ip);       \
125                 if (!(method->flags & METHOD_ATTRIBUTE_STATIC) &&       \
126                                 !((context_used) & MONO_GENERIC_CONTEXT_USED_METHOD)) \
127                         NEW_ARGLOAD (cfg, this, 0);                     \
128                 (rgctx) = get_runtime_generic_context (cfg, method, (context_used), this, ip); \
129         } while (0)
130
131
132 #define MONO_CHECK_THIS(ins) (mono_method_signature (cfg->method)->hasthis && (ins)->ssa_op == MONO_SSA_LOAD && (ins)->inst_left->inst_c0 == 0)
133
134 static void setup_stat_profiler (void);
135 gboolean  mono_arch_print_tree(MonoInst *tree, int arity);
136 static gpointer mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt);
137 static gpointer mono_jit_compile_method (MonoMethod *method);
138 inline static int mono_emit_jit_icall (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoInst **args, const guint8 *ip);
139
140 static void handle_stobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, MonoInst *src, 
141                           const unsigned char *ip, MonoClass *klass, gboolean to_end, gboolean native, gboolean write_barrier);
142
143 static void dec_foreach (MonoInst *tree, MonoCompile *cfg);
144
145 static int mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
146                    int locals_offset, MonoInst *return_var, GList *dont_inline, MonoInst **inline_args, 
147                    guint inline_offset, gboolean is_virtual_call);
148
149 #ifdef MONO_ARCH_SOFT_FLOAT
150 static void
151 handle_store_float (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ptr, MonoInst *val, const unsigned char *ip);
152 #endif
153
154 /* helper methods signature */
155 static MonoMethodSignature *helper_sig_class_init_trampoline = NULL;
156 static MonoMethodSignature *helper_sig_generic_class_init_trampoline = NULL;
157 static MonoMethodSignature *helper_sig_rgctx_lazy_fetch_trampoline = NULL;
158 static MonoMethodSignature *helper_sig_domain_get = NULL;
159
160 static guint32 default_opt = 0;
161 static gboolean default_opt_set = FALSE;
162
163 guint32 mono_jit_tls_id = -1;
164
165 #ifdef HAVE_KW_THREAD
166 static __thread gpointer mono_jit_tls MONO_TLS_FAST;
167 #endif
168
169 MonoTraceSpec *mono_jit_trace_calls = NULL;
170 gboolean mono_break_on_exc = FALSE;
171 #ifndef DISABLE_AOT
172 gboolean mono_compile_aot = FALSE;
173 #endif
174 /* If this is set, no code is generated dynamically, everything is taken from AOT files */
175 gboolean mono_aot_only = FALSE;
176 MonoMethodDesc *mono_inject_async_exc_method = NULL;
177 int mono_inject_async_exc_pos;
178 MonoMethodDesc *mono_break_at_bb_method = NULL;
179 int mono_break_at_bb_bb_num;
180
181 static int mini_verbose = 0;
182
183 #define mono_jit_lock() EnterCriticalSection (&jit_mutex)
184 #define mono_jit_unlock() LeaveCriticalSection (&jit_mutex)
185 static CRITICAL_SECTION jit_mutex;
186
187 static GHashTable *rgctx_lazy_fetch_trampoline_hash = NULL;
188
189 static MonoCodeManager *global_codeman = NULL;
190
191 static GHashTable *jit_icall_name_hash = NULL;
192
193 static MonoDebugOptions debug_options;
194
195 #ifdef VALGRIND_JIT_REGISTER_MAP
196 static int valgrind_register = 0;
197 #endif
198
199 /*
200  * Table written to by the debugger with a 1-based index into the
201  * mono_breakpoint_info table, which contains changes made to
202  * the JIT instructions by the debugger.
203  */
204 gssize
205 mono_breakpoint_info_index [MONO_BREAKPOINT_ARRAY_SIZE];
206
207 /* Whenever to check for pending exceptions in managed-to-native wrappers */
208 gboolean check_for_pending_exc = TRUE;
209
210 gboolean
211 mono_running_on_valgrind (void)
212 {
213 #ifdef HAVE_VALGRIND_MEMCHECK_H
214                 if (RUNNING_ON_VALGRIND){
215 #ifdef VALGRIND_JIT_REGISTER_MAP
216                         valgrind_register = TRUE;
217 #endif
218                         return TRUE;
219                 } else
220                         return FALSE;
221 #else
222                 return FALSE;
223 #endif
224 }
225
226 typedef struct {
227         void *ip;
228         MonoMethod *method;
229 } FindTrampUserData;
230
231 static void
232 find_tramp (gpointer key, gpointer value, gpointer user_data)
233 {
234         FindTrampUserData *ud = (FindTrampUserData*)user_data;
235
236         if (value == ud->ip)
237                 ud->method = (MonoMethod*)key;
238 }
239
240 /* debug function */
241 G_GNUC_UNUSED static char*
242 get_method_from_ip (void *ip)
243 {
244         MonoJitInfo *ji;
245         char *method;
246         char *res;
247         MonoDomain *domain = mono_domain_get ();
248         MonoDebugSourceLocation *location;
249         FindTrampUserData user_data;
250         
251         ji = mono_jit_info_table_find (domain, ip);
252         if (!ji) {
253                 user_data.ip = ip;
254                 user_data.method = NULL;
255                 mono_domain_lock (domain);
256                 g_hash_table_foreach (domain->jit_trampoline_hash, find_tramp, &user_data);
257                 mono_domain_unlock (domain);
258                 if (user_data.method) {
259                         char *mname = mono_method_full_name (user_data.method, TRUE);
260                         res = g_strdup_printf ("<%p - JIT trampoline for %s>", ip, mname);
261                         g_free (mname);
262                         return res;
263                 }
264                 else
265                         return NULL;
266         }
267         method = mono_method_full_name (ji->method, TRUE);
268         /* FIXME: unused ? */
269         location = mono_debug_lookup_source_location (ji->method, (guint32)((guint8*)ip - (guint8*)ji->code_start), domain);
270
271         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);
272
273         mono_debug_free_source_location (location);
274         g_free (method);
275
276         return res;
277 }
278
279 /** 
280  * mono_pmip:
281  * @ip: an instruction pointer address
282  *
283  * This method is used from a debugger to get the name of the
284  * method at address @ip.   This routine is typically invoked from
285  * a debugger like this:
286  *
287  * (gdb) print mono_pmip ($pc)
288  *
289  * Returns: the name of the method at address @ip.
290  */
291 G_GNUC_UNUSED char *
292 mono_pmip (void *ip)
293 {
294         return get_method_from_ip (ip);
295 }
296
297 /** 
298  * mono_print_method_from_ip
299  * @ip: an instruction pointer address
300  *
301  * This method is used from a debugger to get the name of the
302  * method at address @ip.
303  *
304  * This prints the name of the method at address @ip in the standard
305  * output.  Unlike mono_pmip which returns a string, this routine
306  * prints the value on the standard output. 
307  */
308 void
309 mono_print_method_from_ip (void *ip)
310 {
311         MonoJitInfo *ji;
312         char *method;
313         MonoDebugSourceLocation *source;
314         MonoDomain *domain = mono_domain_get ();
315         FindTrampUserData user_data;
316         
317         ji = mono_jit_info_table_find (domain, ip);
318         if (!ji) {
319                 user_data.ip = ip;
320                 user_data.method = NULL;
321                 mono_domain_lock (domain);
322                 g_hash_table_foreach (domain->jit_trampoline_hash, find_tramp, &user_data);
323                 mono_domain_unlock (domain);
324                 if (user_data.method) {
325                         char *mname = mono_method_full_name (user_data.method, TRUE);
326                         printf ("IP %p is a JIT trampoline for %s\n", ip, mname);
327                         g_free (mname);
328                 }
329                 else
330                         g_print ("No method at %p\n", ip);
331                 return;
332         }
333         method = mono_method_full_name (ji->method, TRUE);
334         source = mono_debug_lookup_source_location (ji->method, (guint32)((guint8*)ip - (guint8*)ji->code_start), domain);
335
336         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);
337
338         if (source)
339                 g_print ("%s:%d\n", source->source_file, source->row);
340
341         mono_debug_free_source_location (source);
342         g_free (method);
343 }
344         
345 /* 
346  * mono_method_same_domain:
347  *
348  * Determine whenever two compiled methods are in the same domain, thus
349  * the address of the callee can be embedded in the caller.
350  */
351 gboolean mono_method_same_domain (MonoJitInfo *caller, MonoJitInfo *callee)
352 {
353         if (!caller || !callee)
354                 return FALSE;
355
356         /*
357          * If the call was made from domain-neutral to domain-specific 
358          * code, we can't patch the call site.
359          */
360         if (caller->domain_neutral && !callee->domain_neutral)
361                 return FALSE;
362
363         if ((caller->method->klass == mono_defaults.appdomain_class) &&
364                 (strstr (caller->method->name, "InvokeInDomain"))) {
365                  /* The InvokeInDomain methods change the current appdomain */
366                 return FALSE;
367         }
368
369         return TRUE;
370 }
371
372 /*
373  * mono_global_codeman_reserve:
374  *
375  *  Allocate code memory from the global code manager.
376  */
377 void *mono_global_codeman_reserve (int size)
378 {
379         void *ptr;
380
381         /*
382         if (mono_aot_only)
383                 g_error ("Attempting to allocate from the global code manager while running with --aot-only.\n");
384         */
385
386         if (!global_codeman) {
387                 /* This can happen during startup */
388                 global_codeman = mono_code_manager_new ();
389                 return mono_code_manager_reserve (global_codeman, size);
390         }
391         else {
392                 mono_jit_lock ();
393                 ptr = mono_code_manager_reserve (global_codeman, size);
394                 mono_jit_unlock ();
395                 return ptr;
396         }
397 }
398
399 MonoJumpInfoToken *
400 mono_jump_info_token_new (MonoMemPool *mp, MonoImage *image, guint32 token)
401 {
402         MonoJumpInfoToken *res = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoToken));
403         res->image = image;
404         res->token = token;
405
406         return res;
407 }
408
409 #define MONO_INIT_VARINFO(vi,id) do { \
410         (vi)->range.first_use.pos.bid = 0xffff; \
411         (vi)->reg = -1; \
412         (vi)->idx = (id); \
413 } while (0)
414
415 //#define UNVERIFIED do { G_BREAKPOINT (); goto unverified; } while (0)
416 #define UNVERIFIED do { if (debug_options.break_on_unverified) G_BREAKPOINT (); else goto unverified; } while (0)
417
418 /*
419  * Basic blocks have two numeric identifiers:
420  * dfn: Depth First Number
421  * block_num: unique ID assigned at bblock creation
422  */
423 #define NEW_BBLOCK(cfg,new_bb) do {     \
424                 new_bb = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock)); \
425                 MONO_INST_LIST_INIT (&new_bb->ins_list); \
426         } while (0)
427
428 #define ADD_BBLOCK(cfg,b) do {  \
429                 cfg->cil_offset_to_bb [(b)->cil_code - cfg->cil_start] = (b);   \
430                 (b)->block_num = cfg->num_bblocks++;    \
431                 (b)->real_offset = real_offset; \
432         } while (0)
433
434 #define GET_BBLOCK(cfg,tblock,ip) do {  \
435                 (tblock) = cfg->cil_offset_to_bb [(ip) - cfg->cil_start]; \
436                 if (!(tblock)) {        \
437                         if ((ip) >= end || (ip) < header->code) UNVERIFIED; \
438                         NEW_BBLOCK (cfg, (tblock));     \
439                         (tblock)->cil_code = (ip);      \
440                         ADD_BBLOCK (cfg, (tblock));     \
441                 } \
442         } while (0)
443
444 #define CHECK_BBLOCK(target,ip,tblock) do {     \
445                 if ((target) < (ip) && \
446                                 MONO_INST_LIST_EMPTY (&(tblock)->ins_list)) { \
447                         bb_recheck = g_list_prepend (bb_recheck, (tblock)); \
448                         if (cfg->verbose_level > 2) \
449                                 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)); \
450                 } \
451         } while (0)
452
453 #define NEW_ICONST(cfg,dest,val) do {   \
454                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
455                 (dest)->opcode = OP_ICONST;     \
456                 (dest)->inst_c0 = (val);        \
457                 (dest)->type = STACK_I4;        \
458         } while (0)
459
460 #define NEW_PCONST(cfg,dest,val) do {   \
461                 MONO_INST_NEW ((cfg), (dest), OP_PCONST);       \
462                 (dest)->inst_p0 = (val);        \
463                 (dest)->type = STACK_PTR;       \
464         } while (0)
465
466
467 #ifdef MONO_ARCH_NEED_GOT_VAR
468
469 #define NEW_PATCH_INFO(cfg,dest,el1,el2) do {   \
470                 MONO_INST_NEW ((cfg), (dest), OP_PATCH_INFO);   \
471                 (dest)->inst_left = (gpointer)(el1);    \
472                 (dest)->inst_right = (gpointer)(el2);   \
473         } while (0)
474
475 #define NEW_AOTCONST(cfg,dest,patch_type,cons) do {                     \
476                 MONO_INST_NEW ((cfg), (dest), OP_NOP); \
477                 (dest)->opcode = cfg->compile_aot ? OP_GOT_ENTRY : OP_PCONST; \
478                 if (cfg->compile_aot) {                                 \
479                         MonoInst *group, *got_var, *got_loc;            \
480                         got_loc = mono_get_got_var (cfg);               \
481                         NEW_TEMPLOAD ((cfg), got_var, got_loc->inst_c0); \
482                         NEW_PATCH_INFO ((cfg), group, cons, patch_type); \
483                         (dest)->inst_p0 = got_var;                      \
484                         (dest)->inst_p1 = group;                        \
485                 } else {                                                \
486                         (dest)->inst_p0 = (cons);                       \
487                         (dest)->inst_i1 = (gpointer)(patch_type);       \
488                 }                                                       \
489                 (dest)->type = STACK_PTR;                               \
490         } while (0)
491
492 #define NEW_AOTCONST_TOKEN(cfg,dest,patch_type,image,token,stack_type,stack_class) do { \
493                 MonoInst *group, *got_var, *got_loc;                    \
494                 MONO_INST_NEW ((cfg), (dest), OP_GOT_ENTRY); \
495                 got_loc = mono_get_got_var (cfg);                       \
496                 NEW_TEMPLOAD ((cfg), got_var, got_loc->inst_c0);        \
497                 NEW_PATCH_INFO ((cfg), group, NULL, patch_type);        \
498                 group->inst_p0 = mono_jump_info_token_new ((cfg)->mempool, (image), (token)); \
499                 (dest)->inst_p0 = got_var;                              \
500                 (dest)->inst_p1 = group;                                \
501                 (dest)->type = (stack_type);                    \
502         (dest)->klass = (stack_class);          \
503         } while (0)
504
505 #else
506
507 #define NEW_AOTCONST(cfg,dest,patch_type,cons) do {    \
508                 MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
509                 (dest)->opcode = cfg->compile_aot ? OP_AOTCONST : OP_PCONST;    \
510                 (dest)->inst_p0 = (cons);       \
511                 (dest)->inst_i1 = (gpointer)(patch_type); \
512                 (dest)->type = STACK_PTR;       \
513     } while (0)
514
515 #define NEW_AOTCONST_TOKEN(cfg,dest,patch_type,image,token,stack_type,stack_class) do { \
516                 MONO_INST_NEW ((cfg), (dest), OP_AOTCONST);     \
517                 (dest)->inst_p0 = mono_jump_info_token_new ((cfg)->mempool, (image), (token));  \
518                 (dest)->inst_p1 = (gpointer)(patch_type); \
519                 (dest)->type = (stack_type);    \
520         (dest)->klass = (stack_class);          \
521     } while (0)
522
523 #endif
524
525 #define NEW_CLASSCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_CLASS, (val))
526
527 #define NEW_IMAGECONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_IMAGE, (val))
528
529 #define NEW_FIELDCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_FIELD, (val))
530
531 #define NEW_METHODCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_METHODCONST, (val))
532
533 #define NEW_VTABLECONST(cfg,dest,vtable) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_VTABLE, cfg->compile_aot ? (gpointer)((vtable)->klass) : (vtable))
534
535 #define NEW_SFLDACONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_SFLDA, (val))
536
537 #define NEW_LDSTRCONST(cfg,dest,image,token) NEW_AOTCONST_TOKEN ((cfg), (dest), MONO_PATCH_INFO_LDSTR, (image), (token), STACK_OBJ, mono_defaults.string_class)
538
539 #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)
540
541 #define NEW_LDTOKENCONST(cfg,dest,image,token) NEW_AOTCONST_TOKEN ((cfg), (dest), MONO_PATCH_INFO_LDTOKEN, (image), (token), STACK_PTR, NULL)
542
543 #define NEW_DECLSECCONST(cfg,dest,image,entry) do { \
544                 if (cfg->compile_aot) { \
545                         NEW_AOTCONST_TOKEN (cfg, dest, MONO_PATCH_INFO_DECLSEC, image, (entry).index, STACK_OBJ, NULL); \
546                 } else { \
547                         NEW_PCONST (cfg, args [0], (entry).blob); \
548                 } \
549         } while (0)
550
551 #define NEW_DOMAINCONST(cfg,dest) do { \
552                 if (cfg->opt & MONO_OPT_SHARED) { \
553                         /* avoid depending on undefined C behavior in sequence points */ \
554                         MonoInst* __domain_var = mono_get_domainvar (cfg); \
555                         NEW_TEMPLOAD (cfg, dest, __domain_var->inst_c0); \
556                 } else { \
557                         NEW_PCONST (cfg, dest, (cfg)->domain); \
558                 } \
559         } while (0)
560
561 #define GET_VARINFO_INST(cfg,num) ((cfg)->varinfo [(num)]->inst)
562
563 #define NEW_ARGLOAD(cfg,dest,num) do {  \
564                 if (arg_array [(num)]->opcode == OP_ICONST) (dest) = arg_array [(num)]; else { \
565                 MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
566                 (dest)->ssa_op = MONO_SSA_LOAD; \
567                 (dest)->inst_i0 = arg_array [(num)];    \
568                 (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
569                 type_to_eval_stack_type ((cfg), param_types [(num)], (dest));   \
570                 (dest)->klass = (dest)->inst_i0->klass; \
571         }} while (0)
572
573 #define NEW_LOCLOAD(cfg,dest,num) do {  \
574                 MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
575                 (dest)->ssa_op = MONO_SSA_LOAD; \
576                 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)];       \
577                 (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
578                 type_to_eval_stack_type ((cfg), header->locals [(num)], (dest));        \
579                 (dest)->klass = (dest)->inst_i0->klass; \
580         } while (0)
581
582 #define NEW_LOCLOADA(cfg,dest,num) do { \
583                 MONO_INST_NEW ((cfg), (dest), OP_LDADDR);       \
584                 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN;        \
585                 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)];       \
586                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
587                 (dest)->type = STACK_MP;        \
588                 (dest)->klass = (dest)->inst_i0->klass; \
589         if (!MONO_TYPE_ISSTRUCT (header->locals [(num)])) \
590            (cfg)->disable_ssa = TRUE; \
591         } while (0)
592
593 #define NEW_RETLOADA(cfg,dest) do {     \
594         if (cfg->vret_addr) { \
595                     MONO_INST_NEW ((cfg), (dest), OP_NOP);      \
596                     (dest)->ssa_op = MONO_SSA_LOAD;     \
597                     (dest)->inst_i0 = cfg->vret_addr; \
598                     (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
599             (dest)->type = STACK_MP; \
600                     (dest)->klass = (dest)->inst_i0->klass;     \
601         } else { \
602                         MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
603                     (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN;    \
604                     (dest)->inst_i0 = (cfg)->ret;       \
605                     (dest)->inst_i0->flags |= MONO_INST_INDIRECT;       \
606                     (dest)->opcode = cfg->ret_var_is_local ? OP_LDADDR : CEE_LDIND_I;   \
607                     (dest)->type = STACK_MP;    \
608                     (dest)->klass = (dest)->inst_i0->klass;     \
609             (cfg)->disable_ssa = TRUE; \
610         } \
611         } while (0)
612
613 #define NEW_ARGLOADA(cfg,dest,num) do { \
614                 if (arg_array [(num)]->opcode == OP_ICONST) goto inline_failure; \
615                 MONO_INST_NEW ((cfg), (dest), OP_LDADDR);       \
616                 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN;        \
617                 (dest)->inst_i0 = arg_array [(num)];    \
618                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
619                 (dest)->type = STACK_MP;        \
620                 (dest)->klass = (dest)->inst_i0->klass; \
621                 (cfg)->disable_ssa = TRUE; \
622         } while (0)
623
624 #define NEW_TEMPLOAD(cfg,dest,num) do { \
625                 MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
626                 (dest)->ssa_op = MONO_SSA_LOAD; \
627                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
628                 (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
629                 type_to_eval_stack_type ((cfg), (dest)->inst_i0->inst_vtype, (dest));   \
630                 (dest)->klass = (dest)->inst_i0->klass; \
631         } while (0)
632
633 #define NEW_TEMPLOADA(cfg,dest,num) do {        \
634                 MONO_INST_NEW ((cfg), (dest), OP_LDADDR);       \
635                 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN;        \
636                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
637                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
638                 (dest)->type = STACK_MP;        \
639                 (dest)->klass = (dest)->inst_i0->klass; \
640         if (!MONO_TYPE_ISSTRUCT (cfg->varinfo [(num)]->inst_vtype)) \
641            (cfg)->disable_ssa = TRUE; \
642         } while (0)
643
644 #define NEW_INDLOAD(cfg,dest,addr,vtype) do {   \
645                 MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
646                 (dest)->inst_left = addr;       \
647                 (dest)->opcode = mini_type_to_ldind ((cfg), vtype);     \
648                 type_to_eval_stack_type ((cfg), vtype, (dest)); \
649                 /* FIXME: (dest)->klass = (dest)->inst_i0->klass;*/     \
650         } while (0)
651
652 #define NEW_INDSTORE(cfg,dest,addr,value,vtype) do {    \
653                 MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
654                 (dest)->inst_i0 = addr; \
655                 (dest)->opcode = mini_type_to_stind ((cfg), vtype);     \
656                 (dest)->inst_i1 = (value);      \
657                 /* FIXME: (dest)->klass = (dest)->inst_i0->klass;*/     \
658         } while (0)
659
660 #define NEW_TEMPSTORE(cfg,dest,num,inst) do {   \
661                 MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
662                 (dest)->ssa_op = MONO_SSA_STORE;        \
663                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
664                 (dest)->opcode = mini_type_to_stind ((cfg), (dest)->inst_i0->inst_vtype); \
665                 (dest)->inst_i1 = (inst);       \
666                 (dest)->klass = (dest)->inst_i0->klass; \
667         } while (0)
668
669 #define NEW_LOCSTORE(cfg,dest,num,inst) do {    \
670                 MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
671                 (dest)->opcode = mini_type_to_stind ((cfg), header->locals [(num)]); \
672                 (dest)->ssa_op = MONO_SSA_STORE;        \
673                 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)];       \
674                 (dest)->inst_i1 = (inst);       \
675                 (dest)->klass = (dest)->inst_i0->klass; \
676         } while (0)
677
678 #define NEW_ARGSTORE(cfg,dest,num,inst) do {    \
679                 if (arg_array [(num)]->opcode == OP_ICONST) goto inline_failure; \
680                 MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
681                 (dest)->opcode = mini_type_to_stind ((cfg), param_types [(num)]); \
682                 (dest)->ssa_op = MONO_SSA_STORE;        \
683                 (dest)->inst_i0 = arg_array [(num)];    \
684                 (dest)->inst_i1 = (inst);       \
685                 (dest)->klass = (dest)->inst_i0->klass; \
686         } while (0)
687
688 #define NEW_MEMCPY(cfg,dest,dst,src,memcpy_size,memcpy_align) do { \
689                 MONO_INST_NEW (cfg, dest, OP_MEMCPY); \
690         (dest)->inst_left = (dst); \
691                 (dest)->inst_right = (src); \
692         (dest)->backend.memcpy_args = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoMemcpyArgs)); \
693                 (dest)->backend.memcpy_args->size = (memcpy_size); \
694                 (dest)->backend.memcpy_args->align = (memcpy_align); \
695     } while (0)
696
697 #define NEW_MEMSET(cfg,dest,dst,imm,memcpy_size,memcpy_align) do { \
698                 MONO_INST_NEW (cfg, dest, OP_MEMSET); \
699         (dest)->inst_left = (dst); \
700                 (dest)->inst_imm = (imm); \
701         (dest)->backend.memcpy_args = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoMemcpyArgs)); \
702                 (dest)->backend.memcpy_args->size = (memcpy_size); \
703                 (dest)->backend.memcpy_args->align = (memcpy_align); \
704     } while (0)
705
706 #define NEW_DUMMY_USE(cfg,dest,load) do { \
707                 MONO_INST_NEW ((cfg), (dest), OP_DUMMY_USE);    \
708                 (dest)->inst_left = (load); \
709     } while (0)
710
711 #define NEW_DUMMY_STORE(cfg,dest,num) do { \
712                 MONO_INST_NEW ((cfg), (dest), OP_DUMMY_STORE);  \
713                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
714                 (dest)->klass = (dest)->inst_i0->klass; \
715         } while (0)
716
717 #define ADD_BINOP(op) do {      \
718                 MONO_INST_NEW (cfg, ins, (op)); \
719                 sp -= 2;        \
720                 ins->inst_i0 = sp [0];  \
721                 ins->inst_i1 = sp [1];  \
722                 *sp++ = ins;    \
723                 type_from_op (ins);     \
724                 CHECK_TYPE (ins);       \
725                 /* Have to insert a widening op */               \
726                 /* FIXME: Need to add many more cases */ \
727                 if (ins->inst_i0->type == STACK_PTR && ins->inst_i1->type == STACK_I4) { \
728                         MonoInst *widen;  \
729                         MONO_INST_NEW (cfg, widen, CEE_CONV_I); \
730             widen->inst_i0 = ins->inst_i1; \
731                         ins->inst_i1 = widen; \
732                 } \
733         } while (0)
734
735 #define ADD_UNOP(op) do {       \
736                 MONO_INST_NEW (cfg, ins, (op)); \
737                 sp--;   \
738                 ins->inst_i0 = sp [0];  \
739                 *sp++ = ins;    \
740                 type_from_op (ins);     \
741                 CHECK_TYPE (ins);       \
742         } while (0)
743
744 #define ADD_BINCOND(next_block) do {    \
745                 MonoInst *cmp;  \
746                 sp -= 2;                \
747                 MONO_INST_NEW(cfg, cmp, OP_COMPARE);    \
748                 cmp->inst_i0 = sp [0];  \
749                 cmp->inst_i1 = sp [1];  \
750                 cmp->cil_code = ins->cil_code;  \
751                 type_from_op (cmp);     \
752                 CHECK_TYPE (cmp);       \
753                 ins->inst_i0 = cmp;     \
754                 MONO_ADD_INS (bblock, ins);     \
755                 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);      \
756                 GET_BBLOCK (cfg, tblock, target);               \
757                 link_bblock (cfg, bblock, tblock);      \
758                 ins->inst_true_bb = tblock;     \
759                 CHECK_BBLOCK (target, ip, tblock);      \
760                 if ((next_block)) {     \
761                         link_bblock (cfg, bblock, (next_block));        \
762                         ins->inst_false_bb = (next_block);      \
763                         start_new_bblock = 1;   \
764                 } else {        \
765                         GET_BBLOCK (cfg, tblock, ip);           \
766                         link_bblock (cfg, bblock, tblock);      \
767                         ins->inst_false_bb = tblock;    \
768                         start_new_bblock = 2;   \
769                 }       \
770         } while (0)
771
772 /* FIXME: handle float, long ... */
773 #define ADD_UNCOND(istrue) do { \
774                 MonoInst *cmp;  \
775                 sp--;           \
776                 MONO_INST_NEW(cfg, cmp, OP_COMPARE);    \
777                 cmp->inst_i0 = sp [0];  \
778                 switch (cmp->inst_i0->type) { \
779                 case STACK_I8: \
780                         cmp->inst_i1 = zero_int64; break; \
781                 case STACK_R8: \
782                         cmp->inst_i1 = zero_r8; break; \
783                 case STACK_PTR: \
784                 case STACK_MP: \
785                         cmp->inst_i1 = zero_ptr; break; \
786                 case STACK_OBJ: \
787                         cmp->inst_i1 = zero_obj; break; \
788                 default: \
789                         cmp->inst_i1 = zero_int32;  \
790                 }  \
791                 cmp->cil_code = ins->cil_code;  \
792                 type_from_op (cmp);     \
793                 CHECK_TYPE (cmp);       \
794                 ins->inst_i0 = cmp;     \
795                 ins->opcode = (istrue)? CEE_BNE_UN: CEE_BEQ;    \
796                 MONO_ADD_INS (bblock, ins);     \
797                 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);      \
798                 GET_BBLOCK (cfg, tblock, target);               \
799                 link_bblock (cfg, bblock, tblock);      \
800                 ins->inst_true_bb = tblock;     \
801                 CHECK_BBLOCK (target, ip, tblock);      \
802                 GET_BBLOCK (cfg, tblock, ip);           \
803                 link_bblock (cfg, bblock, tblock);      \
804                 ins->inst_false_bb = tblock;    \
805                 start_new_bblock = 2;   \
806         } while (0)
807
808 #define NEW_LDELEMA(cfg,dest,sp,k) do { \
809                 MONO_INST_NEW ((cfg), (dest), CEE_LDELEMA);     \
810                 (dest)->inst_left = (sp) [0];   \
811                 (dest)->inst_right = (sp) [1];  \
812                 (dest)->type = STACK_MP;        \
813                 (dest)->klass = (k);    \
814                 (cfg)->flags |= MONO_CFG_HAS_LDELEMA; \
815         } while (0)
816
817 #define NEW_GROUP(cfg,dest,el1,el2) do {        \
818                 MONO_INST_NEW ((cfg), (dest), OP_GROUP);        \
819                 (dest)->inst_left = (el1);      \
820                 (dest)->inst_right = (el2);     \
821         } while (0)
822
823 #if 0
824 static gint
825 compare_bblock (gconstpointer a, gconstpointer b)
826 {
827         const MonoBasicBlock *b1 = a;
828         const MonoBasicBlock *b2 = b;
829
830         return b2->cil_code - b1->cil_code;
831 }
832 #endif
833
834 /* *
835  * link_bblock: Links two basic blocks
836  *
837  * links two basic blocks in the control flow graph, the 'from'
838  * argument is the starting block and the 'to' argument is the block
839  * the control flow ends to after 'from'.
840  */
841 static void
842 link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
843 {
844         MonoBasicBlock **newa;
845         int i, found;
846
847 #if 0
848         if (from->cil_code) {
849                 if (to->cil_code)
850                         g_print ("edge from IL%04x to IL_%04x\n", from->cil_code - cfg->cil_code, to->cil_code - cfg->cil_code);
851                 else
852                         g_print ("edge from IL%04x to exit\n", from->cil_code - cfg->cil_code);
853         } else {
854                 if (to->cil_code)
855                         g_print ("edge from entry to IL_%04x\n", to->cil_code - cfg->cil_code);
856                 else
857                         g_print ("edge from entry to exit\n");
858         }
859 #endif
860         found = FALSE;
861         for (i = 0; i < from->out_count; ++i) {
862                 if (to == from->out_bb [i]) {
863                         found = TRUE;
864                         break;
865                 }
866         }
867         if (!found) {
868                 newa = mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (from->out_count + 1));
869                 for (i = 0; i < from->out_count; ++i) {
870                         newa [i] = from->out_bb [i];
871                 }
872                 newa [i] = to;
873                 from->out_count++;
874                 from->out_bb = newa;
875         }
876
877         found = FALSE;
878         for (i = 0; i < to->in_count; ++i) {
879                 if (from == to->in_bb [i]) {
880                         found = TRUE;
881                         break;
882                 }
883         }
884         if (!found) {
885                 newa = mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (to->in_count + 1));
886                 for (i = 0; i < to->in_count; ++i) {
887                         newa [i] = to->in_bb [i];
888                 }
889                 newa [i] = from;
890                 to->in_count++;
891                 to->in_bb = newa;
892         }
893 }
894
895 /**
896  * mono_unlink_bblock:
897  *
898  *   Unlink two basic blocks.
899  */
900 static void
901 mono_unlink_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
902 {
903         int i, pos;
904         gboolean found;
905
906         found = FALSE;
907         for (i = 0; i < from->out_count; ++i) {
908                 if (to == from->out_bb [i]) {
909                         found = TRUE;
910                         break;
911                 }
912         }
913         if (found) {
914                 pos = 0;
915                 for (i = 0; i < from->out_count; ++i) {
916                         if (from->out_bb [i] != to)
917                                 from->out_bb [pos ++] = from->out_bb [i];
918                 }
919                 g_assert (pos == from->out_count - 1);
920                 from->out_count--;
921         }
922
923         found = FALSE;
924         for (i = 0; i < to->in_count; ++i) {
925                 if (from == to->in_bb [i]) {
926                         found = TRUE;
927                         break;
928                 }
929         }
930         if (found) {
931                 pos = 0;
932                 for (i = 0; i < to->in_count; ++i) {
933                         if (to->in_bb [i] != from)
934                                 to->in_bb [pos ++] = to->in_bb [i];
935                 }
936                 g_assert (pos == to->in_count - 1);
937                 to->in_count--;
938         }
939 }
940
941 /**
942  * mono_find_block_region:
943  *
944  *   We mark each basic block with a region ID. We use that to avoid BB
945  *   optimizations when blocks are in different regions.
946  *
947  * Returns:
948  *   A region token that encodes where this region is, and information
949  *   about the clause owner for this block.
950  *
951  *   The region encodes the try/catch/filter clause that owns this block
952  *   as well as the type.  -1 is a special value that represents a block
953  *   that is in none of try/catch/filter.
954  */
955 static int
956 mono_find_block_region (MonoCompile *cfg, int offset)
957 {
958         MonoMethod *method = cfg->method;
959         MonoMethodHeader *header = mono_method_get_header (method);
960         MonoExceptionClause *clause;
961         int i;
962
963         /* first search for handlers and filters */
964         for (i = 0; i < header->num_clauses; ++i) {
965                 clause = &header->clauses [i];
966                 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->data.filter_offset) &&
967                     (offset < (clause->handler_offset)))
968                         return ((i + 1) << 8) | MONO_REGION_FILTER | clause->flags;
969                            
970                 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
971                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
972                                 return ((i + 1) << 8) | MONO_REGION_FINALLY | clause->flags;
973                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
974                                 return ((i + 1) << 8) | MONO_REGION_FAULT | clause->flags;
975                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
976                                 return ((i + 1) << 8) | MONO_REGION_CATCH | clause->flags;
977                 }
978         }
979
980         /* search the try blocks */
981         for (i = 0; i < header->num_clauses; ++i) {
982                 clause = &header->clauses [i];
983                 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
984                         return ((i + 1) << 8) | clause->flags;
985         }
986
987         return -1;
988 }
989
990 static GList*
991 mono_find_final_block (MonoCompile *cfg, unsigned char *ip, unsigned char *target, int type)
992 {
993         MonoMethod *method = cfg->method;
994         MonoMethodHeader *header = mono_method_get_header (method);
995         MonoExceptionClause *clause;
996         MonoBasicBlock *handler;
997         int i;
998         GList *res = NULL;
999
1000         for (i = 0; i < header->num_clauses; ++i) {
1001                 clause = &header->clauses [i];
1002                 if (MONO_OFFSET_IN_CLAUSE (clause, (ip - header->code)) && 
1003                     (!MONO_OFFSET_IN_CLAUSE (clause, (target - header->code)))) {
1004                         if (clause->flags == type) {
1005                                 handler = cfg->cil_offset_to_bb [clause->handler_offset];
1006                                 g_assert (handler);
1007                                 res = g_list_append (res, handler);
1008                         }
1009                 }
1010         }
1011         return res;
1012 }
1013
1014 MonoInst *
1015 mono_find_spvar_for_region (MonoCompile *cfg, int region)
1016 {
1017         return g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
1018 }
1019
1020 static void
1021 mono_create_spvar_for_region (MonoCompile *cfg, int region)
1022 {
1023         MonoInst *var;
1024
1025         var = g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
1026         if (var)
1027                 return;
1028
1029         var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1030         /* prevent it from being register allocated */
1031         var->flags |= MONO_INST_INDIRECT;
1032
1033         g_hash_table_insert (cfg->spvars, GINT_TO_POINTER (region), var);
1034 }
1035
1036 static MonoInst *
1037 mono_find_exvar_for_offset (MonoCompile *cfg, int offset)
1038 {
1039         return g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
1040 }
1041
1042 static MonoInst*
1043 mono_create_exvar_for_offset (MonoCompile *cfg, int offset)
1044 {
1045         MonoInst *var;
1046
1047         var = g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
1048         if (var)
1049                 return var;
1050
1051         var = mono_compile_create_var (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL);
1052         /* prevent it from being register allocated */
1053         var->flags |= MONO_INST_INDIRECT;
1054
1055         g_hash_table_insert (cfg->exvars, GINT_TO_POINTER (offset), var);
1056
1057         return var;
1058 }
1059
1060 static void
1061 df_visit (MonoBasicBlock *start, int *dfn, MonoBasicBlock **array)
1062 {
1063         int i;
1064
1065         array [*dfn] = start;
1066         /*g_print ("visit %d at %p (BB%ld)\n", *dfn, start->cil_code, start->block_num);*/
1067         for (i = 0; i < start->out_count; ++i) {
1068                 if (start->out_bb [i]->dfn)
1069                         continue;
1070                 (*dfn)++;
1071                 start->out_bb [i]->dfn = *dfn;
1072                 start->out_bb [i]->df_parent = start;
1073                 array [*dfn] = start->out_bb [i];
1074                 df_visit (start->out_bb [i], dfn, array);
1075         }
1076 }
1077
1078 static MonoBasicBlock*
1079 find_previous (MonoBasicBlock **bblocks, guint32 n_bblocks, MonoBasicBlock *start, const guchar *code)
1080 {
1081         MonoBasicBlock *best = start;
1082         int i;
1083
1084         for (i = 0; i < n_bblocks; ++i) {
1085                 if (bblocks [i]) {
1086                         MonoBasicBlock *bb = bblocks [i];
1087
1088                         if (bb->cil_code && bb->cil_code < code && bb->cil_code > best->cil_code)
1089                                 best = bb;
1090                 }
1091         }
1092
1093         return best;
1094 }
1095
1096 static void
1097 split_bblock (MonoCompile *cfg, MonoBasicBlock *first, MonoBasicBlock *second) {
1098         int i, j;
1099         MonoInst *inst;
1100         MonoBasicBlock *bb;
1101
1102         if (!MONO_INST_LIST_EMPTY (&second->ins_list))
1103                 return;
1104         
1105         /* 
1106          * FIXME: take into account all the details:
1107          * second may have been the target of more than one bblock
1108          */
1109         second->out_count = first->out_count;
1110         second->out_bb = first->out_bb;
1111
1112         for (i = 0; i < first->out_count; ++i) {
1113                 bb = first->out_bb [i];
1114                 for (j = 0; j < bb->in_count; ++j) {
1115                         if (bb->in_bb [j] == first)
1116                                 bb->in_bb [j] = second;
1117                 }
1118         }
1119
1120         first->out_count = 0;
1121         first->out_bb = NULL;
1122         link_bblock (cfg, first, second);
1123
1124         /*g_print ("start search at %p for %p\n", first->cil_code, second->cil_code);*/
1125         MONO_BB_FOR_EACH_INS (first, inst) {
1126                 MonoInst *inst_next;
1127
1128                 /*char *code = mono_disasm_code_one (NULL, cfg->method, inst->next->cil_code, NULL);
1129                 g_print ("found %p: %s", inst->next->cil_code, code);
1130                 g_free (code);*/
1131                 if (inst->cil_code >= second->cil_code)
1132                         continue;
1133
1134                 inst_next = mono_inst_list_next (&inst->node, &first->ins_list);
1135                 if (!inst_next)
1136                         break;
1137
1138                 if (inst_next->cil_code < second->cil_code)
1139                         continue;
1140                         
1141                 second->ins_list.next = inst->node.next;
1142                 second->ins_list.prev = first->ins_list.prev;
1143                 inst->node.next = &first->ins_list;
1144                 first->ins_list.prev = &inst->node;
1145
1146                 second->next_bb = first->next_bb;
1147                 first->next_bb = second;
1148                 return;
1149         }
1150         if (MONO_INST_LIST_EMPTY (&second->ins_list)) {
1151                 g_warning ("bblock split failed in %s::%s\n", cfg->method->klass->name, cfg->method->name);
1152                 //G_BREAKPOINT ();
1153         }
1154 }
1155
1156 static guint32
1157 reverse_branch_op (guint32 opcode)
1158 {
1159         static const int reverse_map [] = {
1160                 CEE_BNE_UN, CEE_BLT, CEE_BLE, CEE_BGT, CEE_BGE,
1161                 CEE_BEQ, CEE_BLT_UN, CEE_BLE_UN, CEE_BGT_UN, CEE_BGE_UN
1162         };
1163         static const int reverse_fmap [] = {
1164                 OP_FBNE_UN, OP_FBLT, OP_FBLE, OP_FBGT, OP_FBGE,
1165                 OP_FBEQ, OP_FBLT_UN, OP_FBLE_UN, OP_FBGT_UN, OP_FBGE_UN
1166         };
1167         static const int reverse_lmap [] = {
1168                 OP_LBNE_UN, OP_LBLT, OP_LBLE, OP_LBGT, OP_LBGE,
1169                 OP_LBEQ, OP_LBLT_UN, OP_LBLE_UN, OP_LBGT_UN, OP_LBGE_UN
1170         };
1171         static const int reverse_imap [] = {
1172                 OP_IBNE_UN, OP_IBLT, OP_IBLE, OP_IBGT, OP_IBGE,
1173                 OP_IBEQ, OP_IBLT_UN, OP_IBLE_UN, OP_IBGT_UN, OP_IBGE_UN
1174         };
1175                                 
1176         if (opcode >= CEE_BEQ && opcode <= CEE_BLT_UN) {
1177                 opcode = reverse_map [opcode - CEE_BEQ];
1178         } else if (opcode >= OP_FBEQ && opcode <= OP_FBLT_UN) {
1179                 opcode = reverse_fmap [opcode - OP_FBEQ];
1180         } else if (opcode >= OP_LBEQ && opcode <= OP_LBLT_UN) {
1181                 opcode = reverse_lmap [opcode - OP_LBEQ];
1182         } else if (opcode >= OP_IBEQ && opcode <= OP_IBLT_UN) {
1183                 opcode = reverse_imap [opcode - OP_IBEQ];
1184         } else
1185                 g_assert_not_reached ();
1186
1187         return opcode;
1188 }
1189
1190 #ifdef MONO_ARCH_SOFT_FLOAT
1191 static int
1192 condbr_to_fp_br (int opcode)
1193 {
1194         switch (opcode) {
1195         case CEE_BEQ: return OP_FBEQ;
1196         case CEE_BGE: return OP_FBGE;
1197         case CEE_BGT: return OP_FBGT;
1198         case CEE_BLE: return OP_FBLE;
1199         case CEE_BLT: return OP_FBLT;
1200         case CEE_BNE_UN: return OP_FBNE_UN;
1201         case CEE_BGE_UN: return OP_FBGE_UN;
1202         case CEE_BGT_UN: return OP_FBGT_UN;
1203         case CEE_BLE_UN: return OP_FBLE_UN;
1204         case CEE_BLT_UN: return OP_FBLT_UN;
1205         }
1206         g_assert_not_reached ();
1207         return 0;
1208 }
1209 #endif
1210
1211 /*
1212  * Returns the type used in the eval stack when @type is loaded.
1213  * FIXME: return a MonoType/MonoClass for the byref and VALUETYPE cases.
1214  */
1215 static void
1216 type_to_eval_stack_type (MonoCompile *cfg, MonoType *type, MonoInst *inst)
1217 {
1218         MonoClass *klass;
1219
1220         inst->klass = klass = mono_class_from_mono_type (type);
1221         if (type->byref) {
1222                 inst->type = STACK_MP;
1223                 return;
1224         }
1225
1226 handle_enum:
1227         switch (type->type) {
1228         case MONO_TYPE_VOID:
1229                 inst->type = STACK_INV;
1230                 return;
1231         case MONO_TYPE_I1:
1232         case MONO_TYPE_U1:
1233         case MONO_TYPE_BOOLEAN:
1234         case MONO_TYPE_I2:
1235         case MONO_TYPE_U2:
1236         case MONO_TYPE_CHAR:
1237         case MONO_TYPE_I4:
1238         case MONO_TYPE_U4:
1239                 inst->type = STACK_I4;
1240                 return;
1241         case MONO_TYPE_I:
1242         case MONO_TYPE_U:
1243         case MONO_TYPE_PTR:
1244         case MONO_TYPE_FNPTR:
1245                 inst->type = STACK_PTR;
1246                 return;
1247         case MONO_TYPE_CLASS:
1248         case MONO_TYPE_STRING:
1249         case MONO_TYPE_OBJECT:
1250         case MONO_TYPE_SZARRAY:
1251         case MONO_TYPE_ARRAY:    
1252                 inst->type = STACK_OBJ;
1253                 return;
1254         case MONO_TYPE_I8:
1255         case MONO_TYPE_U8:
1256                 inst->type = STACK_I8;
1257                 return;
1258         case MONO_TYPE_R4:
1259         case MONO_TYPE_R8:
1260                 inst->type = STACK_R8;
1261                 return;
1262         case MONO_TYPE_VALUETYPE:
1263                 if (type->data.klass->enumtype) {
1264                         type = type->data.klass->enum_basetype;
1265                         goto handle_enum;
1266                 } else {
1267                         inst->klass = klass;
1268                         inst->type = STACK_VTYPE;
1269                         return;
1270                 }
1271         case MONO_TYPE_TYPEDBYREF:
1272                 inst->klass = mono_defaults.typed_reference_class;
1273                 inst->type = STACK_VTYPE;
1274                 return;
1275         case MONO_TYPE_GENERICINST:
1276                 type = &type->data.generic_class->container_class->byval_arg;
1277                 goto handle_enum;
1278         case MONO_TYPE_VAR :
1279         case MONO_TYPE_MVAR :
1280                 /* FIXME: all the arguments must be references for now,
1281                  * later look inside cfg and see if the arg num is
1282                  * really a reference
1283                  */
1284                 g_assert (cfg->generic_sharing_context);
1285                 inst->type = STACK_OBJ;
1286                 return;
1287         default:
1288                 g_error ("unknown type 0x%02x in eval stack type", type->type);
1289         }
1290 }
1291
1292 /*
1293  * The following tables are used to quickly validate the IL code in type_from_op ().
1294  */
1295 static const char
1296 bin_num_table [STACK_MAX] [STACK_MAX] = {
1297         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1298         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
1299         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1300         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
1301         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_R8,  STACK_INV, STACK_INV, STACK_INV},
1302         {STACK_INV, STACK_MP,  STACK_INV, STACK_MP,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV},
1303         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1304         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1305 };
1306
1307 static const char 
1308 neg_table [] = {
1309         STACK_INV, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_INV, STACK_INV, STACK_INV
1310 };
1311
1312 /* reduce the size of this table */
1313 static const char
1314 bin_int_table [STACK_MAX] [STACK_MAX] = {
1315         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1316         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1317         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1318         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1319         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1320         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1321         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1322         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1323 };
1324
1325 static const char
1326 bin_comp_table [STACK_MAX] [STACK_MAX] = {
1327 /*      Inv i  L  p  F  &  O  vt */
1328         {0},
1329         {0, 1, 0, 1, 0, 0, 0, 0}, /* i, int32 */
1330         {0, 0, 1, 0, 0, 0, 0, 0}, /* L, int64 */
1331         {0, 1, 0, 1, 0, 2, 4, 0}, /* p, ptr */
1332         {0, 0, 0, 0, 1, 0, 0, 0}, /* F, R8 */
1333         {0, 0, 0, 2, 0, 1, 0, 0}, /* &, managed pointer */
1334         {0, 0, 0, 4, 0, 0, 3, 0}, /* O, reference */
1335         {0, 0, 0, 0, 0, 0, 0, 0}, /* vt value type */
1336 };
1337
1338 /* reduce the size of this table */
1339 static const char
1340 shift_table [STACK_MAX] [STACK_MAX] = {
1341         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1342         {STACK_INV, STACK_I4,  STACK_INV, STACK_I4,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1343         {STACK_INV, STACK_I8,  STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1344         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1345         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1346         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1347         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1348         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1349 };
1350
1351 /*
1352  * Tables to map from the non-specific opcode to the matching
1353  * type-specific opcode.
1354  */
1355 /* handles from CEE_ADD to CEE_SHR_UN (CEE_REM_UN for floats) */
1356 static const guint16
1357 binops_op_map [STACK_MAX] = {
1358         0, 0, OP_LADD-CEE_ADD, OP_PADD-CEE_ADD, OP_FADD-CEE_ADD, OP_PADD-CEE_ADD
1359 };
1360
1361 /* handles from CEE_NEG to CEE_CONV_U8 */
1362 static const guint16
1363 unops_op_map [STACK_MAX] = {
1364         0, 0, OP_LNEG-CEE_NEG, OP_PNEG-CEE_NEG, OP_FNEG-CEE_NEG, OP_PNEG-CEE_NEG
1365 };
1366
1367 /* handles from CEE_CONV_U2 to CEE_SUB_OVF_UN */
1368 static const guint16
1369 ovfops_op_map [STACK_MAX] = {
1370         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
1371 };
1372
1373 /* handles from CEE_CONV_OVF_I1_UN to CEE_CONV_OVF_U_UN */
1374 static const guint16
1375 ovf2ops_op_map [STACK_MAX] = {
1376         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
1377 };
1378
1379 /* handles from CEE_CONV_OVF_I1 to CEE_CONV_OVF_U8 */
1380 static const guint16
1381 ovf3ops_op_map [STACK_MAX] = {
1382         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
1383 };
1384
1385 /* handles from CEE_CEQ to CEE_CLT_UN */
1386 static const guint16
1387 ceqops_op_map [STACK_MAX] = {
1388         0, 0, OP_LCEQ-OP_CEQ, OP_PCEQ-OP_CEQ, OP_FCEQ-OP_CEQ, OP_LCEQ-OP_CEQ
1389 };
1390
1391 /*
1392  * Sets ins->type (the type on the eval stack) according to the
1393  * type of the opcode and the arguments to it.
1394  * Invalid IL code is marked by setting ins->type to the invalid value STACK_INV.
1395  *
1396  * FIXME: this function sets ins->type unconditionally in some cases, but
1397  * it should set it to invalid for some types (a conv.x on an object)
1398  */
1399 static void
1400 type_from_op (MonoInst *ins) {
1401         switch (ins->opcode) {
1402         /* binops */
1403         case CEE_ADD:
1404         case CEE_SUB:
1405         case CEE_MUL:
1406         case CEE_DIV:
1407         case CEE_REM:
1408                 /* FIXME: check unverifiable args for STACK_MP */
1409                 ins->type = bin_num_table [ins->inst_i0->type] [ins->inst_i1->type];
1410                 ins->opcode += binops_op_map [ins->type];
1411                 return;
1412         case CEE_DIV_UN:
1413         case CEE_REM_UN:
1414         case CEE_AND:
1415         case CEE_OR:
1416         case CEE_XOR:
1417                 ins->type = bin_int_table [ins->inst_i0->type] [ins->inst_i1->type];
1418                 ins->opcode += binops_op_map [ins->type];
1419                 return;
1420         case CEE_SHL:
1421         case CEE_SHR:
1422         case CEE_SHR_UN:
1423                 ins->type = shift_table [ins->inst_i0->type] [ins->inst_i1->type];
1424                 ins->opcode += binops_op_map [ins->type];
1425                 return;
1426         case OP_COMPARE:
1427         case OP_LCOMPARE:
1428                 /* FIXME: handle some specifics with ins->next->type */
1429                 ins->type = bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] ? STACK_I4: STACK_INV;
1430                 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))))
1431                         ins->opcode = OP_LCOMPARE;
1432                 return;
1433         case OP_CEQ:
1434                 ins->type = bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] ? STACK_I4: STACK_INV;
1435                 ins->opcode += ceqops_op_map [ins->inst_i0->type];
1436                 return;
1437                 
1438         case OP_CGT:
1439         case OP_CGT_UN:
1440         case OP_CLT:
1441         case OP_CLT_UN:
1442                 ins->type = (bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] & 1) ? STACK_I4: STACK_INV;
1443                 ins->opcode += ceqops_op_map [ins->inst_i0->type];
1444                 return;
1445         /* unops */
1446         case CEE_NEG:
1447                 ins->type = neg_table [ins->inst_i0->type];
1448                 ins->opcode += unops_op_map [ins->type];
1449                 return;
1450         case CEE_NOT:
1451                 if (ins->inst_i0->type >= STACK_I4 && ins->inst_i0->type <= STACK_PTR)
1452                         ins->type = ins->inst_i0->type;
1453                 else
1454                         ins->type = STACK_INV;
1455                 ins->opcode += unops_op_map [ins->type];
1456                 return;
1457         case CEE_CONV_I1:
1458         case CEE_CONV_I2:
1459         case CEE_CONV_I4:
1460         case CEE_CONV_U4:
1461                 ins->type = STACK_I4;
1462                 ins->opcode += unops_op_map [ins->inst_i0->type];
1463                 return;
1464         case CEE_CONV_R_UN:
1465                 ins->type = STACK_R8;
1466                 switch (ins->inst_i0->type) {
1467                 case STACK_I4:
1468                 case STACK_PTR:
1469                         break;
1470                 case STACK_I8:
1471                         ins->opcode = OP_LCONV_TO_R_UN; 
1472                         break;
1473                 }
1474                 return;
1475         case CEE_CONV_OVF_I1:
1476         case CEE_CONV_OVF_U1:
1477         case CEE_CONV_OVF_I2:
1478         case CEE_CONV_OVF_U2:
1479         case CEE_CONV_OVF_I4:
1480         case CEE_CONV_OVF_U4:
1481                 ins->type = STACK_I4;
1482                 ins->opcode += ovf3ops_op_map [ins->inst_i0->type];
1483                 return;
1484         case CEE_CONV_OVF_I_UN:
1485         case CEE_CONV_OVF_U_UN:
1486                 ins->type = STACK_PTR;
1487                 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1488                 return;
1489         case CEE_CONV_OVF_I1_UN:
1490         case CEE_CONV_OVF_I2_UN:
1491         case CEE_CONV_OVF_I4_UN:
1492         case CEE_CONV_OVF_U1_UN:
1493         case CEE_CONV_OVF_U2_UN:
1494         case CEE_CONV_OVF_U4_UN:
1495                 ins->type = STACK_I4;
1496                 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1497                 return;
1498         case CEE_CONV_U:
1499                 ins->type = STACK_PTR;
1500                 switch (ins->inst_i0->type) {
1501                 case STACK_I4:
1502                         break;
1503                 case STACK_PTR:
1504                 case STACK_MP:
1505 #if SIZEOF_VOID_P == 8
1506                         ins->opcode = OP_LCONV_TO_U;
1507 #endif
1508                         break;
1509                 case STACK_I8:
1510                         ins->opcode = OP_LCONV_TO_U;
1511                         break;
1512                 case STACK_R8:
1513                         ins->opcode = OP_FCONV_TO_U;
1514                         break;
1515                 }
1516                 return;
1517         case CEE_CONV_I8:
1518         case CEE_CONV_U8:
1519                 ins->type = STACK_I8;
1520                 ins->opcode += unops_op_map [ins->inst_i0->type];
1521                 return;
1522         case CEE_CONV_OVF_I8:
1523         case CEE_CONV_OVF_U8:
1524                 ins->type = STACK_I8;
1525                 ins->opcode += ovf3ops_op_map [ins->inst_i0->type];
1526                 return;
1527         case CEE_CONV_OVF_U8_UN:
1528         case CEE_CONV_OVF_I8_UN:
1529                 ins->type = STACK_I8;
1530                 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1531                 return;
1532         case CEE_CONV_R4:
1533         case CEE_CONV_R8:
1534                 ins->type = STACK_R8;
1535                 ins->opcode += unops_op_map [ins->inst_i0->type];
1536                 return;
1537         case OP_CKFINITE:
1538                 ins->type = STACK_R8;           
1539                 return;
1540         case CEE_CONV_U2:
1541         case CEE_CONV_U1:
1542                 ins->type = STACK_I4;
1543                 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1544                 break;
1545         case CEE_CONV_I:
1546         case CEE_CONV_OVF_I:
1547         case CEE_CONV_OVF_U:
1548                 ins->type = STACK_PTR;
1549                 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1550                 return;
1551         case CEE_ADD_OVF:
1552         case CEE_ADD_OVF_UN:
1553         case CEE_MUL_OVF:
1554         case CEE_MUL_OVF_UN:
1555         case CEE_SUB_OVF:
1556         case CEE_SUB_OVF_UN:
1557                 ins->type = bin_num_table [ins->inst_i0->type] [ins->inst_i1->type];
1558                 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1559                 if (ins->type == STACK_R8)
1560                         ins->type = STACK_INV;
1561                 return;
1562         default:
1563                 g_error ("opcode 0x%04x not handled in type from op", ins->opcode);
1564                 break;
1565         }
1566 }
1567
1568 static const char 
1569 ldind_type [] = {
1570         STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_R8, STACK_OBJ
1571 };
1572
1573 /* map ldelem.x to the matching ldind.x opcode */
1574 static const guchar
1575 ldelem_to_ldind [] = {
1576         CEE_LDIND_I1,
1577         CEE_LDIND_U1,
1578         CEE_LDIND_I2,
1579         CEE_LDIND_U2,
1580         CEE_LDIND_I4,
1581         CEE_LDIND_U4,
1582         CEE_LDIND_I8,
1583         CEE_LDIND_I,
1584         CEE_LDIND_R4,
1585         CEE_LDIND_R8,
1586         CEE_LDIND_REF
1587 };
1588
1589 /* map stelem.x to the matching stind.x opcode */
1590 static const guchar
1591 stelem_to_stind [] = {
1592         CEE_STIND_I,
1593         CEE_STIND_I1,
1594         CEE_STIND_I2,
1595         CEE_STIND_I4,
1596         CEE_STIND_I8,
1597         CEE_STIND_R4,
1598         CEE_STIND_R8,
1599         CEE_STIND_REF
1600 };
1601
1602 #if 0
1603
1604 static const char
1605 param_table [STACK_MAX] [STACK_MAX] = {
1606         {0},
1607 };
1608
1609 static int
1610 check_values_to_signature (MonoInst *args, MonoType *this, MonoMethodSignature *sig)
1611 {
1612         int i;
1613
1614         if (sig->hasthis) {
1615                 switch (args->type) {
1616                 case STACK_I4:
1617                 case STACK_I8:
1618                 case STACK_R8:
1619                 case STACK_VTYPE:
1620                 case STACK_INV:
1621                         return 0;
1622                 }
1623                 args++;
1624         }
1625         for (i = 0; i < sig->param_count; ++i) {
1626                 switch (args [i].type) {
1627                 case STACK_INV:
1628                         return 0;
1629                 case STACK_MP:
1630                         if (!sig->params [i]->byref)
1631                                 return 0;
1632                         continue;
1633                 case STACK_OBJ:
1634                         if (sig->params [i]->byref)
1635                                 return 0;
1636                         switch (sig->params [i]->type) {
1637                         case MONO_TYPE_CLASS:
1638                         case MONO_TYPE_STRING:
1639                         case MONO_TYPE_OBJECT:
1640                         case MONO_TYPE_SZARRAY:
1641                         case MONO_TYPE_ARRAY:
1642                                 break;
1643                         default:
1644                                 return 0;
1645                         }
1646                         continue;
1647                 case STACK_R8:
1648                         if (sig->params [i]->byref)
1649                                 return 0;
1650                         if (sig->params [i]->type != MONO_TYPE_R4 && sig->params [i]->type != MONO_TYPE_R8)
1651                                 return 0;
1652                         continue;
1653                 case STACK_PTR:
1654                 case STACK_I4:
1655                 case STACK_I8:
1656                 case STACK_VTYPE:
1657                         break;
1658                 }
1659                 /*if (!param_table [args [i].type] [sig->params [i]->type])
1660                         return 0;*/
1661         }
1662         return 1;
1663 }
1664 #endif
1665
1666 static guint
1667 mini_type_to_ldind (MonoCompile* cfg, MonoType *type)
1668 {
1669         if (cfg->generic_sharing_context && !type->byref) {
1670                 /* FIXME: all the arguments must be references for now,
1671                  * later look inside cfg and see if the arg num is
1672                  * really a reference
1673                  */
1674                 if (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)
1675                         return CEE_LDIND_REF;
1676         }
1677         return mono_type_to_ldind (type);
1678 }
1679
1680 static guint
1681 mini_type_to_stind (MonoCompile* cfg, MonoType *type)
1682 {
1683         if (cfg->generic_sharing_context && !type->byref) {
1684                 /* FIXME: all the arguments must be references for now,
1685                  * later look inside cfg and see if the arg num is
1686                  * really a reference
1687                  */
1688                 if (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)
1689                         return CEE_STIND_REF;
1690         }
1691         return mono_type_to_stind (type);
1692 }
1693
1694 int
1695 mono_op_imm_to_op (int opcode)
1696 {
1697         switch (opcode) {
1698         case OP_ADD_IMM:
1699                 return OP_PADD;
1700         case OP_IADD_IMM:
1701                 return OP_IADD;
1702         case OP_LADD_IMM:
1703                 return OP_LADD;
1704         case OP_ISUB_IMM:
1705                 return OP_ISUB;
1706         case OP_LSUB_IMM:
1707                 return OP_LSUB;
1708         case OP_AND_IMM:
1709 #if SIZEOF_VOID_P == 4
1710                 return OP_IAND;
1711 #else
1712                 return OP_LAND;
1713 #endif
1714         case OP_IAND_IMM:
1715                 return OP_IAND;
1716         case OP_LAND_IMM:
1717                 return OP_LAND;
1718         case OP_IOR_IMM:
1719                 return OP_IOR;
1720         case OP_LOR_IMM:
1721                 return OP_LOR;
1722         case OP_IXOR_IMM:
1723                 return OP_IXOR;
1724         case OP_LXOR_IMM:
1725                 return OP_LXOR;
1726         case OP_ISHL_IMM:
1727                 return OP_ISHL;
1728         case OP_LSHL_IMM:
1729                 return OP_LSHL;
1730         case OP_ISHR_IMM:
1731                 return OP_ISHR;
1732         case OP_LSHR_IMM:
1733                 return OP_LSHR;
1734         case OP_ISHR_UN_IMM:
1735                 return OP_ISHR_UN;
1736         case OP_LSHR_UN_IMM:
1737                 return OP_LSHR_UN;
1738         case OP_IDIV_IMM:
1739                 return OP_IDIV;
1740         case OP_IDIV_UN_IMM:
1741                 return OP_IDIV_UN;
1742         case OP_IREM_UN_IMM:
1743                 return OP_IREM_UN;
1744         case OP_IREM_IMM:
1745                 return OP_IREM;
1746         case OP_DIV_IMM:
1747 #if SIZEOF_VOID_P == 4
1748                 return OP_IDIV;
1749 #else
1750                 return OP_LDIV;
1751 #endif
1752         case OP_REM_IMM:
1753 #if SIZEOF_VOID_P == 4
1754                 return OP_IREM;
1755 #else
1756                 return OP_LREM;
1757 #endif
1758         case OP_ADDCC_IMM:
1759                 return OP_ADDCC;
1760         case OP_ADC_IMM:
1761                 return OP_ADC;
1762         case OP_SUBCC_IMM:
1763                 return OP_SUBCC;
1764         case OP_SBB_IMM:
1765                 return OP_SBB;
1766         case OP_IADC_IMM:
1767                 return OP_IADC;
1768         case OP_ISBB_IMM:
1769                 return OP_ISBB;
1770         case OP_COMPARE_IMM:
1771                 return OP_COMPARE;
1772         case OP_ICOMPARE_IMM:
1773                 return OP_ICOMPARE;
1774         default:
1775                 printf ("%s\n", mono_inst_name (opcode));
1776                 g_assert_not_reached ();
1777         }
1778 }
1779
1780 /*
1781  * mono_decompose_op_imm:
1782  *
1783  *   Replace the OP_.._IMM INS with its non IMM variant.
1784  */
1785 void
1786 mono_decompose_op_imm (MonoCompile *cfg, MonoInst *ins)
1787 {
1788         MonoInst *temp;
1789
1790         MONO_INST_NEW (cfg, temp, OP_ICONST);
1791         temp->inst_c0 = ins->inst_imm;
1792         temp->dreg = mono_regstate_next_int (cfg->rs);
1793         MONO_INST_LIST_ADD_TAIL (&(temp)->node, &(ins)->node);
1794         ins->opcode = mono_op_imm_to_op (ins->opcode);
1795         ins->sreg2 = temp->dreg;
1796 }
1797
1798 /*
1799  * When we need a pointer to the current domain many times in a method, we
1800  * call mono_domain_get() once and we store the result in a local variable.
1801  * This function returns the variable that represents the MonoDomain*.
1802  */
1803 inline static MonoInst *
1804 mono_get_domainvar (MonoCompile *cfg)
1805 {
1806         if (!cfg->domainvar)
1807                 cfg->domainvar = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1808         return cfg->domainvar;
1809 }
1810
1811 /*
1812  * The got_var contains the address of the Global Offset Table when AOT 
1813  * compiling.
1814  */
1815 inline static MonoInst *
1816 mono_get_got_var (MonoCompile *cfg)
1817 {
1818 #ifdef MONO_ARCH_NEED_GOT_VAR
1819         if (!cfg->compile_aot)
1820                 return NULL;
1821         if (!cfg->got_var) {
1822                 cfg->got_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1823         }
1824         return cfg->got_var;
1825 #else
1826         return NULL;
1827 #endif
1828 }
1829
1830 static MonoInst *
1831 mono_get_vtable_var (MonoCompile *cfg)
1832 {
1833         g_assert (cfg->generic_sharing_context);
1834
1835         if (!cfg->rgctx_var) {
1836                 cfg->rgctx_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1837                 /* force the var to be stack allocated */
1838                 cfg->rgctx_var->flags |= MONO_INST_INDIRECT;
1839         }
1840
1841         return cfg->rgctx_var;
1842 }
1843
1844 MonoInst*
1845 mono_compile_create_var (MonoCompile *cfg, MonoType *type, int opcode)
1846 {
1847         MonoInst *inst;
1848         int num = cfg->num_varinfo;
1849
1850         if ((num + 1) >= cfg->varinfo_count) {
1851                 int orig_count = cfg->varinfo_count;
1852                 cfg->varinfo_count = (cfg->varinfo_count + 2) * 2;
1853                 cfg->varinfo = (MonoInst **)g_realloc (cfg->varinfo, sizeof (MonoInst*) * cfg->varinfo_count);
1854                 cfg->vars = (MonoMethodVar *)g_realloc (cfg->vars, sizeof (MonoMethodVar) * cfg->varinfo_count);
1855                 memset (&cfg->vars [orig_count], 0, (cfg->varinfo_count - orig_count) * sizeof (MonoMethodVar));
1856         }
1857
1858         /*g_print ("created temp %d of type 0x%x\n", num, type->type);*/
1859         mono_jit_stats.allocate_var++;
1860
1861         MONO_INST_NEW (cfg, inst, opcode);
1862         inst->inst_c0 = num;
1863         inst->inst_vtype = type;
1864         inst->klass = mono_class_from_mono_type (type);
1865         /* if set to 1 the variable is native */
1866         inst->backend.is_pinvoke = 0;
1867
1868         cfg->varinfo [num] = inst;
1869
1870         MONO_INIT_VARINFO (&cfg->vars [num], num);
1871
1872         cfg->num_varinfo++;
1873         if (cfg->verbose_level > 2)
1874                 g_print ("created temp %d of type %s\n", num, mono_type_get_name (type));
1875         return inst;
1876 }
1877
1878 /*
1879  * Transform a MonoInst into a load from the variable of index var_index.
1880  */
1881 void
1882 mono_compile_make_var_load (MonoCompile *cfg, MonoInst *dest, gssize var_index) {
1883         memset (dest, 0, sizeof (MonoInst));
1884         dest->ssa_op = MONO_SSA_LOAD;
1885         dest->inst_i0 = cfg->varinfo [var_index];
1886         dest->opcode = mini_type_to_ldind (cfg, dest->inst_i0->inst_vtype);
1887         type_to_eval_stack_type (cfg, dest->inst_i0->inst_vtype, dest);
1888         dest->klass = dest->inst_i0->klass;
1889 }
1890
1891 /*
1892  * Create a MonoInst that is a load from the variable of index var_index.
1893  */
1894 MonoInst*
1895 mono_compile_create_var_load (MonoCompile *cfg, gssize var_index) {
1896         MonoInst *dest;
1897         NEW_TEMPLOAD (cfg,dest,var_index);
1898         return dest;
1899 }
1900
1901 /*
1902  * Create a MonoInst that is a store of the given value into the variable of index var_index.
1903  */
1904 MonoInst*
1905 mono_compile_create_var_store (MonoCompile *cfg, gssize var_index, MonoInst *value) {
1906         MonoInst *dest;
1907         NEW_TEMPSTORE (cfg, dest, var_index, value);
1908         return dest;
1909 }
1910
1911 static MonoType*
1912 type_from_stack_type (MonoInst *ins) {
1913         switch (ins->type) {
1914         case STACK_I4: return &mono_defaults.int32_class->byval_arg;
1915         case STACK_I8: return &mono_defaults.int64_class->byval_arg;
1916         case STACK_PTR: return &mono_defaults.int_class->byval_arg;
1917         case STACK_R8: return &mono_defaults.double_class->byval_arg;
1918         case STACK_MP:
1919                 /* 
1920                  * this if used to be commented without any specific reason, but
1921                  * it breaks #80235 when commented
1922                  */
1923                 if (ins->klass)
1924                         return &ins->klass->this_arg;
1925                 else
1926                         return &mono_defaults.object_class->this_arg;
1927         case STACK_OBJ:
1928                 /* ins->klass may not be set for ldnull.
1929                  * Also, if we have a boxed valuetype, we want an object lass,
1930                  * not the valuetype class
1931                  */
1932                 if (ins->klass && !ins->klass->valuetype)
1933                         return &ins->klass->byval_arg;
1934                 return &mono_defaults.object_class->byval_arg;
1935         case STACK_VTYPE: return &ins->klass->byval_arg;
1936         default:
1937                 g_error ("stack type %d to montype not handled\n", ins->type);
1938         }
1939         return NULL;
1940 }
1941
1942 MonoType*
1943 mono_type_from_stack_type (MonoInst *ins) {
1944         return type_from_stack_type (ins);
1945 }
1946
1947 static MonoClass*
1948 array_access_to_klass (int opcode, MonoInst *array_obj)
1949 {
1950         switch (opcode) {
1951         case CEE_LDELEM_U1:
1952                 return mono_defaults.byte_class;
1953         case CEE_LDELEM_U2:
1954                 return mono_defaults.uint16_class;
1955         case CEE_LDELEM_I:
1956         case CEE_STELEM_I:
1957                 return mono_defaults.int_class;
1958         case CEE_LDELEM_I1:
1959         case CEE_STELEM_I1:
1960                 return mono_defaults.sbyte_class;
1961         case CEE_LDELEM_I2:
1962         case CEE_STELEM_I2:
1963                 return mono_defaults.int16_class;
1964         case CEE_LDELEM_I4:
1965         case CEE_STELEM_I4:
1966                 return mono_defaults.int32_class;
1967         case CEE_LDELEM_U4:
1968                 return mono_defaults.uint32_class;
1969         case CEE_LDELEM_I8:
1970         case CEE_STELEM_I8:
1971                 return mono_defaults.int64_class;
1972         case CEE_LDELEM_R4:
1973         case CEE_STELEM_R4:
1974                 return mono_defaults.single_class;
1975         case CEE_LDELEM_R8:
1976         case CEE_STELEM_R8:
1977                 return mono_defaults.double_class;
1978         case CEE_LDELEM_REF:
1979         case CEE_STELEM_REF: {
1980                 MonoClass *klass = array_obj->klass;
1981                 /* FIXME: add assert */
1982                 if (klass && klass->rank)
1983                         return klass->element_class;
1984                 return mono_defaults.object_class;
1985         }
1986         default:
1987                 g_assert_not_reached ();
1988         }
1989         return NULL;
1990 }
1991
1992 void
1993 mono_add_ins_to_end (MonoBasicBlock *bb, MonoInst *inst)
1994 {
1995         MonoInst *last = mono_inst_list_last (&bb->ins_list);
1996
1997         if (last && ((last->opcode >= CEE_BEQ &&
1998                         last->opcode <= CEE_BLT_UN) ||
1999                         last->opcode == OP_BR ||
2000                         last->opcode == OP_SWITCH)) {
2001                 MONO_INST_LIST_ADD_TAIL (&inst->node, &last->node);
2002         } else {
2003                 MONO_ADD_INS (bb, inst);
2004         }
2005 }
2006
2007 void
2008 mono_add_varcopy_to_end (MonoCompile *cfg, MonoBasicBlock *bb, int src, int dest)
2009 {
2010         MonoInst *inst, *load;
2011
2012         NEW_TEMPLOAD (cfg, load, src);
2013
2014         NEW_TEMPSTORE (cfg, inst, dest, load);
2015         /* FIXME: handle CEE_STIND_R4 */
2016         if (inst->opcode == CEE_STOBJ) {
2017                 NEW_TEMPLOADA (cfg, inst, dest);
2018                 handle_stobj (cfg, bb, inst, load, NULL, inst->klass, TRUE, FALSE, FALSE);
2019         } else {
2020                 inst->cil_code = NULL;
2021                 mono_add_ins_to_end (bb, inst);
2022         }
2023 }
2024
2025 /*
2026  * This function is called to handle items that are left on the evaluation stack
2027  * at basic block boundaries. What happens is that we save the values to local variables
2028  * and we reload them later when first entering the target basic block (with the
2029  * handle_loaded_temps () function).
2030  * It is also used to handle items on the stack in store opcodes, since it is
2031  * possible that the variable to be stored into is already on the stack, in
2032  * which case its old value should be used.
2033  * A single joint point will use the same variables (stored in the array bb->out_stack or
2034  * bb->in_stack, if the basic block is before or after the joint point).
2035  * If the stack merge fails at a join point, cfg->unverifiable is set.
2036  */
2037 static void
2038 handle_stack_args (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst **sp, int count)
2039 {
2040         int i, bindex;
2041         MonoBasicBlock *outb;
2042         MonoInst *inst, **locals;
2043         gboolean found;
2044
2045         if (!count)
2046                 return;
2047         if (cfg->verbose_level > 3)
2048                 g_print ("%d item(s) on exit from B%d\n", count, bb->block_num);
2049
2050         if (!bb->out_scount) {
2051                 bb->out_scount = count;
2052                 //g_print ("bblock %d has out:", bb->block_num);
2053                 found = FALSE;
2054                 for (i = 0; i < bb->out_count; ++i) {
2055                         outb = bb->out_bb [i];
2056                         /* exception handlers are linked, but they should not be considered for stack args */
2057                         if (outb->flags & BB_EXCEPTION_HANDLER)
2058                                 continue;
2059                         //g_print (" %d", outb->block_num);
2060                         if (outb->in_stack) {
2061                                 found = TRUE;
2062                                 bb->out_stack = outb->in_stack;
2063                                 break;
2064                         }
2065                 }
2066                 //g_print ("\n");
2067                 if (!found) {
2068                         bb->out_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * count);
2069                         for (i = 0; i < count; ++i) {
2070                                 /* 
2071                                  * try to reuse temps already allocated for this purpouse, if they occupy the same
2072                                  * stack slot and if they are of the same type.
2073                                  * This won't cause conflicts since if 'local' is used to 
2074                                  * store one of the values in the in_stack of a bblock, then
2075                                  * the same variable will be used for the same outgoing stack 
2076                                  * slot as well. 
2077                                  * This doesn't work when inlining methods, since the bblocks
2078                                  * in the inlined methods do not inherit their in_stack from
2079                                  * the bblock they are inlined to. See bug #58863 for an
2080                                  * example.
2081                                  * This hack is disabled since it also prevents proper tracking of types.
2082                                  */
2083 #if 1
2084                                 bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
2085 #else
2086                                 if (cfg->inlined_method)
2087                                         bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
2088                                 else
2089                                         bb->out_stack [i] = mono_compile_get_interface_var (cfg, i, sp [i]);
2090 #endif
2091                         }
2092                 }
2093         }
2094
2095         for (i = 0; i < bb->out_count; ++i) {
2096                 outb = bb->out_bb [i];
2097                 /* exception handlers are linked, but they should not be considered for stack args */
2098                 if (outb->flags & BB_EXCEPTION_HANDLER)
2099                         continue;
2100                 if (outb->in_scount) {
2101                         if (outb->in_scount != bb->out_scount) {
2102                                 cfg->unverifiable = TRUE;
2103                                 return;
2104                         }
2105                         continue; /* check they are the same locals */
2106                 }
2107                 outb->in_scount = count;
2108                 outb->in_stack = bb->out_stack;
2109         }
2110
2111         locals = bb->out_stack;
2112         for (i = 0; i < count; ++i) {
2113                 /* add store ops at the end of the bb, before the branch */
2114                 NEW_TEMPSTORE (cfg, inst, locals [i]->inst_c0, sp [i]);
2115                 if (inst->opcode == CEE_STOBJ) {
2116                         NEW_TEMPLOADA (cfg, inst, locals [i]->inst_c0);
2117                         handle_stobj (cfg, bb, inst, sp [i], sp [i]->cil_code, inst->klass, TRUE, FALSE, FALSE);
2118                 } else {
2119                         inst->cil_code = sp [i]->cil_code;
2120                         mono_add_ins_to_end (bb, inst);
2121                 }
2122                 if (cfg->verbose_level > 3)
2123                         g_print ("storing %d to temp %d\n", i, (int)locals [i]->inst_c0);
2124         }
2125
2126         /*
2127          * It is possible that the out bblocks already have in_stack assigned, and
2128          * the in_stacks differ. In this case, we will store to all the different 
2129          * in_stacks.
2130          */
2131
2132         found = TRUE;
2133         bindex = 0;
2134         while (found) {
2135                 /* Find a bblock which has a different in_stack */
2136                 found = FALSE;
2137                 while (bindex < bb->out_count) {
2138                         outb = bb->out_bb [bindex];
2139                         /* exception handlers are linked, but they should not be considered for stack args */
2140                         if (outb->flags & BB_EXCEPTION_HANDLER) {
2141                                 bindex++;
2142                                 continue;
2143                         }
2144                         if (outb->in_stack != locals) {
2145                                 /* 
2146                                  * Instead of storing sp [i] to locals [i], we need to store
2147                                  * locals [i] to <new locals>[i], since the sp [i] tree can't
2148                                  * be shared between trees.
2149                                  */
2150                                 for (i = 0; i < count; ++i)
2151                                         mono_add_varcopy_to_end (cfg, bb, locals [i]->inst_c0, outb->in_stack [i]->inst_c0);
2152                                 locals = outb->in_stack;
2153                                 found = TRUE;
2154                                 break;
2155                         }
2156                         bindex ++;
2157                 }
2158         }
2159 }
2160
2161 static int
2162 ret_type_to_call_opcode (MonoType *type, int calli, int virt, MonoGenericSharingContext *gsctx)
2163 {
2164         if (type->byref)
2165                 return calli? OP_CALL_REG: virt? OP_CALLVIRT: OP_CALL;
2166
2167 handle_enum:
2168         type = mini_get_basic_type_from_generic (gsctx, type);
2169         switch (type->type) {
2170         case MONO_TYPE_VOID:
2171                 return calli? OP_VOIDCALL_REG: virt? OP_VOIDCALLVIRT: OP_VOIDCALL;
2172         case MONO_TYPE_I1:
2173         case MONO_TYPE_U1:
2174         case MONO_TYPE_BOOLEAN:
2175         case MONO_TYPE_I2:
2176         case MONO_TYPE_U2:
2177         case MONO_TYPE_CHAR:
2178         case MONO_TYPE_I4:
2179         case MONO_TYPE_U4:
2180                 return calli? OP_CALL_REG: virt? OP_CALLVIRT: OP_CALL;
2181         case MONO_TYPE_I:
2182         case MONO_TYPE_U:
2183         case MONO_TYPE_PTR:
2184         case MONO_TYPE_FNPTR:
2185                 return calli? OP_CALL_REG: virt? OP_CALLVIRT: OP_CALL;
2186         case MONO_TYPE_CLASS:
2187         case MONO_TYPE_STRING:
2188         case MONO_TYPE_OBJECT:
2189         case MONO_TYPE_SZARRAY:
2190         case MONO_TYPE_ARRAY:    
2191                 return calli? OP_CALL_REG: virt? OP_CALLVIRT: OP_CALL;
2192         case MONO_TYPE_I8:
2193         case MONO_TYPE_U8:
2194                 return calli? OP_LCALL_REG: virt? OP_LCALLVIRT: OP_LCALL;
2195         case MONO_TYPE_R4:
2196         case MONO_TYPE_R8:
2197                 return calli? OP_FCALL_REG: virt? OP_FCALLVIRT: OP_FCALL;
2198         case MONO_TYPE_VALUETYPE:
2199                 if (type->data.klass->enumtype) {
2200                         type = type->data.klass->enum_basetype;
2201                         goto handle_enum;
2202                 } else
2203                         return calli? OP_VCALL_REG: virt? OP_VCALLVIRT: OP_VCALL;
2204         case MONO_TYPE_TYPEDBYREF:
2205                 return calli? OP_VCALL_REG: virt? OP_VCALLVIRT: OP_VCALL;
2206         case MONO_TYPE_GENERICINST:
2207                 type = &type->data.generic_class->container_class->byval_arg;
2208                 goto handle_enum;
2209         default:
2210                 g_error ("unknown type 0x%02x in ret_type_to_call_opcode", type->type);
2211         }
2212         return -1;
2213 }
2214
2215 void
2216 mono_create_jump_table (MonoCompile *cfg, MonoInst *label, MonoBasicBlock **bbs, int num_blocks)
2217 {
2218         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
2219         MonoJumpInfoBBTable *table;
2220
2221         table = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfoBBTable));
2222         table->table = bbs;
2223         table->table_size = num_blocks;
2224         
2225         ji->ip.label = label;
2226         ji->type = MONO_PATCH_INFO_SWITCH;
2227         ji->data.table = table;
2228         ji->next = cfg->patch_info;
2229         cfg->patch_info = ji;
2230 }
2231
2232 static void
2233 mono_save_token_info (MonoCompile *cfg, MonoImage *image, guint32 token, gpointer key)
2234 {
2235         if (cfg->compile_aot) {
2236                 MonoJumpInfoToken *jump_info_token = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoToken));
2237                 jump_info_token->image = image;
2238                 jump_info_token->token = token;
2239                 g_hash_table_insert (cfg->token_info_hash, key, jump_info_token);
2240         }
2241 }
2242
2243 /*
2244  * When we add a tree of instructions, we need to ensure the instructions currently
2245  * on the stack are executed before (like, if we load a value from a local).
2246  * We ensure this by saving the currently loaded values to temps and rewriting the
2247  * instructions to load the values.
2248  * This is not done for opcodes that terminate a basic block (because it's handled already
2249  * by handle_stack_args ()) and for opcodes that can't change values, like POP.
2250  */
2251 static void
2252 handle_loaded_temps (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst **stack, MonoInst **sp)
2253 {
2254         MonoInst *load, *store, *temp, *ins;
2255
2256         while (stack < sp) {
2257                 ins = *stack;
2258                 /* handle also other constants */
2259                 if ((ins->opcode != OP_ICONST) &&
2260                     /* temps never get written to again, so we can safely avoid duplicating them */
2261                     !(ins->ssa_op == MONO_SSA_LOAD && ins->inst_i0->opcode == OP_LOCAL && ins->inst_i0->flags & MONO_INST_IS_TEMP)) {
2262                         temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
2263                         temp->flags |= MONO_INST_IS_TEMP;
2264                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2265                         store->cil_code = ins->cil_code;
2266                         if (store->opcode == CEE_STOBJ) {
2267                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
2268                                 handle_stobj (cfg, bblock, store, ins, ins->cil_code, temp->klass, FALSE, FALSE, FALSE);
2269                         } else
2270                                 MONO_ADD_INS (bblock, store);
2271                         NEW_TEMPLOAD (cfg, load, temp->inst_c0);
2272                         load->cil_code = ins->cil_code;
2273                         *stack = load;
2274                 }
2275                 stack++;
2276         }
2277 }
2278
2279 /*
2280  * target_type_is_incompatible:
2281  * @cfg: MonoCompile context
2282  *
2283  * Check that the item @arg on the evaluation stack can be stored
2284  * in the target type (can be a local, or field, etc).
2285  * The cfg arg can be used to check if we need verification or just
2286  * validity checks.
2287  *
2288  * Returns: non-0 value if arg can't be stored on a target.
2289  */
2290 static int
2291 target_type_is_incompatible (MonoCompile *cfg, MonoType *target, MonoInst *arg)
2292 {
2293         MonoType *simple_type;
2294         MonoClass *klass;
2295
2296         if (target->byref) {
2297                 /* FIXME: check that the pointed to types match */
2298                 if (arg->type == STACK_MP)
2299                         return arg->klass != mono_class_from_mono_type (target);
2300                 if (arg->type == STACK_PTR)
2301                         return 0;
2302                 return 1;
2303         }
2304         simple_type = mono_type_get_underlying_type (target);
2305         switch (simple_type->type) {
2306         case MONO_TYPE_VOID:
2307                 return 1;
2308         case MONO_TYPE_I1:
2309         case MONO_TYPE_U1:
2310         case MONO_TYPE_BOOLEAN:
2311         case MONO_TYPE_I2:
2312         case MONO_TYPE_U2:
2313         case MONO_TYPE_CHAR:
2314         case MONO_TYPE_I4:
2315         case MONO_TYPE_U4:
2316                 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
2317                         return 1;
2318                 return 0;
2319         case MONO_TYPE_PTR:
2320                 /* STACK_MP is needed when setting pinned locals */
2321                 if (arg->type != STACK_I4 && arg->type != STACK_PTR && arg->type != STACK_MP)
2322                         return 1;
2323                 return 0;
2324         case MONO_TYPE_I:
2325         case MONO_TYPE_U:
2326         case MONO_TYPE_FNPTR:
2327                 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
2328                         return 1;
2329                 return 0;
2330         case MONO_TYPE_OBJECT:
2331                 if (arg->type != STACK_OBJ)
2332                         return 1;
2333                 return 0;
2334         case MONO_TYPE_STRING:
2335                 if (arg->type != STACK_OBJ)
2336                         return 1;
2337                 /* ldnull has arg->klass unset */
2338                 /*if (arg->klass && arg->klass != mono_defaults.string_class) {
2339                         G_BREAKPOINT ();
2340                         return 1;
2341                 }*/
2342                 return 0;
2343         case MONO_TYPE_CLASS:
2344         case MONO_TYPE_SZARRAY:
2345         case MONO_TYPE_ARRAY:    
2346                 if (arg->type != STACK_OBJ)
2347                         return 1;
2348                 /* FIXME: check type compatibility */
2349                 return 0;
2350         case MONO_TYPE_I8:
2351         case MONO_TYPE_U8:
2352                 if (arg->type != STACK_I8)
2353                         return 1;
2354                 return 0;
2355         case MONO_TYPE_R4:
2356         case MONO_TYPE_R8:
2357                 if (arg->type != STACK_R8)
2358                         return 1;
2359                 return 0;
2360         case MONO_TYPE_VALUETYPE:
2361                 if (arg->type != STACK_VTYPE)
2362                         return 1;
2363                 klass = mono_class_from_mono_type (simple_type);
2364                 if (klass != arg->klass)
2365                         return 1;
2366                 return 0;
2367         case MONO_TYPE_TYPEDBYREF:
2368                 if (arg->type != STACK_VTYPE)
2369                         return 1;
2370                 klass = mono_class_from_mono_type (simple_type);
2371                 if (klass != arg->klass)
2372                         return 1;
2373                 return 0;
2374         case MONO_TYPE_GENERICINST:
2375                 if (mono_type_generic_inst_is_valuetype (simple_type)) {
2376                         klass = mono_class_from_mono_type (simple_type);
2377                         if (klass->enumtype)
2378                                 return target_type_is_incompatible (cfg, klass->enum_basetype, arg);
2379                         if (arg->type != STACK_VTYPE)
2380                                 return 1;
2381                         if (klass != arg->klass)
2382                                 return 1;
2383                         return 0;
2384                 } else {
2385                         if (arg->type != STACK_OBJ)
2386                                 return 1;
2387                         /* FIXME: check type compatibility */
2388                         return 0;
2389                 }
2390         case MONO_TYPE_VAR:
2391         case MONO_TYPE_MVAR:
2392                 /* FIXME: all the arguments must be references for now,
2393                  * later look inside cfg and see if the arg num is
2394                  * really a reference
2395                  */
2396                 g_assert (cfg->generic_sharing_context);
2397                 if (arg->type != STACK_OBJ)
2398                         return 1;
2399                 return 0;
2400         default:
2401                 g_error ("unknown type 0x%02x in target_type_is_incompatible", simple_type->type);
2402         }
2403         return 1;
2404 }
2405
2406 /*
2407  * Prepare arguments for passing to a function call.
2408  * Return a non-zero value if the arguments can't be passed to the given
2409  * signature.
2410  * The type checks are not yet complete and some conversions may need
2411  * casts on 32 or 64 bit architectures.
2412  *
2413  * FIXME: implement this using target_type_is_incompatible ()
2414  */
2415 static int
2416 check_call_signature (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args)
2417 {
2418         MonoType *simple_type;
2419         int i;
2420
2421         if (sig->hasthis) {
2422                 if (args [0]->type != STACK_OBJ && args [0]->type != STACK_MP && args [0]->type != STACK_PTR)
2423                         return 1;
2424                 args++;
2425         }
2426         for (i = 0; i < sig->param_count; ++i) {
2427                 if (sig->params [i]->byref) {
2428                         if (args [i]->type != STACK_MP && args [i]->type != STACK_PTR)
2429                                 return 1;
2430                         continue;
2431                 }
2432                 simple_type = sig->params [i];
2433                 simple_type = mini_get_basic_type_from_generic (cfg->generic_sharing_context, simple_type);
2434 handle_enum:
2435                 switch (simple_type->type) {
2436                 case MONO_TYPE_VOID:
2437                         return 1;
2438                         continue;
2439                 case MONO_TYPE_I1:
2440                 case MONO_TYPE_U1:
2441                 case MONO_TYPE_BOOLEAN:
2442                 case MONO_TYPE_I2:
2443                 case MONO_TYPE_U2:
2444                 case MONO_TYPE_CHAR:
2445                 case MONO_TYPE_I4:
2446                 case MONO_TYPE_U4:
2447                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR)
2448                                 return 1;
2449                         continue;
2450                 case MONO_TYPE_I:
2451                 case MONO_TYPE_U:
2452                 case MONO_TYPE_PTR:
2453                 case MONO_TYPE_FNPTR:
2454                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR && args [i]->type != STACK_MP && args [i]->type != STACK_OBJ)
2455                                 return 1;
2456                         continue;
2457                 case MONO_TYPE_CLASS:
2458                 case MONO_TYPE_STRING:
2459                 case MONO_TYPE_OBJECT:
2460                 case MONO_TYPE_SZARRAY:
2461                 case MONO_TYPE_ARRAY:    
2462                         if (args [i]->type != STACK_OBJ)
2463                                 return 1;
2464                         continue;
2465                 case MONO_TYPE_I8:
2466                 case MONO_TYPE_U8:
2467                         if (args [i]->type != STACK_I8)
2468                                 return 1;
2469                         continue;
2470                 case MONO_TYPE_R4:
2471                 case MONO_TYPE_R8:
2472                         if (args [i]->type != STACK_R8)
2473                                 return 1;
2474                         continue;
2475                 case MONO_TYPE_VALUETYPE:
2476                         if (simple_type->data.klass->enumtype) {
2477                                 simple_type = simple_type->data.klass->enum_basetype;
2478                                 goto handle_enum;
2479                         }
2480                         if (args [i]->type != STACK_VTYPE)
2481                                 return 1;
2482                         continue;
2483                 case MONO_TYPE_TYPEDBYREF:
2484                         if (args [i]->type != STACK_VTYPE)
2485                                 return 1;
2486                         continue;
2487                 case MONO_TYPE_GENERICINST:
2488                         simple_type = &simple_type->data.generic_class->container_class->byval_arg;
2489                         goto handle_enum;
2490
2491                 default:
2492                         g_error ("unknown type 0x%02x in check_call_signature",
2493                                  simple_type->type);
2494                 }
2495         }
2496         return 0;
2497 }
2498
2499 inline static int
2500 mono_spill_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoCallInst *call, MonoMethodSignature *sig, gboolean ret_object, 
2501                  const guint8 *ip, gboolean to_end)
2502 {
2503         MonoInst *temp, *store, *ins = (MonoInst*)call;
2504         MonoType *ret = sig->ret;
2505
2506         if (!MONO_TYPE_IS_VOID (ret) || ret_object) {
2507                 if (ret_object) {
2508                         call->inst.type = STACK_OBJ;
2509                         call->inst.opcode = OP_CALL;
2510                         temp = mono_compile_create_var (cfg, &mono_defaults.string_class->byval_arg, OP_LOCAL);
2511                 } else {
2512                         type_to_eval_stack_type (cfg, ret, ins);
2513                         temp = mono_compile_create_var (cfg, ret, OP_LOCAL);
2514                 }
2515                 
2516                 temp->flags |= MONO_INST_IS_TEMP;
2517
2518                 if (MONO_TYPE_ISSTRUCT (ret)) {
2519                         MonoInst *loada, *dummy_store;
2520
2521                         /* 
2522                          * Emit a dummy store to the local holding the result so the
2523                          * liveness info remains correct.
2524                          */
2525                         NEW_DUMMY_STORE (cfg, dummy_store, temp->inst_c0);
2526                         if (to_end)
2527                                 mono_add_ins_to_end (bblock, dummy_store);
2528                         else
2529                                 MONO_ADD_INS (bblock, dummy_store);
2530
2531                         /* we use this to allocate native sized structs */
2532                         temp->backend.is_pinvoke = sig->pinvoke;
2533
2534                         NEW_TEMPLOADA (cfg, loada, temp->inst_c0);
2535                         if (call->inst.opcode == OP_VCALL || call->inst.opcode == OP_VCALL_RGCTX)
2536                                 ins->inst_left = loada;
2537                         else
2538                                 ins->inst_right = loada; /* a virtual or indirect call */
2539
2540                         if (to_end)
2541                                 mono_add_ins_to_end (bblock, ins);
2542                         else
2543                                 MONO_ADD_INS (bblock, ins);
2544                 } else {
2545                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2546                         store->cil_code = ip;
2547                         
2548 #ifdef MONO_ARCH_SOFT_FLOAT
2549                         if (store->opcode == CEE_STIND_R4) {
2550                                 /*FIXME implement proper support for to_end*/
2551                                 g_assert (!to_end);
2552                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
2553                                 handle_store_float (cfg, bblock, store, ins, ip);
2554                         } else
2555 #endif
2556                         if (to_end)
2557                                 mono_add_ins_to_end (bblock, store);
2558                         else
2559                                 MONO_ADD_INS (bblock, store);
2560                 }
2561                 return temp->inst_c0;
2562         } else {
2563                 if (to_end)
2564                         mono_add_ins_to_end (bblock, ins);
2565                 else
2566                         MONO_ADD_INS (bblock, ins);
2567                 return -1;
2568         }
2569 }
2570
2571 inline static MonoCallInst *
2572 mono_emit_call_args (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, 
2573                      MonoInst **args, int calli, int virtual, const guint8 *ip, gboolean to_end)
2574 {
2575         MonoCallInst *call;
2576         MonoInst *arg, *n;
2577
2578         MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (sig->ret, calli, virtual, cfg->generic_sharing_context));
2579
2580 #ifdef MONO_ARCH_SOFT_FLOAT
2581         /* we need to convert the r4 value to an int value */
2582         {
2583                 int i;
2584                 for (i = 0; i < sig->param_count; ++i) {
2585                         if (!sig->params [i]->byref && sig->params [i]->type == MONO_TYPE_R4) {
2586                                 MonoInst *iargs [1];
2587                                 int temp;
2588                                 iargs [0] = args [i + sig->hasthis];
2589
2590                                 temp = mono_emit_jit_icall (cfg, bblock, mono_fload_r4_arg, iargs, ip);
2591                                 NEW_TEMPLOAD (cfg, arg, temp);
2592                                 args [i + sig->hasthis] = arg;
2593                         }
2594                 }
2595         }
2596 #endif
2597
2598         call->inst.cil_code = ip;
2599         call->args = args;
2600         call->signature = sig;
2601         call = mono_arch_call_opcode (cfg, bblock, call, virtual);
2602         type_to_eval_stack_type (cfg, sig->ret, &call->inst);
2603
2604         MONO_INST_LIST_FOR_EACH_ENTRY_SAFE (arg, n, &call->out_args, node) {
2605                 if (!arg->cil_code)
2606                         arg->cil_code = ip;
2607                 if (to_end)
2608                         mono_add_ins_to_end (bblock, arg);
2609                 else
2610                         MONO_ADD_INS (bblock, arg);
2611         }
2612         return call;
2613 }
2614
2615 inline static MonoCallInst*
2616 mono_emit_calli (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, 
2617                  MonoInst **args, MonoInst *addr, const guint8 *ip)
2618 {
2619         MonoCallInst *call = mono_emit_call_args (cfg, bblock, sig, args, TRUE, FALSE, ip, FALSE);
2620
2621         call->inst.inst_i0 = addr;
2622
2623         return call;
2624 }
2625
2626 inline static MonoCallInst*
2627 mono_emit_rgctx_calli (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig,
2628         MonoInst **args, MonoInst *addr, MonoInst *rgctx_arg, const guint8 *ip)
2629 {
2630         MonoCallInst *call = mono_emit_calli (cfg, bblock, sig, args, addr, ip);
2631
2632         if (rgctx_arg) {
2633                 switch (call->inst.opcode) {
2634                 case OP_CALL_REG: call->inst.opcode = OP_CALL_REG_RGCTX; break;
2635                 case OP_VOIDCALL_REG: call->inst.opcode = OP_VOIDCALL_REG_RGCTX; break;
2636                 case OP_FCALL_REG: call->inst.opcode = OP_FCALL_REG_RGCTX; break;
2637                 case OP_LCALL_REG: call->inst.opcode = OP_LCALL_REG_RGCTX; break;
2638                 case OP_VCALL_REG: {
2639                         MonoInst *group;
2640
2641                         NEW_GROUP (cfg, group, call->inst.inst_left, NULL);
2642                         call->inst.inst_left = group;
2643                         call->inst.opcode = OP_VCALL_REG_RGCTX;
2644                         break;
2645                 }
2646                 default: g_assert_not_reached ();
2647                 }
2648
2649                 if (call->inst.opcode != OP_VCALL_REG_RGCTX) {
2650                         g_assert (!call->inst.inst_right);
2651                         call->inst.inst_right = rgctx_arg;
2652                 } else {
2653                         g_assert (!call->inst.inst_left->inst_right);
2654                         call->inst.inst_left->inst_right = rgctx_arg;
2655                 }
2656         }
2657
2658         return call;
2659 }
2660
2661 inline static int
2662 mono_emit_calli_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, 
2663                                                  MonoInst **args, MonoInst *addr, const guint8 *ip)
2664 {
2665         MonoCallInst *call = mono_emit_calli (cfg, bblock, sig, args, addr, ip);
2666
2667         return mono_spill_call (cfg, bblock, call, sig, FALSE, ip, FALSE);
2668 }
2669
2670 static int
2671 mono_emit_rgctx_calli_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig,
2672         MonoInst **args, MonoInst *addr, MonoInst *rgctx_arg, const guint8 *ip)
2673 {
2674         MonoCallInst *call = mono_emit_rgctx_calli (cfg, bblock, sig, args, addr, rgctx_arg, ip);
2675
2676         return mono_spill_call (cfg, bblock, call, sig, FALSE, ip, FALSE);
2677 }
2678
2679 static MonoCallInst*
2680 mono_emit_method_call_full (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method, MonoMethodSignature *sig,
2681                        MonoInst **args, const guint8 *ip, MonoInst *this, gboolean to_end)
2682 {
2683         gboolean virtual = this != NULL;
2684         MonoCallInst *call;
2685
2686         call = mono_emit_call_args (cfg, bblock, sig, args, FALSE, virtual, ip, to_end);
2687
2688         if (this && sig->hasthis && 
2689             (method->klass->marshalbyref || method->klass == mono_defaults.object_class) && 
2690             !(method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !MONO_CHECK_THIS (this)) {
2691                 call->method = mono_marshal_get_remoting_invoke_with_check (method);
2692         } else {
2693                 call->method = method;
2694         }
2695         call->inst.flags |= MONO_INST_HAS_METHOD;
2696         call->inst.inst_left = this;
2697
2698         if (call->method->klass->flags & TYPE_ATTRIBUTE_INTERFACE)
2699                 /* Needed by the code generated in inssel.brg */
2700                 mono_get_got_var (cfg);
2701
2702         return call;
2703 }
2704
2705 static MonoCallInst*
2706 mono_emit_method_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method, MonoMethodSignature *sig,
2707                        MonoInst **args, const guint8 *ip, MonoInst *this)
2708 {
2709         return mono_emit_method_call_full (cfg, bblock, method, sig, args, ip, this, FALSE);
2710 }
2711
2712 inline static int
2713 mono_emit_method_call_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,  
2714                        MonoMethodSignature *signature, MonoInst **args, const guint8 *ip, MonoInst *this)
2715 {
2716         MonoCallInst *call = mono_emit_method_call (cfg, bblock, method, signature, args, ip, this);
2717
2718         return mono_spill_call (cfg, bblock, call, signature, method->string_ctor, ip, FALSE);
2719 }
2720
2721 inline static int
2722 mono_emit_method_call_spilled_full (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,  
2723                        MonoMethodSignature *signature, MonoInst **args, const guint8 *ip, MonoInst *this,
2724                        gboolean ret_object, gboolean to_end)
2725 {
2726         MonoCallInst *call = mono_emit_method_call_full (cfg, bblock, method, signature, args, ip, this, to_end);
2727
2728         return mono_spill_call (cfg, bblock, call, signature, ret_object, ip, to_end);
2729 }
2730
2731 inline static int
2732 mono_emit_native_call (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoMethodSignature *sig,
2733                        MonoInst **args, const guint8 *ip, gboolean ret_object, gboolean to_end)
2734 {
2735         MonoCallInst *call;
2736
2737         g_assert (sig);
2738
2739         call = mono_emit_call_args (cfg, bblock, sig, args, FALSE, FALSE, ip, to_end);
2740         call->fptr = func;
2741
2742         return mono_spill_call (cfg, bblock, call, sig, ret_object, ip, to_end);
2743 }
2744
2745 inline static int
2746 mono_emit_jit_icall (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoInst **args, const guint8 *ip)
2747 {
2748         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (func);
2749         
2750         if (!info) {
2751                 g_warning ("unregistered JIT ICall");
2752                 g_assert_not_reached ();
2753         }
2754
2755         return mono_emit_native_call (cfg, bblock, mono_icall_get_wrapper (info), info->sig, args, ip, FALSE, FALSE);
2756 }
2757
2758 static MonoCallInst*
2759 mono_emit_rgctx_method_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method, MonoMethodSignature *sig,
2760                 MonoInst **args, MonoInst *rgctx_arg, MonoInst *imt_arg, const guint8 *ip, MonoInst *this)
2761 {
2762         MonoCallInst *call = mono_emit_method_call_full (cfg, bblock, method, sig, args, ip, this, FALSE);
2763
2764         g_assert (!(rgctx_arg && imt_arg));
2765
2766         if (rgctx_arg) {
2767                 switch (call->inst.opcode) {
2768                 case OP_CALL: call->inst.opcode = OP_CALL_RGCTX; break;
2769                 case OP_VOIDCALL: call->inst.opcode = OP_VOIDCALL_RGCTX; break;
2770                 case OP_FCALL: call->inst.opcode = OP_FCALL_RGCTX; break;
2771                 case OP_LCALL: call->inst.opcode = OP_LCALL_RGCTX; break;
2772                 case OP_VCALL: call->inst.opcode = OP_VCALL_RGCTX; break;
2773                 default: g_assert_not_reached ();
2774                 }
2775
2776                 if (call->inst.opcode != OP_VCALL_RGCTX) {
2777                         g_assert (!call->inst.inst_left);
2778                         call->inst.inst_left = rgctx_arg;
2779                 } else {
2780                         g_assert (!call->inst.inst_right);
2781                         call->inst.inst_right = rgctx_arg;
2782                 }
2783         } else if (imt_arg) {
2784                 switch (call->inst.opcode) {
2785                 case OP_CALLVIRT: call->inst.opcode = OP_CALLVIRT_IMT; break;
2786                 case OP_VOIDCALLVIRT: call->inst.opcode = OP_VOIDCALLVIRT_IMT; break;
2787                 case OP_FCALLVIRT: call->inst.opcode = OP_FCALLVIRT_IMT; break;
2788                 case OP_LCALLVIRT: call->inst.opcode = OP_LCALLVIRT_IMT; break;
2789                 case OP_VCALLVIRT: {
2790                         MonoInst *group;
2791
2792                         NEW_GROUP (cfg, group, call->inst.inst_left, NULL);
2793                         call->inst.inst_left = group;
2794                         call->inst.opcode = OP_VCALLVIRT_IMT;
2795                         break;
2796                 }
2797                 default: g_assert_not_reached ();
2798                 }
2799
2800                 if (call->inst.opcode != OP_VCALLVIRT_IMT) {
2801                         g_assert (!call->inst.inst_right);
2802                         call->inst.inst_right = imt_arg;
2803                 } else {
2804                         g_assert (!call->inst.inst_left->inst_right);
2805                         call->inst.inst_left->inst_right = imt_arg;
2806                 }
2807         }
2808
2809         return call;
2810 }
2811
2812 inline static int
2813 mono_emit_rgctx_method_call_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,  
2814                 MonoMethodSignature *signature, MonoInst **args, MonoInst *rgctx_arg, MonoInst *imt_arg,
2815                 const guint8 *ip, MonoInst *this)
2816 {
2817         MonoCallInst *call = mono_emit_rgctx_method_call (cfg, bblock, method, signature, args, rgctx_arg, imt_arg, ip, this);
2818
2819         return mono_spill_call (cfg, bblock, call, signature, method->string_ctor, ip, FALSE);
2820 }
2821
2822 static void
2823 mono_emulate_opcode (MonoCompile *cfg, MonoInst *tree, MonoInst **iargs, MonoJitICallInfo *info)
2824 {
2825         MonoInst *ins, *temp = NULL, *store, *load;
2826         MonoInstList *head, *list;
2827         int nargs;
2828         MonoCallInst *call;
2829
2830         //g_print ("emulating: ");
2831         //mono_print_tree_nl (tree);
2832         MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (info->sig->ret, FALSE, FALSE, cfg->generic_sharing_context));
2833         ins = (MonoInst*)call;
2834         MONO_INST_LIST_INIT (&ins->node);
2835         
2836         call->inst.cil_code = tree->cil_code;
2837         call->args = iargs;
2838         call->signature = info->sig;
2839
2840         call = mono_arch_call_opcode (cfg, cfg->cbb, call, FALSE);
2841
2842         if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
2843                 temp = mono_compile_create_var (cfg, info->sig->ret, OP_LOCAL);
2844                 temp->flags |= MONO_INST_IS_TEMP;
2845                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2846                 MONO_INST_LIST_INIT (&store->node);
2847                 /* FIXME: handle CEE_STIND_R4 */
2848                 store->cil_code = tree->cil_code;
2849         } else {
2850                 store = ins;
2851         }
2852
2853         nargs = info->sig->param_count + info->sig->hasthis;
2854
2855         if (nargs) {
2856                 MONO_INST_LIST_ADD_TAIL (&store->node,
2857                                         &call->out_args);
2858                 list = &call->out_args;
2859         } else {
2860                 list = &store->node;
2861         }
2862
2863         if (cfg->prev_ins) {
2864                 /* 
2865                  * This assumes that that in a tree, emulate_opcode is called for a
2866                  * node before it is called for its children. dec_foreach needs to
2867                  * take this into account.
2868                  */
2869                 head = &cfg->prev_ins->node;
2870         } else {
2871                 head = &cfg->cbb->ins_list;
2872         }
2873
2874         MONO_INST_LIST_SPLICE_INIT (list, head);
2875
2876         call->fptr = mono_icall_get_wrapper (info);
2877
2878         if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
2879                 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
2880                 *tree = *load;
2881         }
2882 }
2883
2884 /*
2885  * This entry point could be used later for arbitrary method
2886  * redirection.
2887  */
2888 inline static int
2889 mini_redirect_call (int *temp, MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,  
2890                        MonoMethodSignature *signature, MonoInst **args, const guint8 *ip, MonoInst *this)
2891 {
2892
2893         if (method->klass == mono_defaults.string_class) {
2894                 /* managed string allocation support */
2895                 if (strcmp (method->name, "InternalAllocateStr") == 0) {
2896                         MonoInst *iargs [2];
2897                         MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
2898                         MonoMethod *managed_alloc = mono_gc_get_managed_allocator (vtable, FALSE);
2899                         if (!managed_alloc)
2900                                 return FALSE;
2901                         NEW_VTABLECONST (cfg, iargs [0], vtable);
2902                         iargs [1] = args [0];
2903                         *temp = mono_emit_method_call_spilled (cfg, bblock, managed_alloc, mono_method_signature (managed_alloc), iargs, ip, this);
2904                         return TRUE;
2905                 }
2906         }
2907         return FALSE;
2908 }
2909
2910 static MonoMethodSignature *
2911 mono_get_array_new_va_signature (int arity)
2912 {
2913         static GHashTable *sighash = NULL;
2914         MonoMethodSignature *res;
2915         int i;
2916
2917         mono_jit_lock ();
2918         if (!sighash) {
2919                 sighash = g_hash_table_new (NULL, NULL);
2920         }
2921         else if ((res = g_hash_table_lookup (sighash, GINT_TO_POINTER (arity)))) {
2922                 mono_jit_unlock ();
2923                 return res;
2924         }
2925
2926         res = mono_metadata_signature_alloc (mono_defaults.corlib, arity + 1);
2927
2928         res->pinvoke = 1;
2929 #ifdef MONO_ARCH_VARARG_ICALLS
2930         /* Only set this only some archs since not all backends can handle varargs+pinvoke */
2931         res->call_convention = MONO_CALL_VARARG;
2932 #endif
2933
2934 #ifdef PLATFORM_WIN32
2935         res->call_convention = MONO_CALL_C;
2936 #endif
2937
2938         res->params [0] = &mono_defaults.int_class->byval_arg;  
2939         for (i = 0; i < arity; i++)
2940                 res->params [i + 1] = &mono_defaults.int_class->byval_arg;
2941
2942         res->ret = &mono_defaults.int_class->byval_arg;
2943
2944         g_hash_table_insert (sighash, GINT_TO_POINTER (arity), res);
2945         mono_jit_unlock ();
2946
2947         return res;
2948 }
2949
2950 #ifdef MONO_ARCH_SOFT_FLOAT
2951 static void
2952 handle_store_float (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ptr, MonoInst *val, const unsigned char *ip)
2953 {
2954         MonoInst *iargs [2];
2955         iargs [0] = val;
2956         iargs [1] = ptr;
2957
2958         mono_emit_jit_icall (cfg, bblock, mono_fstore_r4, iargs, ip);
2959 }
2960
2961 static int
2962 handle_load_float (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ptr, const unsigned char *ip)
2963 {
2964         MonoInst *iargs [1];
2965         iargs [0] = ptr;
2966
2967         return mono_emit_jit_icall (cfg, bblock, mono_fload_r4, iargs, ip);
2968 }
2969
2970 #define LDLOC_SOFT_FLOAT(cfg,ins,idx,ip) do {\
2971                 if (header->locals [(idx)]->type == MONO_TYPE_R4 && !header->locals [(idx)]->byref) {   \
2972                         int temp;       \
2973                         NEW_LOCLOADA (cfg, (ins), (idx));       \
2974                         temp = handle_load_float (cfg, bblock, (ins), (ip));    \
2975                         NEW_TEMPLOAD (cfg, (ins), temp);        \
2976                 }       \
2977         } while (0)
2978 #define STLOC_SOFT_FLOAT(cfg,ins,idx,ip) do {\
2979                 if (header->locals [(idx)]->type == MONO_TYPE_R4 && !header->locals [(idx)]->byref) {   \
2980                         int temp;       \
2981                         NEW_LOCLOADA (cfg, (ins), (idx));       \
2982                         handle_store_float (cfg, bblock, (ins), *sp, (ip));     \
2983                         MONO_INST_NEW (cfg, (ins), OP_NOP);     \
2984                 }       \
2985         } while (0)
2986 #define LDARG_SOFT_FLOAT(cfg,ins,idx,ip) do {\
2987                 if (param_types [(idx)]->type == MONO_TYPE_R4 && !param_types [(idx)]->byref) { \
2988                         int temp;       \
2989                         NEW_ARGLOADA (cfg, (ins), (idx));       \
2990                         temp = handle_load_float (cfg, bblock, (ins), (ip));    \
2991                         NEW_TEMPLOAD (cfg, (ins), temp);        \
2992                 }       \
2993         } while (0)
2994 #define STARG_SOFT_FLOAT(cfg,ins,idx,ip) do {\
2995                 if (param_types [(idx)]->type == MONO_TYPE_R4 && !param_types [(idx)]->byref) { \
2996                         int temp;       \
2997                         NEW_ARGLOADA (cfg, (ins), (idx));       \
2998                         handle_store_float (cfg, bblock, (ins), *sp, (ip));     \
2999                         MONO_INST_NEW (cfg, (ins), OP_NOP);     \
3000                 }       \
3001         } while (0)
3002
3003 #define NEW_TEMPLOAD_SOFT_FLOAT(cfg,bblock,ins,num) do {                \
3004         if ((ins)->opcode == CEE_LDIND_R4) {                                            \
3005             int idx = (num);                                                                            \
3006             int temp;                                                                                   \
3007             NEW_TEMPLOADA (cfg, (ins), (idx));                                                  \
3008                 temp = handle_load_float (cfg, (bblock), (ins), ip);            \
3009                 NEW_TEMPLOAD (cfg, (ins), (temp));                                                      \
3010         }                                                                                                                               \
3011         } while (0)
3012
3013 #else
3014 #define LDLOC_SOFT_FLOAT(cfg,ins,idx,ip)
3015 #define STLOC_SOFT_FLOAT(cfg,ins,idx,ip)
3016 #define LDARG_SOFT_FLOAT(cfg,ins,idx,ip)
3017 #define STARG_SOFT_FLOAT(cfg,ins,idx,ip)
3018 #define NEW_TEMPLOAD_SOFT_FLOAT(cfg,bblock,ins,num)
3019 #endif
3020
3021 static MonoMethod*
3022 get_memcpy_method (void)
3023 {
3024         static MonoMethod *memcpy_method = NULL;
3025         if (!memcpy_method) {
3026                 memcpy_method = mono_class_get_method_from_name (mono_defaults.string_class, "memcpy", 3);
3027                 if (!memcpy_method)
3028                         g_error ("Old corlib found. Install a new one");
3029         }
3030         return memcpy_method;
3031 }
3032
3033 static void
3034 handle_stobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, MonoInst *src, const unsigned char *ip, MonoClass *klass, gboolean to_end, gboolean native, gboolean write_barrier) {
3035         MonoInst *iargs [3];
3036         int n;
3037         guint32 align = 0;
3038         MonoMethod *memcpy_method;
3039
3040         g_assert (klass);
3041         /*
3042          * This check breaks with spilled vars... need to handle it during verification anyway.
3043          * g_assert (klass && klass == src->klass && klass == dest->klass);
3044          */
3045
3046         if (native)
3047                 n = mono_class_native_size (klass, &align);
3048         else
3049                 n = mono_class_value_size (klass, &align);
3050
3051 #if HAVE_WRITE_BARRIERS
3052         /* if native is true there should be no references in the struct */
3053         if (write_barrier && klass->has_references && !native) {
3054                 iargs [0] = dest;
3055                 iargs [1] = src;
3056                 NEW_PCONST (cfg, iargs [2], klass);
3057
3058                 mono_emit_jit_icall (cfg, bblock, mono_value_copy, iargs, ip);
3059                 return;
3060         }
3061 #endif
3062
3063         /* FIXME: add write barrier handling */
3064         if ((cfg->opt & MONO_OPT_INTRINS) && !to_end && n <= sizeof (gpointer) * 5) {
3065                 MonoInst *inst;
3066                 if (dest->opcode == OP_LDADDR) {
3067                         /* Keep liveness info correct */
3068                         NEW_DUMMY_STORE (cfg, inst, dest->inst_i0->inst_c0);
3069                         MONO_ADD_INS (bblock, inst);
3070                 }
3071                 NEW_MEMCPY (cfg, inst, dest, src, n, align);
3072                 MONO_ADD_INS (bblock, inst);
3073                 return;
3074         }
3075         iargs [0] = dest;
3076         iargs [1] = src;
3077         NEW_ICONST (cfg, iargs [2], n);
3078
3079         memcpy_method = get_memcpy_method ();
3080         mono_emit_method_call_spilled_full (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL, FALSE, to_end);
3081 }
3082
3083 static MonoMethod*
3084 get_memset_method (void)
3085 {
3086         static MonoMethod *memset_method = NULL;
3087         if (!memset_method) {
3088                 memset_method = mono_class_get_method_from_name (mono_defaults.string_class, "memset", 3);
3089                 if (!memset_method)
3090                         g_error ("Old corlib found. Install a new one");
3091         }
3092         return memset_method;
3093 }
3094
3095 static void
3096 handle_initobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, const guchar *ip, MonoClass *klass, MonoInst **stack_start, MonoInst **sp)
3097 {
3098         MonoInst *iargs [3];
3099         MonoInst *ins, *zero_int32;
3100         int n;
3101         guint32 align;
3102         MonoMethod *memset_method;
3103
3104         NEW_ICONST (cfg, zero_int32, 0);
3105
3106         mono_class_init (klass);
3107         n = mono_class_value_size (klass, &align);
3108         MONO_INST_NEW (cfg, ins, 0);
3109         ins->cil_code = ip;
3110         ins->inst_left = dest;
3111         ins->inst_right = zero_int32;
3112         if (n == 1) {
3113                 ins->opcode = CEE_STIND_I1;
3114                 MONO_ADD_INS (bblock, ins);
3115         } else if ((n == 2) && (align >= 2)) {
3116                 ins->opcode = CEE_STIND_I2;
3117                 MONO_ADD_INS (bblock, ins);
3118         } else if ((n == 2) && (align >= 4)) {
3119                 ins->opcode = CEE_STIND_I4;
3120                 MONO_ADD_INS (bblock, ins);
3121         } else if (n <= sizeof (gpointer) * 5) {
3122                 NEW_MEMSET (cfg, ins, dest, 0, n, align);
3123                 MONO_ADD_INS (bblock, ins);
3124         } else {
3125                 memset_method = get_memset_method ();
3126                 handle_loaded_temps (cfg, bblock, stack_start, sp);
3127                 iargs [0] = dest;
3128                 NEW_ICONST (cfg, iargs [1], 0);
3129                 NEW_ICONST (cfg, iargs [2], n);
3130                 mono_emit_method_call_spilled (cfg, bblock, memset_method, memset_method->signature, iargs, ip, NULL);
3131         }
3132 }
3133
3134 static int
3135 handle_alloc (MonoCompile *cfg, MonoBasicBlock *bblock, MonoClass *klass, gboolean for_box, const guchar *ip)
3136 {
3137         MonoInst *iargs [2];
3138         void *alloc_ftn;
3139
3140         if (cfg->opt & MONO_OPT_SHARED) {
3141                 NEW_DOMAINCONST (cfg, iargs [0]);
3142                 NEW_CLASSCONST (cfg, iargs [1], klass);
3143
3144                 alloc_ftn = mono_object_new;
3145         } else if (cfg->compile_aot && bblock->out_of_line && klass->type_token && klass->image == mono_defaults.corlib) {
3146                 /* This happens often in argument checking code, eg. throw new FooException... */
3147                 /* Avoid relocations by calling a helper function specialized to mscorlib */
3148                 NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (klass->type_token));
3149                 return mono_emit_jit_icall (cfg, bblock, mono_helper_newobj_mscorlib, iargs, ip);
3150         } else {
3151                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
3152                 MonoMethod *managed_alloc = mono_gc_get_managed_allocator (vtable, for_box);
3153                 gboolean pass_lw;
3154
3155                 if (managed_alloc) {
3156                         NEW_VTABLECONST (cfg, iargs [0], vtable);
3157                         return mono_emit_method_call_spilled (cfg, bblock, managed_alloc, mono_method_signature (managed_alloc), iargs, ip, NULL);
3158                 }
3159                 alloc_ftn = mono_class_get_allocation_ftn (vtable, for_box, &pass_lw);
3160                 if (pass_lw) {
3161                         guint32 lw = vtable->klass->instance_size;
3162                         lw = ((lw + (sizeof (gpointer) - 1)) & ~(sizeof (gpointer) - 1)) / sizeof (gpointer);
3163                         NEW_ICONST (cfg, iargs [0], lw);
3164                         NEW_VTABLECONST (cfg, iargs [1], vtable);
3165                 }
3166                 else
3167                         NEW_VTABLECONST (cfg, iargs [0], vtable);
3168         }
3169
3170         return mono_emit_jit_icall (cfg, bblock, alloc_ftn, iargs, ip);
3171 }
3172
3173 static int
3174 handle_alloc_from_inst (MonoCompile *cfg, MonoBasicBlock *bblock, MonoClass *klass, MonoInst *data_inst,
3175                 gboolean for_box, const guchar *ip)
3176 {
3177         MonoInst *iargs [2];
3178         MonoMethod *managed_alloc = NULL;
3179         void *alloc_ftn;
3180         /*
3181           FIXME: we cannot get managed_alloc here because we can't get
3182           the class's vtable (because it's not a closed class)
3183
3184         MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
3185         MonoMethod *managed_alloc = mono_gc_get_managed_allocator (vtable, for_box);
3186         */
3187
3188         if (cfg->opt & MONO_OPT_SHARED) {
3189                 NEW_DOMAINCONST (cfg, iargs [0]);
3190                 iargs [1] = data_inst;
3191                 alloc_ftn = mono_object_new;
3192         } else {
3193                 g_assert (!cfg->compile_aot);
3194
3195                 if (managed_alloc) {
3196                         iargs [0] = data_inst;
3197                         return mono_emit_method_call_spilled (cfg, bblock, managed_alloc,
3198                                 mono_method_signature (managed_alloc), iargs, ip, NULL);
3199                 }
3200
3201                 iargs [0] = data_inst;
3202                 alloc_ftn = mono_object_new_specific;
3203         }
3204
3205         return mono_emit_jit_icall (cfg, bblock, alloc_ftn, iargs, ip);
3206 }
3207
3208 static MonoInst*
3209 handle_box_copy (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *val, const guchar *ip, MonoClass *klass, int temp)
3210 {
3211         MonoInst *dest, *vtoffset, *add, *vstore;
3212
3213         NEW_TEMPLOAD (cfg, dest, temp);
3214         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
3215         MONO_INST_NEW (cfg, add, OP_PADD);
3216         add->inst_left = dest;
3217         add->inst_right = vtoffset;
3218         add->cil_code = ip;
3219         add->klass = klass;
3220         MONO_INST_NEW (cfg, vstore, CEE_STIND_I);
3221         vstore->opcode = mini_type_to_stind (cfg, &klass->byval_arg);
3222         vstore->cil_code = ip;
3223         vstore->inst_left = add;
3224         vstore->inst_right = val;
3225
3226 #ifdef MONO_ARCH_SOFT_FLOAT
3227         if (vstore->opcode == CEE_STIND_R4) {
3228                 handle_store_float (cfg, bblock, add, val, ip);
3229         } else
3230 #endif
3231         if (vstore->opcode == CEE_STOBJ) {
3232                 handle_stobj (cfg, bblock, add, val, ip, klass, FALSE, FALSE, TRUE);
3233         } else
3234                 MONO_ADD_INS (bblock, vstore);
3235
3236         NEW_TEMPLOAD (cfg, dest, temp);
3237         return dest;
3238 }
3239
3240 static MonoInst *
3241 handle_box (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *val, const guchar *ip, MonoClass *klass)
3242 {
3243         MonoInst *dest;
3244         int temp;
3245
3246         if (mono_class_is_nullable (klass)) {
3247                 MonoMethod* method = mono_class_get_method_from_name (klass, "Box", 1);
3248                 temp = mono_emit_method_call_spilled (cfg, bblock, method, mono_method_signature (method), &val, ip, NULL);
3249                 NEW_TEMPLOAD (cfg, dest, temp);
3250                 return dest;
3251         }
3252
3253         temp = handle_alloc (cfg, bblock, klass, TRUE, ip);
3254
3255         return handle_box_copy (cfg, bblock, val, ip, klass, temp);
3256 }
3257
3258 static MonoInst *
3259 handle_box_from_inst (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *val, const guchar *ip,
3260                 MonoClass *klass, MonoInst *data_inst)
3261 {
3262         int temp;
3263
3264         g_assert (!mono_class_is_nullable (klass));
3265
3266         temp = handle_alloc_from_inst (cfg, bblock, klass, data_inst, TRUE, ip);
3267
3268         return handle_box_copy (cfg, bblock, val, ip, klass, temp);
3269 }
3270
3271 static MonoInst*
3272 handle_delegate_ctor (MonoCompile *cfg, MonoBasicBlock *bblock, MonoClass *klass, MonoInst *target, MonoMethod *method, unsigned char *ip)
3273 {
3274         gpointer *trampoline;
3275         MonoInst *obj, *ins, *store, *offset_ins, *method_ins, *tramp_ins;
3276         int temp;
3277
3278         temp = handle_alloc (cfg, bblock, klass, FALSE, ip);
3279
3280         /* Inline the contents of mono_delegate_ctor */
3281
3282         /* Set target field */
3283         /* Optimize away setting of NULL target */
3284         if (!(target->opcode == OP_PCONST && target->inst_p0 == 0)) {
3285                 NEW_TEMPLOAD (cfg, obj, temp);
3286                 NEW_ICONST (cfg, offset_ins, G_STRUCT_OFFSET (MonoDelegate, target));
3287                 MONO_INST_NEW (cfg, ins, OP_PADD);
3288                 ins->inst_left = obj;
3289                 ins->inst_right = offset_ins;
3290
3291                 MONO_INST_NEW (cfg, store, CEE_STIND_REF);
3292                 store->inst_left = ins;
3293                 store->inst_right = target;
3294                 mono_bblock_add_inst (bblock, store);
3295         }
3296
3297         /* Set method field */
3298         NEW_TEMPLOAD (cfg, obj, temp);
3299         NEW_ICONST (cfg, offset_ins, G_STRUCT_OFFSET (MonoDelegate, method));
3300         MONO_INST_NEW (cfg, ins, OP_PADD);
3301         ins->inst_left = obj;
3302         ins->inst_right = offset_ins;
3303
3304         NEW_METHODCONST (cfg, method_ins, method);
3305
3306         MONO_INST_NEW (cfg, store, CEE_STIND_I);
3307         store->inst_left = ins;
3308         store->inst_right = method_ins;
3309         mono_bblock_add_inst (bblock, store);
3310
3311         /* Set invoke_impl field */
3312         NEW_TEMPLOAD (cfg, obj, temp);
3313         NEW_ICONST (cfg, offset_ins, G_STRUCT_OFFSET (MonoDelegate, invoke_impl));
3314         MONO_INST_NEW (cfg, ins, OP_PADD);
3315         ins->inst_left = obj;
3316         ins->inst_right = offset_ins;
3317
3318         trampoline = mono_create_delegate_trampoline (klass);
3319         NEW_AOTCONST (cfg, tramp_ins, MONO_PATCH_INFO_ABS, trampoline);
3320
3321         MONO_INST_NEW (cfg, store, CEE_STIND_I);
3322         store->inst_left = ins;
3323         store->inst_right = tramp_ins;
3324         mono_bblock_add_inst (bblock, store);
3325
3326         /* All the checks which are in mono_delegate_ctor () are done by the delegate trampoline */
3327
3328         NEW_TEMPLOAD (cfg, obj, temp);
3329
3330         return obj;
3331 }
3332
3333 static int
3334 handle_array_new (MonoCompile *cfg, MonoBasicBlock *bblock, int rank, MonoInst **sp, unsigned char *ip)
3335 {
3336         MonoMethodSignature *esig;
3337         char icall_name [256];
3338         char *name;
3339         MonoJitICallInfo *info;
3340
3341         /* Need to register the icall so it gets an icall wrapper */
3342         sprintf (icall_name, "ves_array_new_va_%d", rank);
3343
3344         mono_jit_lock ();
3345         info = mono_find_jit_icall_by_name (icall_name);
3346         if (info == NULL) {
3347                 esig = mono_get_array_new_va_signature (rank);
3348                 name = g_strdup (icall_name);
3349                 info = mono_register_jit_icall (mono_array_new_va, name, esig, FALSE);
3350
3351                 g_hash_table_insert (jit_icall_name_hash, name, name);
3352         }
3353         mono_jit_unlock ();
3354
3355         cfg->flags |= MONO_CFG_HAS_VARARGS;
3356
3357         /* FIXME: This uses info->sig, but it should use the signature of the wrapper */
3358         return mono_emit_native_call (cfg, bblock, mono_icall_get_wrapper (info), info->sig, sp, ip, TRUE, FALSE);
3359 }
3360
3361 static void
3362 mono_emit_load_got_addr (MonoCompile *cfg)
3363 {
3364         MonoInst *load, *store, *dummy_use;
3365         MonoInst *get_got;
3366
3367         if (!cfg->got_var || cfg->got_var_allocated)
3368                 return;
3369
3370         MONO_INST_NEW (cfg, get_got, OP_LOAD_GOTADDR);
3371         NEW_TEMPSTORE (cfg, store, cfg->got_var->inst_c0, get_got);
3372
3373         /* Add it to the start of the first bblock */
3374         MONO_INST_LIST_ADD (&store->node, &cfg->bb_entry->ins_list);
3375
3376         cfg->got_var_allocated = TRUE;
3377
3378         /* 
3379          * Add a dummy use to keep the got_var alive, since real uses might
3380          * only be generated in the decompose or instruction selection phases.
3381          * Add it to end_bblock, so the variable's lifetime covers the whole
3382          * method.
3383          */
3384         NEW_TEMPLOAD (cfg, load, cfg->got_var->inst_c0);
3385         NEW_DUMMY_USE (cfg, dummy_use, load);
3386         MONO_ADD_INS (cfg->bb_exit, dummy_use);
3387 }
3388
3389 #define CODE_IS_STLOC(ip) (((ip) [0] >= CEE_STLOC_0 && (ip) [0] <= CEE_STLOC_3) || ((ip) [0] == CEE_STLOC_S))
3390
3391 static gboolean
3392 mini_class_is_system_array (MonoClass *klass)
3393 {
3394         if (klass->parent == mono_defaults.array_class)
3395                 return TRUE;
3396         else
3397                 return FALSE;
3398 }
3399
3400 static gboolean
3401 mono_method_check_inlining (MonoCompile *cfg, MonoMethod *method)
3402 {
3403         MonoMethodHeader *header = mono_method_get_header (method);
3404         MonoMethodSignature *signature = mono_method_signature (method);
3405         MonoVTable *vtable;
3406         int i;
3407
3408         if (cfg->generic_sharing_context)
3409                 return FALSE;
3410
3411         if (method->inline_failure)
3412                 return FALSE;
3413
3414 #ifdef MONO_ARCH_HAVE_LMF_OPS
3415         if (((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
3416                  (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) &&
3417             !MONO_TYPE_ISSTRUCT (signature->ret) && !mini_class_is_system_array (method->klass))
3418                 return TRUE;
3419 #endif
3420
3421         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3422             (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
3423             (method->iflags & METHOD_IMPL_ATTRIBUTE_NOINLINING) ||
3424             (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) ||
3425             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3426             (method->klass->marshalbyref) ||
3427             !header || header->num_clauses ||
3428             /* fixme: why cant we inline valuetype returns? */
3429             MONO_TYPE_ISSTRUCT (signature->ret))
3430                 return FALSE;
3431
3432 #ifdef MONO_ARCH_SOFT_FLOAT
3433         /* this complicates things, fix later */
3434         if (signature->ret->type == MONO_TYPE_R4)
3435                 return FALSE;
3436 #endif
3437         /* its not worth to inline methods with valuetype arguments?? */
3438         for (i = 0; i < signature->param_count; i++) {
3439                 if (MONO_TYPE_ISSTRUCT (signature->params [i])) {
3440                         return FALSE;
3441                 }
3442 #ifdef MONO_ARCH_SOFT_FLOAT
3443                 /* this complicates things, fix later */
3444                 if (!signature->params [i]->byref && signature->params [i]->type == MONO_TYPE_R4)
3445                         return FALSE;
3446 #endif
3447         }
3448
3449         /* also consider num_locals? */
3450         /* Do the size check early to avoid creating vtables */
3451         if (getenv ("MONO_INLINELIMIT")) {
3452                 if (header->code_size >= atoi (getenv ("MONO_INLINELIMIT"))) {
3453                         return FALSE;
3454                 }
3455         } else if (header->code_size >= INLINE_LENGTH_LIMIT)
3456                 return FALSE;
3457
3458         /*
3459          * if we can initialize the class of the method right away, we do,
3460          * otherwise we don't allow inlining if the class needs initialization,
3461          * since it would mean inserting a call to mono_runtime_class_init()
3462          * inside the inlined code
3463          */
3464         if (!(cfg->opt & MONO_OPT_SHARED)) {
3465                 if (method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) {
3466                         if (cfg->run_cctors && method->klass->has_cctor) {
3467                                 if (!method->klass->runtime_info)
3468                                         /* No vtable created yet */
3469                                         return FALSE;
3470                                 vtable = mono_class_vtable (cfg->domain, method->klass);
3471                                 if (!vtable)
3472                                         return FALSE;
3473                                 /* This makes so that inline cannot trigger */
3474                                 /* .cctors: too many apps depend on them */
3475                                 /* running with a specific order... */
3476                                 if (! vtable->initialized)
3477                                         return FALSE;
3478                                 mono_runtime_class_init (vtable);
3479                         }
3480                 } else if (mono_class_needs_cctor_run (method->klass, NULL)) {
3481                         if (!method->klass->runtime_info)
3482                                 /* No vtable created yet */
3483                                 return FALSE;
3484                         vtable = mono_class_vtable (cfg->domain, method->klass);
3485                         if (!vtable)
3486                                 return FALSE;
3487                         if (!vtable->initialized)
3488                                 return FALSE;
3489                 }
3490         } else {
3491                 /* 
3492                  * If we're compiling for shared code
3493                  * the cctor will need to be run at aot method load time, for example,
3494                  * or at the end of the compilation of the inlining method.
3495                  */
3496                 if (mono_class_needs_cctor_run (method->klass, NULL) && !((method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3497                         return FALSE;
3498         }
3499         //if (!MONO_TYPE_IS_VOID (signature->ret)) return FALSE;
3500
3501         /*
3502          * CAS - do not inline methods with declarative security
3503          * Note: this has to be before any possible return TRUE;
3504          */
3505         if (mono_method_has_declsec (method))
3506                 return FALSE;
3507
3508         return TRUE;
3509 }
3510
3511 static gboolean
3512 mini_field_access_needs_cctor_run (MonoCompile *cfg, MonoMethod *method, MonoVTable *vtable)
3513 {
3514         if (vtable->initialized && !cfg->compile_aot)
3515                 return FALSE;
3516
3517         if (vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)
3518                 return FALSE;
3519
3520         if (!mono_class_needs_cctor_run (vtable->klass, method))
3521                 return FALSE;
3522
3523         if (! (method->flags & METHOD_ATTRIBUTE_STATIC) && (vtable->klass == method->klass))
3524                 /* The initialization is already done before the method is called */
3525                 return FALSE;
3526
3527         return TRUE;
3528 }
3529
3530 static MonoInst*
3531 mini_get_ldelema_ins (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *cmethod, MonoInst **sp, unsigned char *ip, gboolean is_set)
3532 {
3533         int temp, rank;
3534         MonoInst *addr;
3535         MonoMethod *addr_method;
3536         int element_size;
3537
3538         rank = mono_method_signature (cmethod)->param_count - (is_set? 1: 0);
3539
3540         if (rank == 1) {
3541                 MONO_INST_NEW (cfg, addr, CEE_LDELEMA);
3542                 addr->inst_left = sp [0];
3543                 addr->inst_right = sp [1];
3544                 addr->type = STACK_MP;
3545                 addr->klass = cmethod->klass->element_class;
3546                 return addr;
3547         }
3548
3549         if (rank == 2 && (cfg->opt & MONO_OPT_INTRINS)) {
3550 #if defined(MONO_ARCH_EMULATE_MUL_DIV) && !defined(MONO_ARCH_NO_EMULATE_MUL)
3551                 /* OP_LDELEMA2D depends on OP_LMUL */
3552 #else
3553                 MonoInst *indexes;
3554                 NEW_GROUP (cfg, indexes, sp [1], sp [2]);
3555                 MONO_INST_NEW (cfg, addr, OP_LDELEMA2D);
3556                 addr->inst_left = sp [0];
3557                 addr->inst_right = indexes;
3558                 addr->type = STACK_MP;
3559                 addr->klass = cmethod->klass->element_class;
3560                 return addr;
3561 #endif
3562         }
3563
3564         element_size = mono_class_array_element_size (cmethod->klass->element_class);
3565         addr_method = mono_marshal_get_array_address (rank, element_size);
3566         temp = mono_emit_method_call_spilled (cfg, bblock, addr_method, addr_method->signature, sp, ip, NULL);
3567         NEW_TEMPLOAD (cfg, addr, temp);
3568         return addr;
3569
3570 }
3571
3572 static MonoJitICallInfo **emul_opcode_map = NULL;
3573
3574 MonoJitICallInfo *
3575 mono_find_jit_opcode_emulation (int opcode)
3576 {
3577         g_assert (opcode >= 0 && opcode <= OP_LAST);
3578         if  (emul_opcode_map)
3579                 return emul_opcode_map [opcode];
3580         else
3581                 return NULL;
3582 }
3583
3584 static MonoInst*
3585 mini_get_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
3586 {
3587         MonoInst *ins = NULL;
3588         
3589         static MonoClass *runtime_helpers_class = NULL;
3590         if (! runtime_helpers_class)
3591                 runtime_helpers_class = mono_class_from_name (mono_defaults.corlib,
3592                         "System.Runtime.CompilerServices", "RuntimeHelpers");
3593
3594         if (cmethod->klass == mono_defaults.string_class) {
3595                 if (strcmp (cmethod->name, "get_Chars") == 0) {
3596                         MONO_INST_NEW (cfg, ins, OP_GETCHR);
3597                         ins->inst_i0 = args [0];
3598                         ins->inst_i1 = args [1];
3599                         return ins;
3600                 } else if (strcmp (cmethod->name, "get_Length") == 0) {
3601                         MONO_INST_NEW (cfg, ins, OP_STRLEN);
3602                         ins->inst_i0 = args [0];
3603                         return ins;
3604                 } else if (strcmp (cmethod->name, "InternalSetChar") == 0) {
3605                         MonoInst *get_addr;
3606                         MONO_INST_NEW (cfg, get_addr, OP_STR_CHAR_ADDR);
3607                         get_addr->inst_i0 = args [0];
3608                         get_addr->inst_i1 = args [1];
3609                         MONO_INST_NEW (cfg, ins, CEE_STIND_I2);
3610                         ins->inst_i0 = get_addr;
3611                         ins->inst_i1 = args [2];
3612                         return ins;
3613                 } else 
3614                         return NULL;
3615         } else if (cmethod->klass == mono_defaults.object_class) {
3616                 if (strcmp (cmethod->name, "GetType") == 0) {
3617                         MONO_INST_NEW (cfg, ins, OP_GETTYPE);
3618                         ins->inst_i0 = args [0];
3619                         return ins;
3620                 /* The OP_GETHASHCODE rule depends on OP_MUL */
3621 #if !defined(MONO_ARCH_EMULATE_MUL_DIV) && !defined(HAVE_MOVING_COLLECTOR)
3622                 } else if (strcmp (cmethod->name, "InternalGetHashCode") == 0) {
3623                         MONO_INST_NEW (cfg, ins, OP_GETHASHCODE);
3624                         ins->inst_i0 = args [0];
3625                         return ins;
3626 #endif
3627                 } else if (strcmp (cmethod->name, ".ctor") == 0) {
3628                         MONO_INST_NEW (cfg, ins, OP_NOP);
3629                         return ins;
3630                 } else
3631                         return NULL;
3632         } else if (cmethod->klass == mono_defaults.array_class) {
3633                 if (cmethod->name [0] != 'g')
3634                         return NULL;
3635
3636                 if (strcmp (cmethod->name, "get_Rank") == 0) {
3637                         MONO_INST_NEW (cfg, ins, OP_ARRAY_RANK);
3638                         ins->inst_i0 = args [0];
3639                         return ins;
3640                 } else if (strcmp (cmethod->name, "get_Length") == 0) {
3641                         MONO_INST_NEW (cfg, ins, CEE_LDLEN);
3642                         ins->inst_i0 = args [0];
3643                         return ins;
3644                 } else
3645                         return NULL;
3646         } else if (cmethod->klass == runtime_helpers_class) {
3647                 if (strcmp (cmethod->name, "get_OffsetToStringData") == 0) {
3648                         NEW_ICONST (cfg, ins, G_STRUCT_OFFSET (MonoString, chars));
3649                         return ins;
3650                 } else
3651                         return NULL;
3652         } else if (cmethod->klass == mono_defaults.thread_class) {
3653                 if (strcmp (cmethod->name, "get_CurrentThread") == 0 && (ins = mono_arch_get_thread_intrinsic (cfg)))
3654                         return ins;
3655                 if (strcmp (cmethod->name, "MemoryBarrier") == 0) {
3656                         MONO_INST_NEW (cfg, ins, OP_MEMORY_BARRIER);
3657                         return ins;
3658                 }
3659         } else if (mini_class_is_system_array (cmethod->klass) &&
3660                         strcmp (cmethod->name, "GetGenericValueImpl") == 0) {
3661                 MonoInst *sp [2];
3662                 MonoInst *ldelem, *store, *load;
3663                 MonoClass *eklass = mono_class_from_mono_type (fsig->params [1]);
3664                 int n;
3665                 n = mini_type_to_stind (cfg, &eklass->byval_arg);
3666                 if (n == CEE_STOBJ)
3667                         return NULL;
3668                 sp [0] = args [0];
3669                 sp [1] = args [1];
3670                 NEW_LDELEMA (cfg, ldelem, sp, eklass);
3671                 ldelem->flags |= MONO_INST_NORANGECHECK;
3672                 MONO_INST_NEW (cfg, store, n);
3673                 MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, &eklass->byval_arg));
3674                 type_to_eval_stack_type (cfg, &eklass->byval_arg, load);
3675                 load->inst_left = ldelem;
3676                 store->inst_left = args [2];
3677                 store->inst_right = load;
3678                 return store;
3679         } else if (cmethod->klass == mono_defaults.math_class) {
3680                 /* 
3681                  * There is general branches code for Min/Max, but it does not work for 
3682                  * all inputs:
3683                  * http://everything2.com/?node_id=1051618
3684                  */
3685         } else if (cmethod->klass->image == mono_defaults.corlib &&
3686                            (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
3687                            (strcmp (cmethod->klass->name, "Interlocked") == 0)) {
3688                 ins = NULL;
3689
3690 #if SIZEOF_VOID_P == 8
3691                 if (strcmp (cmethod->name, "Read") == 0 && (fsig->params [0]->type == MONO_TYPE_I8)) {
3692                         /* 64 bit reads are already atomic */
3693                         MONO_INST_NEW (cfg, ins, CEE_LDIND_I8);
3694                         ins->inst_i0 = args [0];
3695                 }
3696 #endif
3697
3698 #ifdef MONO_ARCH_HAVE_ATOMIC_ADD
3699                 if (strcmp (cmethod->name, "Increment") == 0) {
3700                         MonoInst *ins_iconst;
3701                         guint32 opcode;
3702
3703                         if (fsig->params [0]->type == MONO_TYPE_I4)
3704                                 opcode = OP_ATOMIC_ADD_NEW_I4;
3705                         else if (fsig->params [0]->type == MONO_TYPE_I8)
3706                                 opcode = OP_ATOMIC_ADD_NEW_I8;
3707                         else
3708                                 g_assert_not_reached ();
3709
3710 #if SIZEOF_VOID_P == 4
3711                         if (opcode == OP_ATOMIC_ADD_NEW_I8)
3712                                 return NULL;
3713 #endif
3714
3715                         MONO_INST_NEW (cfg, ins, opcode);
3716                         MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
3717                         ins_iconst->inst_c0 = 1;
3718
3719                         ins->inst_i0 = args [0];
3720                         ins->inst_i1 = ins_iconst;
3721                 } else if (strcmp (cmethod->name, "Decrement") == 0) {
3722                         MonoInst *ins_iconst;
3723                         guint32 opcode;
3724
3725                         if (fsig->params [0]->type == MONO_TYPE_I4)
3726                                 opcode = OP_ATOMIC_ADD_NEW_I4;
3727                         else if (fsig->params [0]->type == MONO_TYPE_I8)
3728                                 opcode = OP_ATOMIC_ADD_NEW_I8;
3729                         else
3730                                 g_assert_not_reached ();
3731
3732 #if SIZEOF_VOID_P == 4
3733                         if (opcode == OP_ATOMIC_ADD_NEW_I8)
3734                                 return NULL;
3735 #endif
3736
3737                         MONO_INST_NEW (cfg, ins, opcode);
3738                         MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
3739                         ins_iconst->inst_c0 = -1;
3740
3741                         ins->inst_i0 = args [0];
3742                         ins->inst_i1 = ins_iconst;
3743                 } else if (strcmp (cmethod->name, "Add") == 0) {
3744                         guint32 opcode;
3745
3746                         if (fsig->params [0]->type == MONO_TYPE_I4)
3747                                 opcode = OP_ATOMIC_ADD_NEW_I4;
3748                         else if (fsig->params [0]->type == MONO_TYPE_I8)
3749                                 opcode = OP_ATOMIC_ADD_NEW_I8;
3750                         else
3751                                 g_assert_not_reached ();
3752
3753 #if SIZEOF_VOID_P == 4
3754                         if (opcode == OP_ATOMIC_ADD_NEW_I8)
3755                                 return NULL;
3756 #endif
3757                         
3758                         MONO_INST_NEW (cfg, ins, opcode);
3759
3760                         ins->inst_i0 = args [0];
3761                         ins->inst_i1 = args [1];
3762                 }
3763 #endif /* MONO_ARCH_HAVE_ATOMIC_ADD */
3764
3765 #ifdef MONO_ARCH_HAVE_ATOMIC_EXCHANGE
3766                 if (strcmp (cmethod->name, "Exchange") == 0) {
3767                         guint32 opcode;
3768
3769                         if (fsig->params [0]->type == MONO_TYPE_I4)
3770                                 opcode = OP_ATOMIC_EXCHANGE_I4;
3771 #if SIZEOF_VOID_P == 8
3772                         else if ((fsig->params [0]->type == MONO_TYPE_I8) ||
3773                                          (fsig->params [0]->type == MONO_TYPE_I) ||
3774                                          (fsig->params [0]->type == MONO_TYPE_OBJECT))
3775                                 opcode = OP_ATOMIC_EXCHANGE_I8;
3776 #else
3777                         else if ((fsig->params [0]->type == MONO_TYPE_I) ||
3778                                          (fsig->params [0]->type == MONO_TYPE_OBJECT))
3779                                 opcode = OP_ATOMIC_EXCHANGE_I4;
3780 #endif
3781                         else
3782                                 return NULL;
3783
3784 #if SIZEOF_VOID_P == 4
3785                         if (opcode == OP_ATOMIC_EXCHANGE_I8)
3786                                 return NULL;
3787 #endif
3788
3789                         MONO_INST_NEW (cfg, ins, opcode);
3790
3791                         ins->inst_i0 = args [0];
3792                         ins->inst_i1 = args [1];
3793                 }
3794 #endif /* MONO_ARCH_HAVE_ATOMIC_EXCHANGE */
3795
3796 #ifdef MONO_ARCH_HAVE_ATOMIC_CAS_IMM
3797                 /* 
3798                  * Can't implement CompareExchange methods this way since they have
3799                  * three arguments. We can implement one of the common cases, where the new
3800                  * value is a constant.
3801                  */
3802                 if ((strcmp (cmethod->name, "CompareExchange") == 0)) {
3803                         if (fsig->params [1]->type == MONO_TYPE_I4 && args [2]->opcode == OP_ICONST) {
3804                                 MONO_INST_NEW (cfg, ins, OP_ATOMIC_CAS_IMM_I4);
3805                                 ins->inst_i0 = args [0];
3806                                 ins->inst_i1 = args [1];
3807                                 ins->backend.data = GINT_TO_POINTER (args [2]->inst_c0);
3808                         }
3809                         /* The I8 case is hard to detect, since the arg might be a conv.i8 (iconst) tree */
3810                 }
3811 #endif /* MONO_ARCH_HAVE_ATOMIC_CAS_IMM */
3812
3813                 if (ins)
3814                         return ins;
3815         } else if (cmethod->klass->image == mono_defaults.corlib) {
3816                 if (cmethod->name [0] == 'B' && strcmp (cmethod->name, "Break") == 0
3817                                 && strcmp (cmethod->klass->name, "Debugger") == 0) {
3818                         MONO_INST_NEW (cfg, ins, OP_BREAK);
3819                         return ins;
3820                 }
3821                 if (cmethod->name [0] == 'g' && strcmp (cmethod->name, "get_IsRunningOnWindows") == 0
3822                                 && strcmp (cmethod->klass->name, "Environment") == 0) {
3823 #ifdef PLATFORM_WIN32
3824                         NEW_ICONST (cfg, ins, 1);
3825 #else
3826                         NEW_ICONST (cfg, ins, 0);
3827 #endif
3828                         return ins;
3829                 }
3830         }
3831
3832         return mono_arch_get_inst_for_method (cfg, cmethod, fsig, args);
3833 }
3834
3835 static void
3836 mono_save_args (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, MonoInst **sp, MonoInst **args)
3837 {
3838         MonoInst *store, *temp;
3839         int i;
3840
3841         g_assert (!MONO_TYPE_ISSTRUCT (sig->ret));
3842
3843         if (!sig->hasthis && sig->param_count == 0) 
3844                 return;
3845
3846         if (sig->hasthis) {
3847                 if (sp [0]->opcode == OP_ICONST) {
3848                         *args++ = sp [0];
3849                 } else {
3850                         temp = mono_compile_create_var (cfg, type_from_stack_type (*sp), OP_LOCAL);
3851                         *args++ = temp;
3852                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
3853                         /* FIXME: handle CEE_STIND_R4 */
3854                         store->cil_code = sp [0]->cil_code;
3855                         MONO_ADD_INS (bblock, store);
3856                 }
3857                 sp++;
3858         }
3859
3860         for (i = 0; i < sig->param_count; ++i) {
3861                 if (sp [0]->opcode == OP_ICONST) {
3862                         *args++ = sp [0];
3863                 } else {
3864                         temp = mono_compile_create_var (cfg, sig->params [i], OP_LOCAL);
3865                         *args++ = temp;
3866                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
3867                         store->cil_code = sp [0]->cil_code;
3868                         /* FIXME: handle CEE_STIND_R4 */
3869                         if (store->opcode == CEE_STOBJ) {
3870                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
3871                                 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, temp->klass, FALSE, FALSE, FALSE);
3872 #ifdef MONO_ARCH_SOFT_FLOAT
3873                         } else if (store->opcode == CEE_STIND_R4) {
3874                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
3875                                 handle_store_float (cfg, bblock, store, *sp, sp [0]->cil_code);
3876 #endif
3877                         } else {
3878                                 MONO_ADD_INS (bblock, store);
3879                         } 
3880                 }
3881                 sp++;
3882         }
3883 }
3884 #define MONO_INLINE_CALLED_LIMITED_METHODS 0
3885 #define MONO_INLINE_CALLER_LIMITED_METHODS 0
3886
3887 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
3888 static char*
3889 mono_inline_called_method_name_limit = NULL;
3890 static gboolean check_inline_called_method_name_limit (MonoMethod *called_method) {
3891         char *called_method_name = mono_method_full_name (called_method, TRUE);
3892         int strncmp_result;
3893         
3894         if (mono_inline_called_method_name_limit == NULL) {
3895                 char *limit_string = getenv ("MONO_INLINE_CALLED_METHOD_NAME_LIMIT");
3896                 if (limit_string != NULL) {
3897                         mono_inline_called_method_name_limit = limit_string;
3898                 } else {
3899                         mono_inline_called_method_name_limit = (char *) "";
3900                 }
3901         }
3902         
3903         strncmp_result = strncmp (called_method_name, mono_inline_called_method_name_limit, strlen (mono_inline_called_method_name_limit));
3904         g_free (called_method_name);
3905         
3906         //return (strncmp_result <= 0);
3907         return (strncmp_result == 0);
3908 }
3909 #endif
3910
3911 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
3912 static char*
3913 mono_inline_caller_method_name_limit = NULL;
3914 static gboolean check_inline_caller_method_name_limit (MonoMethod *caller_method) {
3915         char *caller_method_name = mono_method_full_name (caller_method, TRUE);
3916         int strncmp_result;
3917         
3918         if (mono_inline_caller_method_name_limit == NULL) {
3919                 char *limit_string = getenv ("MONO_INLINE_CALLER_METHOD_NAME_LIMIT");
3920                 if (limit_string != NULL) {
3921                         mono_inline_caller_method_name_limit = limit_string;
3922                 } else {
3923                         mono_inline_caller_method_name_limit = (char *) "";
3924                 }
3925         }
3926         
3927         strncmp_result = strncmp (caller_method_name, mono_inline_caller_method_name_limit, strlen (mono_inline_caller_method_name_limit));
3928         g_free (caller_method_name);
3929         
3930         //return (strncmp_result <= 0);
3931         return (strncmp_result == 0);
3932 }
3933 #endif
3934
3935 static int
3936 inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoBasicBlock *bblock, MonoInst **sp,
3937                 guchar *ip, guint real_offset, GList *dont_inline, MonoBasicBlock **last_b, gboolean inline_allways)
3938 {
3939         MonoInst *ins, *rvar = NULL;
3940         MonoMethodHeader *cheader;
3941         MonoBasicBlock *ebblock, *sbblock;
3942         int i, costs, new_locals_offset;
3943         MonoMethod *prev_inlined_method;
3944         MonoBasicBlock **prev_cil_offset_to_bb;
3945         unsigned char* prev_cil_start;
3946         guint32 prev_cil_offset_to_bb_len;
3947
3948         g_assert (cfg->exception_type == MONO_EXCEPTION_NONE);
3949
3950 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
3951         if ((! inline_allways) && ! check_inline_called_method_name_limit (cmethod))
3952                 return 0;
3953 #endif
3954 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
3955         if ((! inline_allways) && ! check_inline_caller_method_name_limit (cfg->method))
3956                 return 0;
3957 #endif
3958
3959         if (bblock->out_of_line && !inline_allways)
3960                 return 0;
3961
3962         if (cfg->verbose_level > 2)
3963                 g_print ("INLINE START %p %s -> %s\n", cmethod,  mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
3964
3965         if (!cmethod->inline_info) {
3966                 mono_jit_stats.inlineable_methods++;
3967                 cmethod->inline_info = 1;
3968         }
3969         /* allocate space to store the return value */
3970         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
3971                 rvar =  mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
3972         }
3973
3974         /* allocate local variables */
3975         cheader = mono_method_get_header (cmethod);
3976         new_locals_offset = cfg->num_varinfo;
3977         for (i = 0; i < cheader->num_locals; ++i)
3978                 mono_compile_create_var (cfg, cheader->locals [i], OP_LOCAL);
3979
3980         /* allocate starte and end blocks */
3981         NEW_BBLOCK (cfg, sbblock);
3982         sbblock->block_num = cfg->num_bblocks++;
3983         sbblock->real_offset = real_offset;
3984
3985         NEW_BBLOCK (cfg, ebblock);
3986         ebblock->block_num = cfg->num_bblocks++;
3987         ebblock->real_offset = real_offset;
3988
3989         prev_inlined_method = cfg->inlined_method;
3990         cfg->inlined_method = cmethod;
3991         prev_cil_offset_to_bb = cfg->cil_offset_to_bb;
3992         prev_cil_offset_to_bb_len = cfg->cil_offset_to_bb_len;
3993         prev_cil_start = cfg->cil_start;
3994
3995         costs = mono_method_to_ir (cfg, cmethod, sbblock, ebblock, new_locals_offset, rvar, dont_inline, sp, real_offset, *ip == CEE_CALLVIRT);
3996
3997         cfg->inlined_method = prev_inlined_method;
3998         cfg->cil_offset_to_bb = prev_cil_offset_to_bb;
3999         cfg->cil_offset_to_bb_len = prev_cil_offset_to_bb_len;
4000         cfg->cil_start = prev_cil_start;
4001
4002         if ((costs >= 0 && costs < 60) || inline_allways) {
4003                 if (cfg->verbose_level > 2)
4004                         g_print ("INLINE END %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
4005                 
4006                 mono_jit_stats.inlined_methods++;
4007
4008                 /* always add some code to avoid block split failures */
4009                 MONO_INST_NEW (cfg, ins, OP_NOP);
4010                 MONO_ADD_INS (bblock, ins);
4011                 ins->cil_code = ip;
4012
4013                 bblock->next_bb = sbblock;
4014                 link_bblock (cfg, bblock, sbblock);
4015
4016                 if (rvar) {
4017                         NEW_TEMPLOAD (cfg, ins, rvar->inst_c0);
4018                         NEW_TEMPLOAD_SOFT_FLOAT (cfg, ebblock, ins, rvar->inst_c0);
4019                         *sp++ = ins;
4020                 }
4021                 *last_b = ebblock;
4022                 return costs + 1;
4023         } else {
4024                 if (cfg->verbose_level > 2)
4025                         g_print ("INLINE ABORTED %s\n", mono_method_full_name (cmethod, TRUE));
4026                 cfg->exception_type = MONO_EXCEPTION_NONE;
4027                 mono_loader_clear_error ();
4028                 cmethod->inline_failure = TRUE;
4029         }
4030         return 0;
4031 }
4032
4033 /*
4034  * Some of these comments may well be out-of-date.
4035  * Design decisions: we do a single pass over the IL code (and we do bblock 
4036  * splitting/merging in the few cases when it's required: a back jump to an IL
4037  * address that was not already seen as bblock starting point).
4038  * Code is validated as we go (full verification is still better left to metadata/verify.c).
4039  * Complex operations are decomposed in simpler ones right away. We need to let the 
4040  * arch-specific code peek and poke inside this process somehow (except when the 
4041  * optimizations can take advantage of the full semantic info of coarse opcodes).
4042  * All the opcodes of the form opcode.s are 'normalized' to opcode.
4043  * MonoInst->opcode initially is the IL opcode or some simplification of that 
4044  * (OP_LOAD, OP_STORE). The arch-specific code may rearrange it to an arch-specific 
4045  * opcode with value bigger than OP_LAST.
4046  * At this point the IR can be handed over to an interpreter, a dumb code generator
4047  * or to the optimizing code generator that will translate it to SSA form.
4048  *
4049  * Profiling directed optimizations.
4050  * We may compile by default with few or no optimizations and instrument the code
4051  * or the user may indicate what methods to optimize the most either in a config file
4052  * or through repeated runs where the compiler applies offline the optimizations to 
4053  * each method and then decides if it was worth it.
4054  *
4055  */
4056
4057 #define CHECK_TYPE(ins) if (!(ins)->type) UNVERIFIED
4058 #define CHECK_STACK(num) if ((sp - stack_start) < (num)) UNVERIFIED
4059 #define CHECK_STACK_OVF(num) if (((sp - stack_start) + (num)) > header->max_stack) UNVERIFIED
4060 #define CHECK_ARG(num) if ((unsigned)(num) >= (unsigned)num_args) UNVERIFIED
4061 #define CHECK_LOCAL(num) if ((unsigned)(num) >= (unsigned)header->num_locals) UNVERIFIED
4062 #define CHECK_OPSIZE(size) if (ip + size > end) UNVERIFIED
4063 #define CHECK_UNVERIFIABLE(cfg) if (cfg->unverifiable) UNVERIFIED
4064 #define CHECK_TYPELOAD(klass) if (!(klass) || (klass)->exception_type) {cfg->exception_ptr = klass; goto load_error;}
4065
4066 /* offset from br.s -> br like opcodes */
4067 #define BIG_BRANCH_OFFSET 13
4068
4069 static inline gboolean
4070 ip_in_bb (MonoCompile *cfg, MonoBasicBlock *bb, const guint8* ip)
4071 {
4072         MonoBasicBlock *b = cfg->cil_offset_to_bb [ip - cfg->cil_start];
4073         
4074         return b == NULL || b == bb;
4075 }
4076
4077 static int
4078 get_basic_blocks (MonoCompile *cfg, MonoMethodHeader* header, guint real_offset, unsigned char *start, unsigned char *end, unsigned char **pos)
4079 {
4080         unsigned char *ip = start;
4081         unsigned char *target;
4082         int i;
4083         guint cli_addr;
4084         MonoBasicBlock *bblock;
4085         const MonoOpcode *opcode;
4086
4087         while (ip < end) {
4088                 cli_addr = ip - start;
4089                 i = mono_opcode_value ((const guint8 **)&ip, end);
4090                 if (i < 0)
4091                         UNVERIFIED;
4092                 opcode = &mono_opcodes [i];
4093                 switch (opcode->argument) {
4094                 case MonoInlineNone:
4095                         ip++; 
4096                         break;
4097                 case MonoInlineString:
4098                 case MonoInlineType:
4099                 case MonoInlineField:
4100                 case MonoInlineMethod:
4101                 case MonoInlineTok:
4102                 case MonoInlineSig:
4103                 case MonoShortInlineR:
4104                 case MonoInlineI:
4105                         ip += 5;
4106                         break;
4107                 case MonoInlineVar:
4108                         ip += 3;
4109                         break;
4110                 case MonoShortInlineVar:
4111                 case MonoShortInlineI:
4112                         ip += 2;
4113                         break;
4114                 case MonoShortInlineBrTarget:
4115                         target = start + cli_addr + 2 + (signed char)ip [1];
4116                         GET_BBLOCK (cfg, bblock, target);
4117                         ip += 2;
4118                         if (ip < end)
4119                                 GET_BBLOCK (cfg, bblock, ip);
4120                         break;
4121                 case MonoInlineBrTarget:
4122                         target = start + cli_addr + 5 + (gint32)read32 (ip + 1);
4123                         GET_BBLOCK (cfg, bblock, target);
4124                         ip += 5;
4125                         if (ip < end)
4126                                 GET_BBLOCK (cfg, bblock, ip);
4127                         break;
4128                 case MonoInlineSwitch: {
4129                         guint32 n = read32 (ip + 1);
4130                         guint32 j;
4131                         ip += 5;
4132                         cli_addr += 5 + 4 * n;
4133                         target = start + cli_addr;
4134                         GET_BBLOCK (cfg, bblock, target);
4135                         
4136                         for (j = 0; j < n; ++j) {
4137                                 target = start + cli_addr + (gint32)read32 (ip);
4138                                 GET_BBLOCK (cfg, bblock, target);
4139                                 ip += 4;
4140                         }
4141                         break;
4142                 }
4143                 case MonoInlineR:
4144                 case MonoInlineI8:
4145                         ip += 9;
4146                         break;
4147                 default:
4148                         g_assert_not_reached ();
4149                 }
4150
4151                 if (i == CEE_THROW) {
4152                         unsigned char *bb_start = ip - 1;
4153                         
4154                         /* Find the start of the bblock containing the throw */
4155                         bblock = NULL;
4156                         while ((bb_start >= start) && !bblock) {
4157                                 bblock = cfg->cil_offset_to_bb [(bb_start) - start];
4158                                 bb_start --;
4159                         }
4160                         if (bblock)
4161                                 bblock->out_of_line = 1;
4162                 }
4163         }
4164         return 0;
4165 unverified:
4166         *pos = ip;
4167         return 1;
4168 }
4169
4170 static MonoInst*
4171 emit_tree (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ins, const guint8* ip_next)
4172 {
4173         MonoInst *store, *temp, *load;
4174         
4175         if (ip_in_bb (cfg, bblock, ip_next) &&
4176                 (CODE_IS_STLOC (ip_next) || *ip_next == CEE_RET))
4177                         return ins;
4178         
4179         temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
4180         temp->flags |= MONO_INST_IS_TEMP;
4181         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
4182         /* FIXME: handle CEE_STIND_R4 */
4183         store->cil_code = ins->cil_code;
4184         MONO_ADD_INS (bblock, store);
4185         NEW_TEMPLOAD (cfg, load, temp->inst_c0);
4186         load->cil_code = ins->cil_code;
4187         return load;
4188 }
4189
4190 static inline MonoMethod *
4191 mini_get_method_allow_open (MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context)
4192 {
4193         MonoMethod *method;
4194
4195         if (m->wrapper_type != MONO_WRAPPER_NONE)
4196                 return mono_method_get_wrapper_data (m, token);
4197
4198         method = mono_get_method_full (m->klass->image, token, klass, context);
4199
4200         return method;
4201 }
4202
4203 static inline MonoMethod *
4204 mini_get_method (MonoCompile *cfg, MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context)
4205 {
4206         MonoMethod *method = mini_get_method_allow_open (m, token, klass, context);
4207
4208         if (method && cfg && !cfg->generic_sharing_context && mono_class_is_open_constructed_type (&method->klass->byval_arg))
4209                 return NULL;
4210
4211         return method;
4212 }
4213
4214 static inline MonoClass*
4215 mini_get_class (MonoMethod *method, guint32 token, MonoGenericContext *context)
4216 {
4217         MonoClass *klass;
4218
4219         if (method->wrapper_type != MONO_WRAPPER_NONE)
4220                 klass = mono_method_get_wrapper_data (method, token);
4221         else
4222                 klass = mono_class_get_full (method->klass->image, token, context);
4223         if (klass)
4224                 mono_class_init (klass);
4225         return klass;
4226 }
4227
4228 /*
4229  * Returns TRUE if the JIT should abort inlining because "callee"
4230  * is influenced by security attributes.
4231  */
4232 static
4233 gboolean check_linkdemand (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee, MonoBasicBlock *bblock, unsigned char *ip)
4234 {
4235         guint32 result;
4236         
4237         if ((cfg->method != caller) && mono_method_has_declsec (callee)) {
4238                 return TRUE;
4239         }
4240         
4241         result = mono_declsec_linkdemand (cfg->domain, caller, callee);
4242         if (result == MONO_JIT_SECURITY_OK)
4243                 return FALSE;
4244
4245         if (result == MONO_JIT_LINKDEMAND_ECMA) {
4246                 /* Generate code to throw a SecurityException before the actual call/link */
4247                 MonoSecurityManager *secman = mono_security_manager_get_methods ();
4248                 MonoInst *args [2];
4249
4250                 NEW_ICONST (cfg, args [0], 4);
4251                 NEW_METHODCONST (cfg, args [1], caller);
4252                 mono_emit_method_call_spilled (cfg, bblock, secman->linkdemandsecurityexception, mono_method_signature (secman->linkdemandsecurityexception), args, ip, NULL);
4253         } else if (cfg->exception_type == MONO_EXCEPTION_NONE) {
4254                  /* don't hide previous results */
4255                 cfg->exception_type = MONO_EXCEPTION_SECURITY_LINKDEMAND;
4256                 cfg->exception_data = result;
4257                 return TRUE;
4258         }
4259         
4260         return FALSE;
4261 }
4262
4263 static MonoMethod*
4264 method_access_exception (void)
4265 {
4266         static MonoMethod *method = NULL;
4267
4268         if (!method) {
4269                 MonoSecurityManager *secman = mono_security_manager_get_methods ();
4270                 method = mono_class_get_method_from_name (secman->securitymanager,
4271                                                           "MethodAccessException", 2);
4272         }
4273         g_assert (method);
4274         return method;
4275 }
4276
4277 static void
4278 emit_throw_method_access_exception (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee,
4279                                     MonoBasicBlock *bblock, unsigned char *ip)
4280 {
4281         MonoMethod *thrower = method_access_exception ();
4282         MonoInst *args [2];
4283
4284         NEW_METHODCONST (cfg, args [0], caller);
4285         NEW_METHODCONST (cfg, args [1], callee);
4286         mono_emit_method_call_spilled (cfg, bblock, thrower,
4287                 mono_method_signature (thrower), args, ip, NULL);
4288 }
4289
4290 static MonoMethod*
4291 verification_exception (void)
4292 {
4293         static MonoMethod *method = NULL;
4294
4295         if (!method) {
4296                 MonoSecurityManager *secman = mono_security_manager_get_methods ();
4297                 method = mono_class_get_method_from_name (secman->securitymanager,
4298                                                           "VerificationException", 0);
4299         }
4300         g_assert (method);
4301         return method;
4302 }
4303
4304 static void
4305 emit_throw_verification_exception (MonoCompile *cfg, MonoBasicBlock *bblock, unsigned char *ip)
4306 {
4307         MonoMethod *thrower = verification_exception ();
4308
4309         mono_emit_method_call_spilled (cfg, bblock, thrower,
4310                 mono_method_signature (thrower),
4311                 NULL, ip, NULL);
4312 }
4313
4314 static void
4315 ensure_method_is_allowed_to_call_method (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee,
4316                                          MonoBasicBlock *bblock, unsigned char *ip)
4317 {
4318         MonoSecurityCoreCLRLevel caller_level = mono_security_core_clr_method_level (caller, TRUE);
4319         MonoSecurityCoreCLRLevel callee_level = mono_security_core_clr_method_level (callee, TRUE);
4320         gboolean is_safe = TRUE;
4321
4322         if (!(caller_level >= callee_level ||
4323                         caller_level == MONO_SECURITY_CORE_CLR_SAFE_CRITICAL ||
4324                         callee_level == MONO_SECURITY_CORE_CLR_SAFE_CRITICAL)) {
4325                 is_safe = FALSE;
4326         }
4327
4328         if (!is_safe)
4329                 emit_throw_method_access_exception (cfg, caller, callee, bblock, ip);
4330 }
4331
4332 static gboolean
4333 method_is_safe (MonoMethod *method)
4334 {
4335         /*
4336         if (strcmp (method->name, "unsafeMethod") == 0)
4337                 return FALSE;
4338         */
4339         return TRUE;
4340 }
4341
4342 /*
4343  * Check that the IL instructions at ip are the array initialization
4344  * sequence and return the pointer to the data and the size.
4345  */
4346 static const char*
4347 initialize_array_data (MonoMethod *method, gboolean aot, unsigned char *ip, MonoInst *newarr, int *out_size)
4348 {
4349         /*
4350          * newarr[System.Int32]
4351          * dup
4352          * ldtoken field valuetype ...
4353          * call void class [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class [mscorlib]System.Array, valuetype [mscorlib]System.RuntimeFieldHandle)
4354          */
4355         if (ip [0] == CEE_DUP && ip [1] == CEE_LDTOKEN && ip [5] == 0x4 && ip [6] == CEE_CALL) {
4356                 MonoClass *klass = newarr->inst_newa_class;
4357                 guint32 field_token = read32 (ip + 2);
4358                 guint32 field_index = field_token & 0xffffff;
4359                 guint32 token = read32 (ip + 7);
4360                 guint32 rva;
4361                 const char *data_ptr;
4362                 int size = 0;
4363                 MonoMethod *cmethod;
4364                 MonoClass *dummy_class;
4365                 MonoClassField *field = mono_field_from_token (method->klass->image, field_token, &dummy_class, NULL);
4366                 int dummy_align;
4367
4368                 if (!field)
4369                         return NULL;
4370
4371                 if (newarr->inst_newa_len->opcode != OP_ICONST)
4372                         return NULL;
4373                 cmethod = mini_get_method (NULL, method, token, NULL, NULL);
4374                 if (!cmethod)
4375                         return NULL;
4376                 if (strcmp (cmethod->name, "InitializeArray") || strcmp (cmethod->klass->name, "RuntimeHelpers") || cmethod->klass->image != mono_defaults.corlib)
4377                         return NULL;
4378                 switch (mono_type_get_underlying_type (&klass->byval_arg)->type) {
4379                 case MONO_TYPE_BOOLEAN:
4380                 case MONO_TYPE_I1:
4381                 case MONO_TYPE_U1:
4382                         size = 1; break;
4383                 /* we need to swap on big endian, so punt. Should we handle R4 and R8 as well? */
4384 #if G_BYTE_ORDER == G_LITTLE_ENDIAN
4385                 case MONO_TYPE_CHAR:
4386                 case MONO_TYPE_I2:
4387                 case MONO_TYPE_U2:
4388                         size = 2; break;
4389                 case MONO_TYPE_I4:
4390                 case MONO_TYPE_U4:
4391                 case MONO_TYPE_R4:
4392                         size = 4; break;
4393                 case MONO_TYPE_R8:
4394 #ifdef ARM_FPU_FPA
4395                         return NULL; /* stupid ARM FP swapped format */
4396 #endif
4397                 case MONO_TYPE_I8:
4398                 case MONO_TYPE_U8:
4399                         size = 8; break;
4400 #endif
4401                 default:
4402                         return NULL;
4403                 }
4404                 size *= newarr->inst_newa_len->inst_c0;
4405                 if (size > mono_type_size (field->type, &dummy_align))
4406                     return NULL;
4407                 *out_size = size;
4408                 /*g_print ("optimized in %s: size: %d, numelems: %d\n", method->name, size, newarr->inst_newa_len->inst_c0);*/
4409                 field_index = read32 (ip + 2) & 0xffffff;
4410                 mono_metadata_field_info (method->klass->image, field_index - 1, NULL, &rva, NULL);
4411                 data_ptr = mono_image_rva_map (method->klass->image, rva);
4412                 /*g_print ("field: 0x%08x, rva: %d, rva_ptr: %p\n", read32 (ip + 2), rva, data_ptr);*/
4413                 /* for aot code we do the lookup on load */
4414                 if (aot && data_ptr)
4415                         return GUINT_TO_POINTER (rva);
4416                 return data_ptr;
4417         }
4418         return NULL;
4419 }
4420
4421 static void
4422 set_exception_type_from_invalid_il (MonoCompile *cfg, MonoMethod *method, unsigned char *ip)
4423 {
4424         char *method_fname = mono_method_full_name (method, TRUE);
4425         char *method_code;
4426
4427         if (mono_method_get_header (method)->code_size == 0)
4428                 method_code = g_strdup ("method body is empty.");
4429         else
4430                 method_code = mono_disasm_code_one (NULL, method, ip, NULL);
4431         cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
4432         cfg->exception_message = g_strdup_printf ("Invalid IL code in %s: %s\n", method_fname, method_code);
4433         g_free (method_fname);
4434         g_free (method_code);
4435 }
4436
4437 static MonoInst*
4438 get_runtime_generic_context (MonoCompile *cfg, MonoMethod *method, int context_used, MonoInst *this, unsigned char *ip)
4439 {
4440         g_assert (!method->klass->valuetype);
4441
4442         if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD) {
4443                 MonoInst *mrgctx_loc, *mrgctx_var;
4444
4445                 g_assert (!this);
4446                 g_assert (method->is_inflated && mono_method_get_context (method)->method_inst);
4447
4448                 mrgctx_loc = mono_get_vtable_var (cfg);
4449                 NEW_TEMPLOAD (cfg, mrgctx_var, mrgctx_loc->inst_c0);
4450
4451                 return mrgctx_var;
4452         } else if (method->flags & METHOD_ATTRIBUTE_STATIC) {
4453                 MonoInst *vtable_loc, *vtable_var;
4454
4455                 g_assert (!this);
4456
4457                 vtable_loc = mono_get_vtable_var (cfg);
4458                 NEW_TEMPLOAD (cfg, vtable_var, vtable_loc->inst_c0);
4459
4460                 if (method->is_inflated && mono_method_get_context (method)->method_inst) {
4461                         MonoInst *mrgctx_var = vtable_var;
4462
4463                         g_assert (G_STRUCT_OFFSET (MonoMethodRuntimeGenericContext, class_vtable) == 0);
4464
4465                         MONO_INST_NEW (cfg, vtable_var, CEE_LDIND_I);
4466                         vtable_var->cil_code = ip;
4467                         vtable_var->inst_left = mrgctx_var;
4468                         vtable_var->type = STACK_PTR;
4469                 }
4470
4471                 return vtable_var;
4472         } else {
4473                 MonoInst *vtable;
4474
4475                 g_assert (this);
4476
4477                 MONO_INST_NEW (cfg, vtable, CEE_LDIND_I);
4478                 vtable->inst_left = this;
4479                 vtable->type = STACK_PTR;
4480
4481                 return vtable;
4482         }
4483 }
4484
4485 static gpointer
4486 create_rgctx_lazy_fetch_trampoline (guint32 offset)
4487 {
4488         static gboolean inited = FALSE;
4489         static int num_trampolines = 0;
4490
4491         gpointer tramp, ptr;
4492
4493         mono_jit_lock ();
4494         if (rgctx_lazy_fetch_trampoline_hash)
4495                 tramp = g_hash_table_lookup (rgctx_lazy_fetch_trampoline_hash, GUINT_TO_POINTER (offset));
4496         else
4497                 tramp = NULL;
4498         mono_jit_unlock ();
4499         if (tramp)
4500                 return tramp;
4501
4502         tramp = mono_arch_create_rgctx_lazy_fetch_trampoline (offset);
4503         ptr = mono_create_ftnptr (mono_get_root_domain (), tramp);
4504
4505         mono_jit_lock ();
4506         if (!rgctx_lazy_fetch_trampoline_hash)
4507                 rgctx_lazy_fetch_trampoline_hash = g_hash_table_new (NULL, NULL);
4508         g_hash_table_insert (rgctx_lazy_fetch_trampoline_hash, GUINT_TO_POINTER (offset), ptr);
4509         mono_jit_unlock ();
4510
4511         if (!inited) {
4512                 mono_counters_register ("RGCTX num lazy fetch trampolines",
4513                                 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &num_trampolines);
4514                 inited = TRUE;
4515         }
4516         num_trampolines++;
4517
4518         return ptr;
4519 }
4520
4521 static MonoInst*
4522 get_runtime_generic_context_other_table_ptr (MonoCompile *cfg, MonoBasicBlock *bblock,
4523         MonoInst *rgc_ptr, guint32 slot, const unsigned char *ip)
4524 {
4525         MonoMethodSignature *sig = helper_sig_rgctx_lazy_fetch_trampoline;
4526         guint8 *tramp = create_rgctx_lazy_fetch_trampoline (slot);
4527         int temp;
4528         MonoInst *field;
4529
4530         temp = mono_emit_native_call (cfg, bblock, tramp, sig, &rgc_ptr, ip, FALSE, FALSE);
4531
4532         NEW_TEMPLOAD (cfg, field, temp);
4533
4534         return field;
4535 }
4536
4537 static MonoInst*
4538 get_runtime_generic_context_ptr (MonoCompile *cfg, MonoMethod *method, int context_used, MonoBasicBlock *bblock,
4539         MonoClass *klass, MonoGenericContext *generic_context, MonoInst *rgctx, int rgctx_type, unsigned char *ip)
4540 {
4541         guint32 slot = mono_method_lookup_or_register_other_info (method,
4542                 context_used & MONO_GENERIC_CONTEXT_USED_METHOD, &klass->byval_arg, rgctx_type, generic_context);
4543
4544         return get_runtime_generic_context_other_table_ptr (cfg, bblock, rgctx, slot, ip);
4545 }
4546
4547 static MonoInst*
4548 get_runtime_generic_context_method (MonoCompile *cfg, MonoMethod *method, int context_used, MonoBasicBlock *bblock,
4549         MonoMethod *cmethod, MonoGenericContext *generic_context, MonoInst *rgctx, int rgctx_type, const unsigned char *ip)
4550 {
4551         guint32 slot = mono_method_lookup_or_register_other_info (method,
4552                 context_used & MONO_GENERIC_CONTEXT_USED_METHOD, cmethod, rgctx_type, generic_context);
4553
4554         return get_runtime_generic_context_other_table_ptr (cfg, bblock, rgctx, slot, ip);
4555 }
4556
4557 static MonoInst*
4558 get_runtime_generic_context_field (MonoCompile *cfg, MonoMethod *method, int context_used, MonoBasicBlock *bblock,
4559         MonoClassField *field, MonoGenericContext *generic_context, MonoInst *rgctx, int rgctx_type,
4560         const unsigned char *ip)
4561 {
4562         guint32 slot = mono_method_lookup_or_register_other_info (method,
4563                 context_used & MONO_GENERIC_CONTEXT_USED_METHOD, field, rgctx_type, generic_context);
4564
4565         return get_runtime_generic_context_other_table_ptr (cfg, bblock, rgctx, slot, ip);
4566 }
4567
4568 static MonoInst*
4569 get_runtime_generic_context_method_rgctx (MonoCompile *cfg, MonoMethod *method, int context_used, MonoBasicBlock *bblock,
4570         MonoMethod *rgctx_method, MonoGenericContext *generic_context, MonoInst *rgctx, const unsigned char *ip)
4571 {
4572         guint32 slot = mono_method_lookup_or_register_other_info (method,
4573                 context_used & MONO_GENERIC_CONTEXT_USED_METHOD, rgctx_method,
4574                 MONO_RGCTX_INFO_METHOD_RGCTX, generic_context);
4575
4576         return get_runtime_generic_context_other_table_ptr (cfg, bblock, rgctx, slot, ip);
4577 }
4578
4579 static gboolean
4580 generic_class_is_reference_type (MonoCompile *cfg, MonoClass *klass)
4581 {
4582         MonoType *type;
4583
4584         if (cfg->generic_sharing_context)
4585                 type = mini_get_basic_type_from_generic (cfg->generic_sharing_context, &klass->byval_arg);
4586         else
4587                 type = &klass->byval_arg;
4588         return MONO_TYPE_IS_REFERENCE (type);
4589 }
4590
4591 /**
4592  * Handles unbox of a Nullable<T>, returning a temp variable where the
4593  * result is stored.  If a rgctx is passed, then shared generic code
4594  * is generated.
4595  */
4596 static int
4597 handle_unbox_nullable (MonoCompile* cfg, MonoMethod *caller_method, int context_used, MonoBasicBlock* bblock,
4598         MonoInst* val, const guchar *ip, MonoClass* klass, MonoGenericContext *generic_context, MonoInst *rgctx)
4599 {
4600         MonoMethod* method = mono_class_get_method_from_name (klass, "Unbox", 1);
4601         MonoMethodSignature *signature = mono_method_signature (method);
4602
4603         if (rgctx) {
4604                 MonoInst *addr = get_runtime_generic_context_method (cfg, caller_method, context_used, bblock, method,
4605                         generic_context, rgctx, MONO_RGCTX_INFO_GENERIC_METHOD_CODE, ip);
4606
4607                 return mono_emit_rgctx_calli_spilled (cfg, bblock, signature, &val, addr, NULL, ip);
4608         } else {
4609                 return mono_emit_method_call_spilled (cfg, bblock, method, signature, &val, ip, NULL);
4610         }
4611 }
4612
4613 static MonoInst*
4614 handle_box_nullable_from_inst (MonoCompile *cfg, MonoMethod *caller_method, int context_used, MonoBasicBlock *bblock,
4615         MonoInst *val, const guchar *ip, MonoClass *klass, MonoGenericContext *generic_context, MonoInst *rgctx)
4616 {
4617         MonoMethod* method = mono_class_get_method_from_name (klass, "Box", 1);
4618         MonoInst *dest, *method_addr;
4619         int temp;
4620
4621         g_assert (mono_class_is_nullable (klass));
4622
4623         method_addr = get_runtime_generic_context_method (cfg, caller_method, context_used, bblock, method,
4624                         generic_context, rgctx, MONO_RGCTX_INFO_GENERIC_METHOD_CODE, ip);
4625         temp = mono_emit_rgctx_calli_spilled (cfg, bblock, mono_method_signature (method), &val,
4626                         method_addr, NULL, ip);
4627         NEW_TEMPLOAD (cfg, dest, temp);
4628         return dest;
4629 }
4630
4631 static MonoObject*
4632 mono_object_castclass (MonoObject *obj, MonoClass *klass)
4633 {
4634         if (!obj)
4635                 return NULL;
4636
4637         if (mono_object_isinst (obj, klass))
4638                 return obj;
4639
4640         mono_raise_exception (mono_exception_from_name (mono_defaults.corlib,
4641                                         "System", "InvalidCastException"));
4642
4643         return NULL;
4644 }
4645
4646 static int
4647 emit_castclass (MonoClass *klass, guint32 token, int context_used, gboolean inst_is_castclass, MonoCompile *cfg,
4648                 MonoMethod *method, MonoInst **arg_array, MonoType **param_types, GList *dont_inline,
4649                 unsigned char *end, MonoMethodHeader *header, MonoGenericContext *generic_context,
4650                 MonoBasicBlock **_bblock, unsigned char **_ip, MonoInst ***_sp, int *_inline_costs, guint *_real_offset)
4651 {
4652         MonoBasicBlock *bblock = *_bblock;
4653         unsigned char *ip = *_ip;
4654         MonoInst **sp = *_sp;
4655         int inline_costs = *_inline_costs;
4656         guint real_offset = *_real_offset;
4657         int return_value = 0;
4658
4659         if (context_used) {
4660                 MonoInst *rgctx, *args [2];
4661                 int temp;
4662
4663                 g_assert (!method->klass->valuetype);
4664
4665                 /* obj */
4666                 args [0] = *sp;
4667
4668                 /* klass */
4669                 GET_RGCTX (rgctx, context_used);
4670                 args [1] = get_runtime_generic_context_ptr (cfg, method, context_used, bblock, klass,
4671                                 generic_context, rgctx, MONO_RGCTX_INFO_KLASS, ip);
4672
4673                 temp = mono_emit_jit_icall (cfg, bblock, mono_object_castclass, args, ip);
4674                 NEW_TEMPLOAD (cfg, *sp, temp);
4675
4676                 sp++;
4677                 ip += 5;
4678                 inline_costs += 2;
4679         } else if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
4680
4681                 MonoMethod *mono_castclass;
4682                 MonoInst *iargs [1];
4683                 MonoBasicBlock *ebblock;
4684                 int costs;
4685                 int temp;
4686
4687                 mono_castclass = mono_marshal_get_castclass (klass);
4688                 iargs [0] = sp [0];
4689
4690                 costs = inline_method (cfg, mono_castclass, mono_method_signature (mono_castclass), bblock,
4691                                 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
4692
4693                 g_assert (costs > 0);
4694
4695                 ip += 5;
4696                 real_offset += 5;
4697
4698                 GET_BBLOCK (cfg, bblock, ip);
4699                 ebblock->next_bb = bblock;
4700                 link_bblock (cfg, ebblock, bblock);
4701
4702                 temp = iargs [0]->inst_i0->inst_c0;
4703                 NEW_TEMPLOAD (cfg, *sp, temp);
4704
4705                 sp++;
4706                 bblock = ebblock;
4707                 inline_costs += costs;
4708         } else {
4709                 MonoInst *ins;
4710
4711                 /* Needed by the code generated in inssel.brg */
4712                 mono_get_got_var (cfg);
4713
4714                 MONO_INST_NEW (cfg, ins, CEE_CASTCLASS);
4715                 ins->type = STACK_OBJ;
4716                 ins->inst_left = *sp;
4717                 ins->klass = klass;
4718                 ins->inst_newa_class = klass;
4719                 if (inst_is_castclass)
4720                         ins->backend.record_cast_details = debug_options.better_cast_details;
4721                 if (inst_is_castclass)
4722                         *sp++ = emit_tree (cfg, bblock, ins, ip + 5);
4723                 else
4724                         *sp++ = ins;
4725                 ip += 5;
4726         }
4727
4728 do_return:
4729         *_bblock = bblock;
4730         *_ip = ip;
4731         *_sp = sp;
4732         *_inline_costs = inline_costs;
4733         *_real_offset = real_offset;
4734         return return_value;
4735 exception_exit:
4736         return_value = -2;
4737         goto do_return;
4738 unverified:
4739         return_value = -1;
4740         goto do_return;
4741 }
4742
4743 static int
4744 emit_unbox (MonoClass *klass, guint32 token, int context_used,
4745                 MonoCompile *cfg, MonoMethod *method, MonoInst **arg_array, MonoType **param_types, GList *dont_inline,
4746                 unsigned char *end, MonoMethodHeader *header, MonoGenericContext *generic_context,
4747                 MonoBasicBlock **_bblock, unsigned char **_ip, MonoInst ***_sp, int *_inline_costs, guint *_real_offset)
4748 {
4749         MonoBasicBlock *bblock = *_bblock;
4750         unsigned char *ip = *_ip;
4751         MonoInst **sp = *_sp;
4752         int inline_costs = *_inline_costs;
4753         guint real_offset = *_real_offset;
4754         int return_value = 0;
4755
4756         MonoInst *add, *vtoffset, *ins;
4757
4758         /* Needed by the code generated in inssel.brg */
4759         mono_get_got_var (cfg);
4760
4761         if (context_used) {
4762                 MonoInst *rgctx, *element_class;
4763
4764                 /* This assertion is from the unboxcast insn */
4765                 g_assert (klass->rank == 0);
4766
4767                 GET_RGCTX (rgctx, context_used);
4768                 element_class = get_runtime_generic_context_ptr (cfg, method, context_used, bblock,
4769                                 klass->element_class, generic_context, rgctx, MONO_RGCTX_INFO_KLASS, ip);
4770
4771                 MONO_INST_NEW (cfg, ins, OP_UNBOXCAST_REG);
4772                 ins->type = STACK_OBJ;
4773                 ins->inst_left = *sp;
4774                 ins->inst_right = element_class;
4775                 ins->klass = klass;
4776                 ins->cil_code = ip;
4777         } else {
4778                 MONO_INST_NEW (cfg, ins, OP_UNBOXCAST);
4779                 ins->type = STACK_OBJ;
4780                 ins->inst_left = *sp;
4781                 ins->klass = klass;
4782                 ins->inst_newa_class = klass;
4783                 ins->cil_code = ip;
4784         }
4785
4786         MONO_INST_NEW (cfg, add, OP_PADD);
4787         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
4788         add->inst_left = ins;
4789         add->inst_right = vtoffset;
4790         add->type = STACK_MP;
4791         add->klass = klass;
4792         *sp = add;
4793
4794 do_return:
4795         *_bblock = bblock;
4796         *_ip = ip;
4797         *_sp = sp;
4798         *_inline_costs = inline_costs;
4799         *_real_offset = real_offset;
4800         return return_value;
4801 exception_exit:
4802         return_value = -2;
4803         goto do_return;
4804 }
4805
4806 static gboolean
4807 mini_assembly_can_skip_verification (MonoDomain *domain, MonoMethod *method)
4808 {
4809         MonoAssembly *assembly = method->klass->image->assembly;
4810         if (method->wrapper_type != MONO_WRAPPER_NONE)
4811                 return FALSE;
4812         if (assembly->in_gac || assembly->image == mono_defaults.corlib)
4813                 return FALSE;
4814         if (mono_security_get_mode () != MONO_SECURITY_MODE_NONE)
4815                 return FALSE;
4816         return mono_assembly_has_skip_verification (assembly);
4817 }
4818
4819 /*
4820  * mini_method_verify:
4821  * 
4822  * Verify the method using the new verfier.
4823  * 
4824  * Returns true if the method is invalid. 
4825  */
4826 static gboolean
4827 mini_method_verify (MonoCompile *cfg, MonoMethod *method)
4828 {
4829         GSList *tmp, *res;
4830         gboolean is_fulltrust;
4831         MonoLoaderError *error;
4832
4833         if (method->verification_success)
4834                 return FALSE;
4835
4836         is_fulltrust = mono_verifier_is_method_full_trust (method);
4837
4838         if (!mono_verifier_is_enabled_for_method (method))
4839                 return FALSE;
4840
4841         res = mono_method_verify_with_current_settings (method, cfg->skip_visibility);
4842
4843         if ((error = mono_loader_get_last_error ())) {
4844                 cfg->exception_type = error->exception_type;
4845                 if (res)
4846                         mono_free_verify_list (res);
4847                 return TRUE;
4848         }
4849
4850         if (res) { 
4851                 for (tmp = res; tmp; tmp = tmp->next) {
4852                         MonoVerifyInfoExtended *info = (MonoVerifyInfoExtended *)tmp->data;
4853                         if (info->info.status == MONO_VERIFY_ERROR) {
4854                                 cfg->exception_type = info->exception_type;
4855                                 cfg->exception_message = g_strdup (info->info.message);
4856                                 mono_free_verify_list (res);
4857                                 return TRUE;
4858                         }
4859                         if (info->info.status == MONO_VERIFY_NOT_VERIFIABLE && !is_fulltrust) {
4860                                 cfg->exception_type = info->exception_type;
4861                                 cfg->exception_message = g_strdup (info->info.message);
4862                                 mono_free_verify_list (res);
4863                                 return TRUE;
4864                         }
4865                 }
4866                 mono_free_verify_list (res);
4867         }
4868         method->verification_success = 1;
4869         return FALSE;
4870 }
4871
4872 /*
4873  * mono_method_to_ir: translates IL into basic blocks containing trees
4874  */
4875 static int
4876 mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
4877                    int locals_offset, MonoInst *return_var, GList *dont_inline, MonoInst **inline_args, 
4878                    guint inline_offset, gboolean is_virtual_call)
4879 {
4880         MonoInst *zero_int32, *zero_int64, *zero_ptr, *zero_obj, *zero_r8;
4881         MonoInst *ins, **sp, **stack_start;
4882         MonoBasicBlock *bblock, *tblock = NULL, *init_localsbb = NULL;
4883         MonoMethod *cmethod, *method_definition;
4884         MonoInst **arg_array;
4885         MonoMethodHeader *header;
4886         MonoImage *image;
4887         guint32 token, ins_flag;
4888         MonoClass *klass;
4889         MonoClass *constrained_call = NULL;
4890         unsigned char *ip, *end, *target, *err_pos;
4891         static double r8_0 = 0.0;
4892         MonoMethodSignature *sig;
4893         MonoGenericContext *generic_context = NULL;
4894         MonoGenericContainer *generic_container = NULL;
4895         MonoType **param_types;
4896         GList *bb_recheck = NULL, *tmp;
4897         int i, n, start_new_bblock, ialign;
4898         int num_calls = 0, inline_costs = 0;
4899         int breakpoint_id = 0;
4900         guint32 align;
4901         guint real_offset, num_args;
4902         MonoBoolean security, pinvoke;
4903         MonoSecurityManager* secman = NULL;
4904         MonoDeclSecurityActions actions;
4905         GSList *class_inits = NULL;
4906         gboolean dont_verify, dont_verify_stloc, readonly = FALSE;
4907         int context_used;
4908
4909         /* serialization and xdomain stuff may need access to private fields and methods */
4910         dont_verify = method->klass->image->assembly->corlib_internal? TRUE: FALSE;
4911         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE;
4912         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH;
4913         dont_verify |= method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE; /* bug #77896 */
4914         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP;
4915         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP_INVOKE;
4916
4917         /* turn off visibility checks for smcs */
4918         dont_verify |= mono_security_get_mode () == MONO_SECURITY_MODE_SMCS_HACK;
4919
4920         /* still some type unsafety issues in marshal wrappers... (unknown is PtrToStructure) */
4921         dont_verify_stloc = method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE;
4922         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_UNKNOWN;
4923         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED;
4924
4925         image = method->klass->image;
4926         header = mono_method_get_header (method);
4927         generic_container = mono_method_get_generic_container (method);
4928         sig = mono_method_signature (method);
4929         num_args = sig->hasthis + sig->param_count;
4930         ip = (unsigned char*)header->code;
4931         cfg->cil_start = ip;
4932         end = ip + header->code_size;
4933         mono_jit_stats.cil_code_size += header->code_size;
4934
4935         method_definition = method;
4936         while (method_definition->is_inflated) {
4937                 MonoMethodInflated *imethod = (MonoMethodInflated *) method_definition;
4938                 method_definition = imethod->declaring;
4939         }
4940
4941         /* SkipVerification is not allowed if core-clr is enabled */
4942         if (!dont_verify && mini_assembly_can_skip_verification (cfg->domain, method)) {
4943                 dont_verify = TRUE;
4944                 dont_verify_stloc = TRUE;
4945         }
4946
4947         if (!dont_verify && mini_method_verify (cfg, method_definition))
4948                 goto exception_exit;
4949
4950         if (sig->is_inflated)
4951                 generic_context = mono_method_get_context (method);
4952         else if (generic_container)
4953                 generic_context = &generic_container->context;
4954
4955         if (!cfg->generic_sharing_context)
4956                 g_assert (!sig->has_type_parameters);
4957
4958         if (sig->generic_param_count && method->wrapper_type == MONO_WRAPPER_NONE) {
4959                 g_assert (method->is_inflated);
4960                 g_assert (mono_method_get_context (method)->method_inst);
4961         }
4962         if (method->is_inflated && mono_method_get_context (method)->method_inst)
4963                 g_assert (sig->generic_param_count);
4964
4965         if (cfg->method == method)
4966                 real_offset = 0;
4967         else
4968                 real_offset = inline_offset;
4969
4970         cfg->cil_offset_to_bb = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoBasicBlock*) * header->code_size);
4971         cfg->cil_offset_to_bb_len = header->code_size;
4972
4973         if (cfg->verbose_level > 2)
4974                 g_print ("method to IR %s\n", mono_method_full_name (method, TRUE));
4975
4976         dont_inline = g_list_prepend (dont_inline, method);
4977         if (cfg->method == method) {
4978
4979                 if (cfg->prof_options & MONO_PROFILE_INS_COVERAGE)
4980                         cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, header->code_size);
4981
4982                 /* ENTRY BLOCK */
4983                 NEW_BBLOCK (cfg, start_bblock);
4984                 cfg->bb_entry = start_bblock;
4985                 start_bblock->cil_code = NULL;
4986                 start_bblock->cil_length = 0;
4987                 start_bblock->block_num = cfg->num_bblocks++;
4988
4989                 /* EXIT BLOCK */
4990                 NEW_BBLOCK (cfg, end_bblock);
4991                 cfg->bb_exit = end_bblock;
4992                 end_bblock->cil_code = NULL;
4993                 end_bblock->cil_length = 0;
4994                 end_bblock->block_num = cfg->num_bblocks++;
4995                 g_assert (cfg->num_bblocks == 2);
4996
4997                 arg_array = alloca (sizeof (MonoInst *) * num_args);
4998                 for (i = num_args - 1; i >= 0; i--)
4999                         arg_array [i] = cfg->varinfo [i];
5000
5001                 if (header->num_clauses) {
5002                         cfg->spvars = g_hash_table_new (NULL, NULL);
5003                         cfg->exvars = g_hash_table_new (NULL, NULL);
5004                 }
5005                 /* handle exception clauses */
5006                 for (i = 0; i < header->num_clauses; ++i) {
5007                         MonoBasicBlock *try_bb;
5008                         MonoExceptionClause *clause = &header->clauses [i];
5009
5010                         GET_BBLOCK (cfg, try_bb, ip + clause->try_offset);
5011                         try_bb->real_offset = clause->try_offset;
5012                         GET_BBLOCK (cfg, tblock, ip + clause->handler_offset);
5013                         tblock->real_offset = clause->handler_offset;
5014                         tblock->flags |= BB_EXCEPTION_HANDLER;
5015
5016                         link_bblock (cfg, try_bb, tblock);
5017
5018                         if (*(ip + clause->handler_offset) == CEE_POP)
5019                                 tblock->flags |= BB_EXCEPTION_DEAD_OBJ;
5020
5021                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY ||
5022                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER ||
5023                             clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) {
5024                                 MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
5025                                 MONO_ADD_INS (tblock, ins);
5026
5027                                 /* todo: is a fault block unsafe to optimize? */
5028                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
5029                                         tblock->flags |= BB_EXCEPTION_UNSAFE;
5030                         }
5031
5032
5033                         /*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);
5034                           while (p < end) {
5035                           g_print ("%s", mono_disasm_code_one (NULL, method, p, &p));
5036                           }*/
5037                         /* catch and filter blocks get the exception object on the stack */
5038                         if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE ||
5039                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
5040                                 MonoInst *load, *dummy_use;
5041
5042                                 /* mostly like handle_stack_args (), but just sets the input args */
5043                                 /* g_print ("handling clause at IL_%04x\n", clause->handler_offset); */
5044                                 tblock->in_scount = 1;
5045                                 tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
5046                                 tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
5047
5048                                 /* 
5049                                  * Add a dummy use for the exvar so its liveness info will be
5050                                  * correct.
5051                                  */
5052                                 NEW_TEMPLOAD (cfg, load, tblock->in_stack [0]->inst_c0);
5053                                 NEW_DUMMY_USE (cfg, dummy_use, load);
5054                                 MONO_ADD_INS (tblock, dummy_use);
5055                                 
5056                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
5057                                         GET_BBLOCK (cfg, tblock, ip + clause->data.filter_offset);
5058                                         tblock->real_offset = clause->data.filter_offset;
5059                                         tblock->in_scount = 1;
5060                                         tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
5061                                         /* The filter block shares the exvar with the handler block */
5062                                         tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
5063                                         MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
5064                                         MONO_ADD_INS (tblock, ins);
5065                                 }
5066                         }
5067
5068                         if (clause->flags != MONO_EXCEPTION_CLAUSE_FILTER &&
5069                                         clause->data.catch_class &&
5070                                         cfg->generic_sharing_context &&
5071                                         mono_class_check_context_used (clause->data.catch_class)) {
5072                                 if (mono_method_get_context (method)->method_inst)
5073                                         GENERIC_SHARING_FAILURE (CEE_NOP);
5074
5075                                 /*
5076                                  * In shared generic code with catch
5077                                  * clauses containing type variables
5078                                  * the exception handling code has to
5079                                  * be able to get to the rgctx.
5080                                  * Therefore we have to make sure that
5081                                  * the vtable/mrgctx argument (for
5082                                  * static or generic methods) or the
5083                                  * "this" argument (for non-static
5084                                  * methods) are live.
5085                                  */
5086                                 if ((method->flags & METHOD_ATTRIBUTE_STATIC) ||
5087                                                 mini_method_get_context (method)->method_inst) {
5088                                         mono_get_vtable_var (cfg);
5089                                 } else {
5090                                         MonoInst *this, *dummy_use;
5091                                         MonoType *this_type;
5092
5093                                         if (method->klass->valuetype)
5094                                                 this_type = &method->klass->this_arg;
5095                                         else
5096                                                 this_type = &method->klass->byval_arg;
5097
5098                                         if (arg_array [0]->opcode == OP_ICONST) {
5099                                                 this = arg_array [0];
5100                                         } else {
5101                                                 this = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));
5102                                                 this->ssa_op = MONO_SSA_LOAD;
5103                                                 this->inst_i0 = arg_array [0];
5104                                                 this->opcode = mini_type_to_ldind ((cfg), this->inst_i0->inst_vtype);
5105                                                 type_to_eval_stack_type ((cfg), this_type, this);
5106                                                 this->klass = this->inst_i0->klass;
5107                                         }
5108
5109                                         NEW_DUMMY_USE (cfg, dummy_use, this);
5110                                         MONO_ADD_INS (tblock, dummy_use);
5111                                 }
5112                         }
5113                 }
5114         } else {
5115                 arg_array = alloca (sizeof (MonoInst *) * num_args);
5116                 mono_save_args (cfg, start_bblock, sig, inline_args, arg_array);
5117         }
5118
5119         /* FIRST CODE BLOCK */
5120         NEW_BBLOCK (cfg, bblock);
5121         bblock->cil_code = ip;
5122
5123         ADD_BBLOCK (cfg, bblock);
5124
5125         if (cfg->method == method) {
5126                 breakpoint_id = mono_debugger_method_has_breakpoint (method);
5127                 if (breakpoint_id && (mono_debug_format != MONO_DEBUG_FORMAT_DEBUGGER)) {
5128                         MONO_INST_NEW (cfg, ins, OP_BREAK);
5129                         MONO_ADD_INS (bblock, ins);
5130                 }
5131         }
5132
5133         if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS)
5134                 secman = mono_security_manager_get_methods ();
5135
5136         security = (secman && mono_method_has_declsec (method));
5137         /* at this point having security doesn't mean we have any code to generate */
5138         if (security && (cfg->method == method)) {
5139                 /* Only Demand, NonCasDemand and DemandChoice requires code generation.
5140                  * And we do not want to enter the next section (with allocation) if we
5141                  * have nothing to generate */
5142                 security = mono_declsec_get_demands (method, &actions);
5143         }
5144
5145         /* we must Demand SecurityPermission.Unmanaged before P/Invoking */
5146         pinvoke = (secman && (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE));
5147         if (pinvoke) {
5148                 MonoMethod *wrapped = mono_marshal_method_from_wrapper (method);
5149                 if (wrapped && (wrapped->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5150                         MonoCustomAttrInfo* custom = mono_custom_attrs_from_method (wrapped);
5151
5152                         /* unless the method or it's class has the [SuppressUnmanagedCodeSecurity] attribute */
5153                         if (custom && mono_custom_attrs_has_attr (custom, secman->suppressunmanagedcodesecurity)) {
5154                                 pinvoke = FALSE;
5155                         }
5156                         if (custom)
5157                                 mono_custom_attrs_free (custom);
5158
5159                         if (pinvoke) {
5160                                 custom = mono_custom_attrs_from_class (wrapped->klass);
5161                                 if (custom && mono_custom_attrs_has_attr (custom, secman->suppressunmanagedcodesecurity)) {
5162                                         pinvoke = FALSE;
5163                                 }
5164                                 if (custom)
5165                                         mono_custom_attrs_free (custom);
5166                         }
5167                 } else {
5168                         /* not a P/Invoke after all */
5169                         pinvoke = FALSE;
5170                 }
5171         }
5172         
5173         if ((header->init_locals || (cfg->method == method && (cfg->opt & MONO_OPT_SHARED))) || cfg->compile_aot || security || pinvoke) {
5174                 /* we use a separate basic block for the initialization code */
5175                 NEW_BBLOCK (cfg, init_localsbb);
5176                 cfg->bb_init = init_localsbb;
5177                 init_localsbb->real_offset = real_offset;
5178                 start_bblock->next_bb = init_localsbb;
5179                 init_localsbb->next_bb = bblock;
5180                 link_bblock (cfg, start_bblock, init_localsbb);
5181                 link_bblock (cfg, init_localsbb, bblock);
5182                 init_localsbb->block_num = cfg->num_bblocks++;
5183         } else {
5184                 start_bblock->next_bb = bblock;
5185                 link_bblock (cfg, start_bblock, bblock);
5186         }
5187
5188         /* at this point we know, if security is TRUE, that some code needs to be generated */
5189         if (security && (cfg->method == method)) {
5190                 MonoInst *args [2];
5191
5192                 mono_jit_stats.cas_demand_generation++;
5193
5194                 if (actions.demand.blob) {
5195                         /* Add code for SecurityAction.Demand */
5196                         NEW_DECLSECCONST (cfg, args[0], image, actions.demand);
5197                         NEW_ICONST (cfg, args [1], actions.demand.size);
5198                         /* Calls static void SecurityManager.InternalDemand (byte* permissions, int size); */
5199                         mono_emit_method_call_spilled (cfg, init_localsbb, secman->demand, mono_method_signature (secman->demand), args, ip, NULL);
5200                 }
5201                 if (actions.noncasdemand.blob) {
5202                         /* CLR 1.x uses a .noncasdemand (but 2.x doesn't) */
5203                         /* For Mono we re-route non-CAS Demand to Demand (as the managed code must deal with it anyway) */
5204                         NEW_DECLSECCONST (cfg, args[0], image, actions.noncasdemand);
5205                         NEW_ICONST (cfg, args [1], actions.noncasdemand.size);
5206                         /* Calls static void SecurityManager.InternalDemand (byte* permissions, int size); */
5207                         mono_emit_method_call_spilled (cfg, init_localsbb, secman->demand, mono_method_signature (secman->demand), args, ip, NULL);
5208                 }
5209                 if (actions.demandchoice.blob) {
5210                         /* New in 2.0, Demand must succeed for one of the permissions (i.e. not all) */
5211                         NEW_DECLSECCONST (cfg, args[0], image, actions.demandchoice);
5212                         NEW_ICONST (cfg, args [1], actions.demandchoice.size);
5213                         /* Calls static void SecurityManager.InternalDemandChoice (byte* permissions, int size); */
5214                         mono_emit_method_call_spilled (cfg, init_localsbb, secman->demandchoice, mono_method_signature (secman->demandchoice), args, ip, NULL);
5215                 }
5216         }
5217
5218         /* we must Demand SecurityPermission.Unmanaged before p/invoking */
5219         if (pinvoke) {
5220                 mono_emit_method_call_spilled (cfg, init_localsbb, secman->demandunmanaged, mono_method_signature (secman->demandunmanaged), NULL, ip, NULL);
5221         }
5222
5223         if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
5224                 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
5225                         MonoMethod *wrapped = mono_marshal_method_from_wrapper (method);
5226                         if (wrapped && (wrapped->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5227                                 if (!(method->klass && method->klass->image &&
5228                                                 mono_security_core_clr_is_platform_image (method->klass->image))) {
5229                                         emit_throw_method_access_exception (cfg, method, wrapped, bblock, ip);
5230                                 }
5231                         }
5232                 }
5233                 if (!method_is_safe (method))
5234                         emit_throw_verification_exception (cfg, bblock, ip);
5235         }
5236
5237         if (header->code_size == 0)
5238                 UNVERIFIED;
5239
5240         if (get_basic_blocks (cfg, header, real_offset, ip, end, &err_pos)) {
5241                 ip = err_pos;
5242                 UNVERIFIED;
5243         }
5244
5245         if (cfg->method == method)
5246                 mono_debug_init_method (cfg, bblock, breakpoint_id);
5247
5248         param_types = mono_mempool_alloc (cfg->mempool, sizeof (MonoType*) * num_args);
5249         if (sig->hasthis)
5250                 param_types [0] = method->klass->valuetype?&method->klass->this_arg:&method->klass->byval_arg;
5251         for (n = 0; n < sig->param_count; ++n)
5252                 param_types [n + sig->hasthis] = sig->params [n];
5253         for (n = 0; n < header->num_locals; ++n) {
5254                 if (header->locals [n]->type == MONO_TYPE_VOID && !header->locals [n]->byref)
5255                         UNVERIFIED;
5256         }
5257         class_inits = NULL;
5258
5259         /* do this somewhere outside - not here */
5260         NEW_ICONST (cfg, zero_int32, 0);
5261         NEW_ICONST (cfg, zero_int64, 0);
5262         zero_int64->type = STACK_I8;
5263         NEW_PCONST (cfg, zero_ptr, 0);
5264         NEW_PCONST (cfg, zero_obj, 0);
5265         zero_obj->type = STACK_OBJ;
5266
5267         MONO_INST_NEW (cfg, zero_r8, OP_R8CONST);
5268         zero_r8->type = STACK_R8;
5269         zero_r8->inst_p0 = &r8_0;
5270
5271         /* add a check for this != NULL to inlined methods */
5272         if (is_virtual_call) {
5273                 MONO_INST_NEW (cfg, ins, OP_CHECK_THIS);
5274                 NEW_ARGLOAD (cfg, ins->inst_left, 0);
5275                 ins->cil_code = ip;
5276                 MONO_ADD_INS (bblock, ins);
5277         }
5278
5279         /* we use a spare stack slot in SWITCH and NEWOBJ and others */
5280         stack_start = sp = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (header->max_stack + 1));
5281
5282         ins_flag = 0;
5283         start_new_bblock = 0;
5284         while (ip < end) {
5285
5286                 if (cfg->method == method)
5287                         real_offset = ip - header->code;
5288                 else
5289                         real_offset = inline_offset;
5290                 cfg->ip = ip;
5291
5292                 context_used = 0;
5293
5294                 if (start_new_bblock) {
5295                         bblock->cil_length = ip - bblock->cil_code;
5296                         if (start_new_bblock == 2) {
5297                                 g_assert (ip == tblock->cil_code);
5298                         } else {
5299                                 GET_BBLOCK (cfg, tblock, ip);
5300                         }
5301                         bblock->next_bb = tblock;
5302                         bblock = tblock;
5303                         start_new_bblock = 0;
5304                         for (i = 0; i < bblock->in_scount; ++i) {
5305                                 if (cfg->verbose_level > 3)
5306                                         g_print ("loading %d from temp %d\n", i, (int)bblock->in_stack [i]->inst_c0);                                           
5307                                 NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
5308                                 *sp++ = ins;
5309                         }
5310                         g_slist_free (class_inits);
5311                         class_inits = NULL;
5312                 } else {
5313                         if ((tblock = cfg->cil_offset_to_bb [ip - cfg->cil_start]) && (tblock != bblock)) {
5314                                 link_bblock (cfg, bblock, tblock);
5315                                 if (sp != stack_start) {
5316                                         handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5317                                         sp = stack_start;
5318                                         CHECK_UNVERIFIABLE (cfg);
5319                                 }
5320                                 bblock->next_bb = tblock;
5321                                 bblock = tblock;
5322                                 for (i = 0; i < bblock->in_scount; ++i) {
5323                                         if (cfg->verbose_level > 3)
5324                                                 g_print ("loading %d from temp %d\n", i, (int)bblock->in_stack [i]->inst_c0);                                           
5325                                         NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
5326                                         *sp++ = ins;
5327                                 }
5328                                 g_slist_free (class_inits);
5329                                 class_inits = NULL;
5330                         }
5331                 }
5332
5333                 bblock->real_offset = real_offset;
5334
5335                 if ((cfg->method == method) && cfg->coverage_info) {
5336                         MonoInst *store, *one;
5337                         guint32 cil_offset = ip - header->code;
5338                         cfg->coverage_info->data [cil_offset].cil_code = ip;
5339
5340                         /* TODO: Use an increment here */
5341                         NEW_ICONST (cfg, one, 1);
5342                         one->cil_code = ip;
5343
5344                         NEW_PCONST (cfg, ins, &(cfg->coverage_info->data [cil_offset].count));
5345                         ins->cil_code = ip;
5346
5347                         MONO_INST_NEW (cfg, store, CEE_STIND_I);
5348                         store->inst_left = ins;
5349                         store->inst_right = one;
5350
5351                         MONO_ADD_INS (bblock, store);
5352                 }
5353
5354                 if (cfg->verbose_level > 3)
5355                         g_print ("converting (in B%d: stack: %d) %s", bblock->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
5356
5357                 switch (*ip) {
5358                 case CEE_NOP:
5359                         MONO_INST_NEW (cfg, ins, OP_NOP);
5360                         ip++;
5361                         MONO_ADD_INS (bblock, ins);
5362                         break;
5363                 case CEE_BREAK:
5364                         MONO_INST_NEW (cfg, ins, OP_BREAK);
5365                         ip++;
5366                         MONO_ADD_INS (bblock, ins);
5367                         break;
5368                 case CEE_LDARG_0:
5369                 case CEE_LDARG_1:
5370                 case CEE_LDARG_2:
5371                 case CEE_LDARG_3:
5372                         CHECK_STACK_OVF (1);
5373                         n = (*ip)-CEE_LDARG_0;
5374                         CHECK_ARG (n);
5375                         NEW_ARGLOAD (cfg, ins, n);
5376                         LDARG_SOFT_FLOAT (cfg, ins, n, ip);
5377                         ip++;
5378                         *sp++ = ins;
5379                         break;
5380                 case CEE_LDLOC_0:
5381                 case CEE_LDLOC_1:
5382                 case CEE_LDLOC_2:
5383                 case CEE_LDLOC_3:
5384                         CHECK_STACK_OVF (1);
5385                         n = (*ip)-CEE_LDLOC_0;
5386                         CHECK_LOCAL (n);
5387                         NEW_LOCLOAD (cfg, ins, n);
5388                         LDLOC_SOFT_FLOAT (cfg, ins, n, ip);
5389                         ip++;
5390                         *sp++ = ins;
5391                         break;
5392                 case CEE_STLOC_0:
5393                 case CEE_STLOC_1:
5394                 case CEE_STLOC_2:
5395                 case CEE_STLOC_3:
5396                         CHECK_STACK (1);
5397                         n = (*ip)-CEE_STLOC_0;
5398                         CHECK_LOCAL (n);
5399                         --sp;
5400                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5401                         NEW_LOCSTORE (cfg, ins, n, *sp);
5402                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
5403                                 UNVERIFIED;
5404                         STLOC_SOFT_FLOAT (cfg, ins, n, ip);
5405                         if (ins->opcode == CEE_STOBJ) {
5406                                 NEW_LOCLOADA (cfg, ins, n);
5407                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
5408                         } else
5409                                 MONO_ADD_INS (bblock, ins);
5410                         ++ip;
5411                         inline_costs += 1;
5412                         break;
5413                 case CEE_LDARG_S:
5414                         CHECK_OPSIZE (2);
5415                         CHECK_STACK_OVF (1);
5416                         CHECK_ARG (ip [1]);
5417                         NEW_ARGLOAD (cfg, ins, ip [1]);
5418                         LDARG_SOFT_FLOAT (cfg, ins, ip [1], ip);
5419                         *sp++ = ins;
5420                         ip += 2;
5421                         break;
5422                 case CEE_LDARGA_S:
5423                         CHECK_OPSIZE (2);
5424                         CHECK_STACK_OVF (1);
5425                         CHECK_ARG (ip [1]);
5426                         NEW_ARGLOADA (cfg, ins, ip [1]);
5427                         *sp++ = ins;
5428                         ip += 2;
5429                         break;
5430                 case CEE_STARG_S:
5431                         CHECK_OPSIZE (2);
5432                         CHECK_STACK (1);
5433                         --sp;
5434                         CHECK_ARG (ip [1]);
5435                         NEW_ARGSTORE (cfg, ins, ip [1], *sp);
5436                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5437                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [ip [1]], *sp))
5438                                 UNVERIFIED;
5439                         STARG_SOFT_FLOAT (cfg, ins, ip [1], ip);
5440                         if (ins->opcode == CEE_STOBJ) {
5441                                 NEW_ARGLOADA (cfg, ins, ip [1]);
5442                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
5443                         } else
5444                                 MONO_ADD_INS (bblock, ins);
5445                         ip += 2;
5446                         break;
5447                 case CEE_LDLOC_S:
5448                         CHECK_OPSIZE (2);
5449                         CHECK_STACK_OVF (1);
5450                         CHECK_LOCAL (ip [1]);
5451                         NEW_LOCLOAD (cfg, ins, ip [1]);
5452                         LDLOC_SOFT_FLOAT (cfg, ins, ip [1], ip);
5453                         *sp++ = ins;
5454                         ip += 2;
5455                         break;
5456                 case CEE_LDLOCA_S:
5457                         CHECK_OPSIZE (2);
5458                         CHECK_STACK_OVF (1);
5459                         CHECK_LOCAL (ip [1]);
5460                         NEW_LOCLOADA (cfg, ins, ip [1]);
5461                         *sp++ = ins;
5462                         ip += 2;
5463                         break;
5464                 case CEE_STLOC_S:
5465                         CHECK_OPSIZE (2);
5466                         CHECK_STACK (1);
5467                         --sp;
5468                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5469                         CHECK_LOCAL (ip [1]);
5470                         NEW_LOCSTORE (cfg, ins, ip [1], *sp);
5471                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [ip [1]], *sp))
5472                                 UNVERIFIED;
5473                         STLOC_SOFT_FLOAT (cfg, ins, ip [1], ip);
5474                         if (ins->opcode == CEE_STOBJ) {
5475                                 NEW_LOCLOADA (cfg, ins, ip [1]);
5476                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
5477                         } else
5478                                 MONO_ADD_INS (bblock, ins);
5479                         ip += 2;
5480                         inline_costs += 1;
5481                         break;
5482                 case CEE_LDNULL:
5483                         CHECK_STACK_OVF (1);
5484                         NEW_PCONST (cfg, ins, NULL);
5485                         ins->type = STACK_OBJ;
5486                         ++ip;
5487                         *sp++ = ins;
5488                         break;
5489                 case CEE_LDC_I4_M1:
5490                         CHECK_STACK_OVF (1);
5491                         NEW_ICONST (cfg, ins, -1);
5492                         ++ip;
5493                         *sp++ = ins;
5494                         break;
5495                 case CEE_LDC_I4_0:
5496                 case CEE_LDC_I4_1:
5497                 case CEE_LDC_I4_2:
5498                 case CEE_LDC_I4_3:
5499                 case CEE_LDC_I4_4:
5500                 case CEE_LDC_I4_5:
5501                 case CEE_LDC_I4_6:
5502                 case CEE_LDC_I4_7:
5503                 case CEE_LDC_I4_8:
5504                         CHECK_STACK_OVF (1);
5505                         NEW_ICONST (cfg, ins, (*ip) - CEE_LDC_I4_0);
5506                         ++ip;
5507                         *sp++ = ins;
5508                         break;
5509                 case CEE_LDC_I4_S:
5510                         CHECK_OPSIZE (2);
5511                         CHECK_STACK_OVF (1);
5512                         ++ip;
5513                         NEW_ICONST (cfg, ins, *((signed char*)ip));
5514                         ++ip;
5515                         *sp++ = ins;
5516                         break;
5517                 case CEE_LDC_I4:
5518                         CHECK_OPSIZE (5);
5519                         CHECK_STACK_OVF (1);
5520                         NEW_ICONST (cfg, ins, (gint32)read32 (ip + 1));
5521                         ip += 5;
5522                         *sp++ = ins;
5523                         break;
5524                 case CEE_LDC_I8:
5525                         CHECK_OPSIZE (9);
5526                         CHECK_STACK_OVF (1);
5527                         MONO_INST_NEW (cfg, ins, OP_I8CONST);
5528                         ins->type = STACK_I8;
5529                         ++ip;
5530                         ins->inst_l = (gint64)read64 (ip);
5531                         ip += 8;
5532                         *sp++ = ins;
5533                         break;
5534                 case CEE_LDC_R4: {
5535                         float *f;
5536                         /* we should really allocate this only late in the compilation process */
5537                         mono_domain_lock (cfg->domain);
5538                         f = mono_mempool_alloc (cfg->domain->mp, sizeof (float));
5539                         mono_domain_unlock (cfg->domain);
5540                         CHECK_OPSIZE (5);
5541                         CHECK_STACK_OVF (1);
5542                         MONO_INST_NEW (cfg, ins, OP_R4CONST);
5543                         ins->type = STACK_R8;
5544                         ++ip;
5545                         readr4 (ip, f);
5546                         ins->inst_p0 = f;
5547
5548                         ip += 4;
5549                         *sp++ = ins;                    
5550                         break;
5551                 }
5552                 case CEE_LDC_R8: {
5553                         double *d;
5554                         mono_domain_lock (cfg->domain);
5555                         d = mono_mempool_alloc (cfg->domain->mp, sizeof (double));
5556                         mono_domain_unlock (cfg->domain);
5557                         CHECK_OPSIZE (9);
5558                         CHECK_STACK_OVF (1);
5559                         MONO_INST_NEW (cfg, ins, OP_R8CONST);
5560                         ins->type = STACK_R8;
5561                         ++ip;
5562                         readr8 (ip, d);
5563                         ins->inst_p0 = d;
5564
5565                         ip += 8;
5566                         *sp++ = ins;                    
5567                         break;
5568                 }
5569                 case CEE_DUP: {
5570                         MonoInst *temp, *store;
5571                         CHECK_STACK (1);
5572                         CHECK_STACK_OVF (1);
5573                         sp--;
5574                         ins = *sp;
5575                 
5576                         /* 
5577                          * small optimization: if the loaded value was from a local already,
5578                          * just load it twice.
5579                          */
5580                         if (ins->ssa_op == MONO_SSA_LOAD && 
5581                             (ins->inst_i0->opcode == OP_LOCAL || ins->inst_i0->opcode == OP_ARG)) {
5582                                 sp++;
5583                                 MONO_INST_NEW (cfg, temp, 0);
5584                                 *temp = *ins;
5585                                 *sp++ = temp;
5586                         } else {
5587                                 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
5588                                 temp->flags |= MONO_INST_IS_TEMP;
5589                                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
5590                                 /* FIXME: handle CEE_STIND_R4 */
5591                                 if (store->opcode == CEE_STOBJ) {
5592                                         NEW_TEMPLOADA (cfg, store, temp->inst_c0);
5593                                         handle_stobj (cfg, bblock, store, sp [0], sp [0]->cil_code, store->klass, TRUE, FALSE, FALSE);
5594                                 } else {
5595                                         MONO_ADD_INS (bblock, store);
5596                                 }
5597                                 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
5598                                 *sp++ = ins;
5599                                 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
5600                                 *sp++ = ins;
5601                         }
5602                         ++ip;
5603                         inline_costs += 2;
5604                         break;
5605                 }
5606                 case CEE_POP:
5607                         CHECK_STACK (1);
5608                         MONO_INST_NEW (cfg, ins, CEE_POP);
5609                         MONO_ADD_INS (bblock, ins);
5610                         ip++;
5611                         --sp;
5612                         ins->inst_i0 = *sp;
5613                         break;
5614                 case CEE_JMP:
5615                         CHECK_OPSIZE (5);
5616                         if (stack_start != sp)
5617                                 UNVERIFIED;
5618                         MONO_INST_NEW (cfg, ins, OP_JMP);
5619                         token = read32 (ip + 1);
5620                         /* FIXME: check the signature matches */
5621                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
5622
5623                         if (!cmethod)
5624                                 goto load_error;
5625
5626                         if (cfg->generic_sharing_context && mono_method_check_context_used (cmethod))
5627                                 GENERIC_SHARING_FAILURE (CEE_JMP);
5628
5629                         if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
5630                                 if (check_linkdemand (cfg, method, cmethod, bblock, ip))
5631                                         INLINE_FAILURE;
5632                                 CHECK_CFG_EXCEPTION;
5633                         }
5634
5635                         ins->inst_p0 = cmethod;
5636                         MONO_ADD_INS (bblock, ins);
5637                         ip += 5;
5638                         start_new_bblock = 1;
5639                         break;
5640                 case CEE_CALLI:
5641                 case CEE_CALL:
5642                 case CEE_CALLVIRT: {
5643                         MonoInst *addr = NULL;
5644                         MonoMethodSignature *fsig = NULL;
5645                         int temp, array_rank = 0;
5646                         int virtual = *ip == CEE_CALLVIRT;
5647                         gboolean no_spill;
5648                         gboolean pass_imt_from_rgctx = FALSE;
5649                         MonoInst *imt_arg = NULL;
5650                         gboolean pass_vtable = FALSE;
5651                         gboolean pass_mrgctx = FALSE;
5652                         MonoInst *vtable_arg = NULL;
5653                         gboolean check_this = FALSE;
5654
5655                         CHECK_OPSIZE (5);
5656                         token = read32 (ip + 1);
5657
5658                         if (*ip == CEE_CALLI) {
5659                                 cmethod = NULL;
5660                                 CHECK_STACK (1);
5661                                 --sp;
5662                                 addr = *sp;
5663                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
5664                                         fsig = (MonoMethodSignature *)mono_method_get_wrapper_data (method, token);
5665                                 else
5666                                         fsig = mono_metadata_parse_signature (image, token);
5667
5668                                 n = fsig->param_count + fsig->hasthis;
5669                         } else {
5670                                 MonoMethod *cil_method;
5671                                 
5672                                 if (method->wrapper_type != MONO_WRAPPER_NONE) {
5673                                         cmethod =  (MonoMethod *)mono_method_get_wrapper_data (method, token);
5674                                         cil_method = cmethod;
5675                                 } else if (constrained_call) {
5676                                         cmethod = mono_get_method_constrained (image, token, constrained_call, generic_context, &cil_method);
5677                                         cil_method = cmethod;
5678                                 } else {
5679                                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
5680                                         cil_method = cmethod;
5681                                 }
5682
5683                                 if (!cmethod)
5684                                         goto load_error;
5685                                 if (!dont_verify && !cfg->skip_visibility) {
5686                                         MonoMethod *target_method = cil_method;
5687                                         if (method->is_inflated) {
5688                                                 target_method = mini_get_method_allow_open (method, token, NULL, &(mono_method_get_generic_container (method_definition)->context));
5689                                         }
5690                                         if (!mono_method_can_access_method (method_definition, target_method) &&
5691                                                 !mono_method_can_access_method (method, cil_method))
5692                                                 METHOD_ACCESS_FAILURE;
5693                                 }
5694
5695                                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
5696                                         ensure_method_is_allowed_to_call_method (cfg, method, cil_method, bblock, ip);
5697
5698                                 if (!virtual && (cmethod->flags & METHOD_ATTRIBUTE_ABSTRACT))
5699                                         /* MS.NET seems to silently convert this to a callvirt */
5700                                         virtual = 1;
5701
5702                                 if (!cmethod->klass->inited){
5703                                         if (!mono_class_init (cmethod->klass))
5704                                                 goto load_error;
5705                                 }
5706
5707                                 if (mono_method_signature (cmethod)->pinvoke) {
5708                                         MonoMethod *wrapper = mono_marshal_get_native_wrapper (cmethod, check_for_pending_exc);
5709                                         fsig = mono_method_signature (wrapper);
5710                                 } else if (constrained_call) {
5711                                         fsig = mono_method_signature (cmethod);
5712                                 } else {
5713                                         fsig = mono_method_get_signature_full (cmethod, image, token, generic_context);
5714                                 }
5715
5716                                 mono_save_token_info (cfg, image, token, cmethod);
5717
5718                                 n = fsig->param_count + fsig->hasthis;
5719
5720                                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
5721                                         if (check_linkdemand (cfg, method, cmethod, bblock, ip))
5722                                                 INLINE_FAILURE;
5723                                         CHECK_CFG_EXCEPTION;
5724                                 }
5725
5726                                 if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL &&
5727                                     mini_class_is_system_array (cmethod->klass)) {
5728                                         array_rank = cmethod->klass->rank;
5729                                 }
5730
5731                                 if (cmethod->string_ctor)
5732                                         g_assert_not_reached ();
5733
5734                         }
5735
5736                         if (!cfg->generic_sharing_context && cmethod && cmethod->klass->generic_container)
5737                                 UNVERIFIED;
5738
5739                         if (!cfg->generic_sharing_context && cmethod)
5740                                 g_assert (!mono_method_check_context_used (cmethod));
5741
5742                         CHECK_STACK (n);
5743
5744                         //g_assert (!virtual || fsig->hasthis);
5745
5746                         sp -= n;
5747
5748                         if (constrained_call) {
5749                                 /*
5750                                  * We have the `constrained.' prefix opcode.
5751                                  */
5752                                 if (constrained_call->valuetype && !cmethod->klass->valuetype) {
5753                                         MonoInst *load;
5754                                         /*
5755                                          * The type parameter is instantiated as a valuetype,
5756                                          * but that type doesn't override the method we're
5757                                          * calling, so we need to box `this'.
5758                                          * sp [0] is a pointer to the data: we need the value
5759                                          * in handle_box (), so load it here.
5760                                          */
5761                                         MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, &constrained_call->byval_arg));
5762                                         type_to_eval_stack_type (cfg, &constrained_call->byval_arg, load);
5763                                         load->inst_left = sp [0];
5764                                         sp [0] = handle_box (cfg, bblock, load, ip, constrained_call);
5765                                 } else if (!constrained_call->valuetype) {
5766                                         MonoInst *ins;
5767
5768                                         /*
5769                                          * The type parameter is instantiated as a reference
5770                                          * type.  We have a managed pointer on the stack, so
5771                                          * we need to dereference it here.
5772                                          */
5773
5774                                         MONO_INST_NEW (cfg, ins, CEE_LDIND_REF);
5775                                         ins->inst_i0 = sp [0];
5776                                         ins->type = STACK_OBJ;
5777                                         ins->klass = mono_class_from_mono_type (&constrained_call->byval_arg);
5778                                         sp [0] = ins;
5779                                 } else if (cmethod->klass->valuetype)
5780                                         virtual = 0;
5781                                 constrained_call = NULL;
5782                         }
5783
5784                         if (*ip != CEE_CALLI && check_call_signature (cfg, fsig, sp))
5785                                 UNVERIFIED;
5786
5787                         if (cmethod && (cmethod->flags & METHOD_ATTRIBUTE_STATIC) &&
5788                                         (cmethod->klass->generic_class || cmethod->klass->generic_container)) {
5789                                 gboolean sharing_enabled = mono_class_generic_sharing_enabled (cmethod->klass);
5790                                 MonoGenericContext *context = mini_class_get_context (cmethod->klass);
5791                                 gboolean context_sharable = mono_generic_context_is_sharable (context, TRUE);
5792
5793                                 /*
5794                                  * Pass vtable iff target method might
5795                                  * be shared, which means that sharing
5796                                  * is enabled for its class and its
5797                                  * context is sharable (and it's not a
5798                                  * generic method).
5799                                  */
5800                                 if (sharing_enabled && context_sharable &&
5801                                                 !mini_method_get_context (cmethod)->method_inst)
5802                                         pass_vtable = TRUE;
5803                         }
5804
5805                         if (cmethod && mini_method_get_context (cmethod) &&
5806                                         mini_method_get_context (cmethod)->method_inst) {
5807                                 gboolean sharing_enabled = mono_class_generic_sharing_enabled (cmethod->klass);
5808                                 MonoGenericContext *context = mini_method_get_context (cmethod);
5809                                 gboolean context_sharable = mono_generic_context_is_sharable (context, TRUE);
5810
5811                                 g_assert (!pass_vtable);
5812
5813                                 if (sharing_enabled && context_sharable)
5814                                         pass_mrgctx = TRUE;
5815                         }
5816
5817                         if (cfg->generic_sharing_context && cmethod) {
5818                                 MonoGenericContext *cmethod_context = mono_method_get_context (cmethod);
5819
5820                                 context_used = mono_method_check_context_used (cmethod);
5821
5822                                 if (context_used && (cmethod->klass->flags & TYPE_ATTRIBUTE_INTERFACE)) {
5823                                         /* Generic method interface
5824                                            calls are resolved via a
5825                                            helper function and don't
5826                                            need an imt. */
5827                                         if (!cmethod_context || !cmethod_context->method_inst)
5828                                                 pass_imt_from_rgctx = TRUE;
5829                                 }
5830
5831                                 /*
5832                                  * If a shared method calls another
5833                                  * shared method then the caller must
5834                                  * have a generic sharing context
5835                                  * because the magic trampoline
5836                                  * requires it.  FIXME: We shouldn't
5837                                  * have to force the vtable/mrgctx
5838                                  * variable here.  Instead there
5839                                  * should be a flag in the cfg to
5840                                  * request a generic sharing context.
5841                                  */
5842                                 if (context_used && method->flags & METHOD_ATTRIBUTE_STATIC)
5843                                         mono_get_vtable_var (cfg);
5844                         }
5845
5846                         if (pass_vtable) {
5847                                 if (context_used) {
5848                                         MonoInst *rgctx;
5849
5850                                         GET_RGCTX (rgctx, context_used);
5851                                         vtable_arg = get_runtime_generic_context_ptr (cfg, method, context_used,
5852                                                 bblock, cmethod->klass, generic_context, rgctx, MONO_RGCTX_INFO_VTABLE, ip);
5853                                 } else {
5854                                         MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
5855                                         
5856                                         CHECK_TYPELOAD (cmethod->klass);
5857                                         NEW_VTABLECONST (cfg, vtable_arg, vtable);
5858                                 }
5859                         }
5860
5861                         if (pass_mrgctx) {
5862                                 g_assert (!vtable_arg);
5863
5864                                 if (context_used) {
5865                                         MonoInst *rgctx;
5866
5867                                         GET_RGCTX (rgctx, context_used);
5868                                         vtable_arg = get_runtime_generic_context_method_rgctx (cfg, method,
5869                                                 context_used, bblock, cmethod, generic_context, rgctx, ip);
5870                                 } else {
5871                                         MonoMethodRuntimeGenericContext *mrgctx;
5872
5873                                         mrgctx = mono_method_lookup_rgctx (mono_class_vtable (cfg->domain, cmethod->klass),
5874                                                 mini_method_get_context (cmethod)->method_inst);
5875
5876                                         NEW_PCONST (cfg, vtable_arg, mrgctx);
5877                                 }
5878
5879                                 if (!(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
5880                                                 (cmethod->flags & METHOD_ATTRIBUTE_FINAL)) {
5881                                         if (virtual)
5882                                                 check_this = TRUE;
5883                                         virtual = 0;
5884                                 }
5885                         }
5886
5887                         if (pass_imt_from_rgctx) {
5888                                 MonoInst *rgctx;
5889
5890                                 g_assert (!pass_vtable);
5891                                 g_assert (cmethod);
5892
5893                                 GET_RGCTX (rgctx, context_used);
5894                                 imt_arg = get_runtime_generic_context_method (cfg, method, context_used, bblock, cmethod,
5895                                                 generic_context, rgctx, MONO_RGCTX_INFO_METHOD, ip);
5896                         }
5897
5898                         if (check_this) {
5899                                 MonoInst *check;
5900
5901                                 MONO_INST_NEW (cfg, check, OP_CHECK_THIS_PASSTHROUGH);
5902                                 check->cil_code = ip;
5903                                 check->inst_left = sp [0];
5904                                 check->type = sp [0]->type;
5905                                 sp [0] = check;
5906                         }
5907
5908                         if (cmethod && virtual && 
5909                             (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) && 
5910                             !((cmethod->flags & METHOD_ATTRIBUTE_FINAL) && 
5911                               cmethod->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK) &&
5912                             mono_method_signature (cmethod)->generic_param_count) {
5913                                 MonoInst *this_temp, *this_arg_temp, *store;
5914                                 MonoInst *iargs [4];
5915
5916                                 g_assert (mono_method_signature (cmethod)->is_inflated);
5917                                 /* Prevent inlining of methods that contain indirect calls */
5918                                 INLINE_FAILURE;
5919
5920                                 this_temp = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
5921                                 NEW_TEMPSTORE (cfg, store, this_temp->inst_c0, sp [0]);
5922                                 MONO_ADD_INS (bblock, store);
5923
5924                                 /* FIXME: This should be a managed pointer */
5925                                 this_arg_temp = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
5926
5927                                 /* Because of the PCONST below */
5928                                 cfg->disable_aot = TRUE;
5929                                 NEW_TEMPLOAD (cfg, iargs [0], this_temp->inst_c0);
5930                                 if (context_used) {
5931                                         MonoInst *rgctx;
5932
5933                                         GET_RGCTX (rgctx, context_used);
5934                                         iargs [1] = get_runtime_generic_context_method (cfg, method, context_used,
5935                                                         bblock, cmethod,
5936                                                         generic_context, rgctx, MONO_RGCTX_INFO_METHOD, ip);
5937                                         NEW_TEMPLOADA (cfg, iargs [2], this_arg_temp->inst_c0);
5938                                         temp = mono_emit_jit_icall (cfg, bblock,
5939                                                 mono_helper_compile_generic_method_wo_context, iargs, ip);
5940                                 } else {
5941                                         NEW_METHODCONST (cfg, iargs [1], cmethod);
5942                                         NEW_PCONST (cfg, iargs [2], mono_method_get_context (cmethod));
5943                                         NEW_TEMPLOADA (cfg, iargs [3], this_arg_temp->inst_c0);
5944                                         temp = mono_emit_jit_icall (cfg, bblock, mono_helper_compile_generic_method,
5945                                                 iargs, ip);
5946                                 }
5947
5948                                 NEW_TEMPLOAD (cfg, addr, temp);
5949                                 NEW_TEMPLOAD (cfg, sp [0], this_arg_temp->inst_c0);
5950
5951                                 if ((temp = mono_emit_calli_spilled (cfg, bblock, fsig, sp, addr, ip)) != -1) {
5952                                         NEW_TEMPLOAD (cfg, *sp, temp);
5953                                         sp++;
5954                                 }
5955
5956                                 ip += 5;
5957                                 ins_flag = 0;
5958                                 break;
5959                         }
5960
5961                         /* FIXME: runtime generic context pointer for jumps? */
5962                         /* FIXME: handle this for generic sharing eventually */
5963                         if ((ins_flag & MONO_INST_TAILCALL) && !cfg->generic_sharing_context && !vtable_arg && cmethod && (*ip == CEE_CALL) &&
5964                                  (mono_metadata_signature_equal (mono_method_signature (method), mono_method_signature (cmethod)))) {
5965                                 int i;
5966
5967                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
5968                                 INLINE_FAILURE;
5969                                 /* FIXME: This assumes the two methods has the same number and type of arguments */
5970                                 /*
5971                                  * We implement tail calls by storing the actual arguments into the 
5972                                  * argument variables, then emitting a OP_JMP. Since the actual arguments
5973                                  * can refer to the arg variables, we have to spill them.
5974                                  */
5975                                 handle_loaded_temps (cfg, bblock, sp, sp + n);
5976                                 for (i = 0; i < n; ++i) {
5977                                         /* Prevent argument from being register allocated */
5978                                         arg_array [i]->flags |= MONO_INST_VOLATILE;
5979
5980                                         /* Check if argument is the same */
5981                                         /* 
5982                                          * FIXME: This loses liveness info, so it can only be done if the
5983                                          * argument is not register allocated.
5984                                          */
5985                                         NEW_ARGLOAD (cfg, ins, i);
5986                                         if ((ins->opcode == sp [i]->opcode) && (ins->inst_i0 == sp [i]->inst_i0))
5987                                                 continue;
5988
5989                                         NEW_ARGSTORE (cfg, ins, i, sp [i]);
5990                                         /* FIXME: handle CEE_STIND_R4 */
5991                                         if (ins->opcode == CEE_STOBJ) {
5992                                                 NEW_ARGLOADA (cfg, ins, i);
5993                                                 handle_stobj (cfg, bblock, ins, sp [i], sp [i]->cil_code, ins->klass, FALSE, FALSE, FALSE);
5994                                         }
5995                                         else
5996                                                 MONO_ADD_INS (bblock, ins);
5997                                 }
5998                                 MONO_INST_NEW (cfg, ins, OP_JMP);
5999                                 ins->inst_p0 = cmethod;
6000                                 ins->inst_p1 = arg_array [0];
6001                                 MONO_ADD_INS (bblock, ins);
6002                                 link_bblock (cfg, bblock, end_bblock);                  
6003                                 start_new_bblock = 1;
6004                                 /* skip CEE_RET as well */
6005                                 ip += 6;
6006                                 ins_flag = 0;
6007                                 break;
6008                         }
6009                         if (cmethod && (cfg->opt & MONO_OPT_INTRINS) && (ins = mini_get_inst_for_method (cfg, cmethod, fsig, sp))) {
6010                                 if (MONO_TYPE_IS_VOID (fsig->ret)) {
6011                                         MONO_ADD_INS (bblock, ins);
6012                                 } else {
6013                                         type_to_eval_stack_type (cfg, fsig->ret, ins);
6014                                         *sp = ins;
6015                                         sp++;
6016                                 }
6017
6018                                 ip += 5;
6019                                 ins_flag = 0;
6020                                 break;
6021                         }
6022
6023                         handle_loaded_temps (cfg, bblock, stack_start, sp);
6024
6025                         if ((cfg->opt & MONO_OPT_INLINE) && cmethod && //!check_this &&
6026                             (!virtual || !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) || (cmethod->flags & METHOD_ATTRIBUTE_FINAL)) && 
6027                             mono_method_check_inlining (cfg, cmethod) &&
6028                                  !g_list_find (dont_inline, cmethod)) {
6029                                 int costs;
6030                                 MonoBasicBlock *ebblock;
6031                                 gboolean allways = FALSE;
6032
6033                                 if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
6034                                         (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
6035                                         /* Prevent inlining of methods that call wrappers */
6036                                         INLINE_FAILURE;
6037                                         cmethod = mono_marshal_get_native_wrapper (cmethod, check_for_pending_exc);
6038                                         allways = TRUE;
6039                                 }
6040
6041                                 if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock, allways))) {
6042                                         ip += 5;
6043                                         real_offset += 5;
6044
6045                                         GET_BBLOCK (cfg, bblock, ip);
6046                                         ebblock->next_bb = bblock;
6047                                         link_bblock (cfg, ebblock, bblock);
6048
6049                                         if (!MONO_TYPE_IS_VOID (fsig->ret))
6050                                                 sp++;
6051
6052                                         /* indicates start of a new block, and triggers a load of all 
6053                                            stack arguments at bb boundarie */
6054                                         bblock = ebblock;
6055
6056                                         inline_costs += costs;
6057                                         ins_flag = 0;
6058                                         break;
6059                                 }
6060                         }
6061                         
6062                         inline_costs += 10 * num_calls++;
6063
6064                         /* tail recursion elimination */
6065                         if ((cfg->opt & MONO_OPT_TAILC) && *ip == CEE_CALL && cmethod == method && ip [5] == CEE_RET &&
6066                                         !vtable_arg) {
6067                                 gboolean has_vtargs = FALSE;
6068                                 int i;
6069                                 
6070                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
6071                                 INLINE_FAILURE;
6072                                 /* keep it simple */
6073                                 for (i =  fsig->param_count - 1; i >= 0; i--) {
6074                                         if (MONO_TYPE_ISSTRUCT (mono_method_signature (cmethod)->params [i])) 
6075                                                 has_vtargs = TRUE;
6076                                 }
6077
6078                                 if (!has_vtargs) {
6079                                         for (i = 0; i < n; ++i) {
6080                                                 /* FIXME: handle CEE_STIND_R4 */
6081                                                 NEW_ARGSTORE (cfg, ins, i, sp [i]);
6082                                                 MONO_ADD_INS (bblock, ins);
6083                                         }
6084                                         MONO_INST_NEW (cfg, ins, OP_BR);
6085                                         MONO_ADD_INS (bblock, ins);
6086                                         tblock = start_bblock->out_bb [0];
6087                                         link_bblock (cfg, bblock, tblock);
6088                                         ins->inst_target_bb = tblock;
6089                                         start_new_bblock = 1;
6090
6091                                         /* skip the CEE_RET, too */
6092                                         if (ip_in_bb (cfg, bblock, ip + 5))
6093                                                 ip += 6;
6094                                         else
6095                                                 ip += 5;
6096                                         ins_flag = 0;
6097                                         break;
6098                                 }
6099                         }
6100
6101                         if (ip_in_bb (cfg, bblock, ip + 5) 
6102                                 && (!MONO_TYPE_ISSTRUCT (fsig->ret))
6103                                 && (!MONO_TYPE_IS_VOID (fsig->ret) || (cmethod && cmethod->string_ctor))
6104                                 && (CODE_IS_STLOC (ip + 5) || ip [5] == CEE_POP || ip [5] == CEE_RET))
6105                                 /* No need to spill */
6106                                 no_spill = TRUE;
6107                         else
6108                                 no_spill = FALSE;
6109
6110                         /* FIXME: only do this for generic methods if
6111                            they are not shared! */
6112                         if (context_used &&
6113                                         (cmethod->klass->valuetype ||
6114                                         (cmethod->is_inflated && mono_method_get_context (cmethod)->method_inst && !pass_mrgctx) ||
6115                                         ((cmethod->flags & METHOD_ATTRIBUTE_STATIC) &&
6116                                                 mono_class_generic_sharing_enabled (cmethod->klass)) ||
6117                                         (!imt_arg && !mono_method_is_generic_sharable_impl (cmethod, TRUE) &&
6118                                                 (!virtual || cmethod->flags & METHOD_ATTRIBUTE_FINAL ||
6119                                                 !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL))))) {
6120                                 MonoInst *rgctx;
6121
6122                                 INLINE_FAILURE;
6123
6124                                 g_assert (cfg->generic_sharing_context && cmethod);
6125                                 g_assert (!addr);
6126
6127                                 /*
6128                                  * We are compiling a call to
6129                                  * non-shared generic code from shared
6130                                  * code, which means that we have to
6131                                  * look up the method in the rgctx and
6132                                  * do an indirect call.
6133                                  */
6134                                 GET_RGCTX (rgctx, context_used);
6135                                 addr = get_runtime_generic_context_method (cfg, method, context_used, bblock, cmethod,
6136                                                 generic_context, rgctx, MONO_RGCTX_INFO_GENERIC_METHOD_CODE, ip);
6137
6138                         }
6139
6140                         if (addr) {
6141                                 g_assert (!imt_arg);
6142
6143                                 if (*ip == CEE_CALL) {
6144                                         g_assert (context_used);
6145                                 } else if (*ip == CEE_CALLI) {
6146                                         g_assert (!vtable_arg);
6147                                 } else {
6148                                         g_assert (cmethod->flags & METHOD_ATTRIBUTE_FINAL ||
6149                                                         !(cmethod->flags & METHOD_ATTRIBUTE_FINAL));
6150                                 }
6151
6152                                 /* Prevent inlining of methods with indirect calls */
6153                                 INLINE_FAILURE;
6154                                 if (no_spill) {
6155                                         ins = (MonoInst*)mono_emit_rgctx_calli (cfg, bblock, fsig, sp, addr, vtable_arg, ip);
6156                                         *sp++ = ins;                                    
6157                                 } else {
6158                                         temp = mono_emit_rgctx_calli_spilled (cfg, bblock, fsig, sp, addr, vtable_arg, ip);
6159                                         if (temp != -1) {
6160                                                 NEW_TEMPLOAD (cfg, *sp, temp);
6161                                                 sp++;
6162                                         }
6163                                 }                       
6164                         } else if (array_rank) {
6165                                 MonoInst *addr;
6166
6167                                 if (strcmp (cmethod->name, "Set") == 0) { /* array Set */ 
6168                                         if (sp [fsig->param_count]->type == STACK_OBJ) {
6169                                                 MonoInst *iargs [2];
6170                                                 MonoInst *array, *to_store, *store;
6171
6172                                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
6173                                                 
6174                                                 array = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
6175                                                 NEW_TEMPSTORE (cfg, store, array->inst_c0, sp [0]);
6176                                                 MONO_ADD_INS (bblock, store);
6177                                                 NEW_TEMPLOAD (cfg, iargs [0], array->inst_c0);
6178
6179                                                 to_store = mono_compile_create_var (cfg, type_from_stack_type (sp [fsig->param_count]), OP_LOCAL);
6180                                                 NEW_TEMPSTORE (cfg, store, to_store->inst_c0, sp [fsig->param_count]);
6181                                                 /* FIXME: handle CEE_STIND_R4 */
6182                                                 MONO_ADD_INS (bblock, store);
6183                                                 NEW_TEMPLOAD (cfg, iargs [1], to_store->inst_c0);
6184
6185                                                 /*
6186                                                  * We first save the args for the call so that the args are copied to the stack
6187                                                  * and a new instruction tree for them is created. If we don't do this,
6188                                                  * the same MonoInst is added to two different trees and this is not 
6189                                                  * allowed by burg.
6190                                                  */
6191                                                 mono_emit_jit_icall (cfg, bblock, mono_helper_stelem_ref_check, iargs, ip);
6192
6193                                                 NEW_TEMPLOAD (cfg, sp [0], array->inst_c0);
6194                                                 NEW_TEMPLOAD (cfg, sp [fsig->param_count], to_store->inst_c0);
6195                                         }
6196
6197                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, TRUE);
6198                                         NEW_INDSTORE (cfg, ins, addr, sp [fsig->param_count], fsig->params [fsig->param_count - 1]);
6199                                         /* FIXME: handle CEE_STIND_R4 */
6200                                         if (ins->opcode == CEE_STOBJ) {
6201                                                 handle_stobj (cfg, bblock, addr, sp [fsig->param_count], ip, mono_class_from_mono_type (fsig->params [fsig->param_count-1]), FALSE, FALSE, TRUE);
6202                                         } else {
6203                                                 MONO_ADD_INS (bblock, ins);
6204                                         }
6205
6206                                 } else if (strcmp (cmethod->name, "Get") == 0) { /* array Get */
6207                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
6208                                         NEW_INDLOAD (cfg, ins, addr, fsig->ret);
6209
6210                                         *sp++ = ins;
6211                                 } else if (strcmp (cmethod->name, "Address") == 0) { /* array Address */
6212                                         if (!cmethod->klass->element_class->valuetype && !readonly) {
6213                                                 MonoInst* check;
6214                                                 //* Needed by the code generated in inssel.brg * /
6215                                                 mono_get_got_var (cfg);
6216
6217                                                 MONO_INST_NEW (cfg, check, OP_CHECK_ARRAY_TYPE);
6218                                                 check->klass = cmethod->klass;
6219                                                 check->inst_left = sp [0];
6220                                                 check->type = STACK_OBJ;
6221                                                 sp [0] = check;
6222                                         }
6223
6224                                         readonly = FALSE;
6225                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
6226                                         *sp++ = addr;
6227                                 } else {
6228                                         g_assert_not_reached ();
6229                                 }
6230
6231                         } else {
6232                                 /* Prevent inlining of methods which call other methods */
6233                                 INLINE_FAILURE;
6234                                 if (mini_redirect_call (&temp, cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL)) {
6235                                         if (temp != -1) {
6236                                                 NEW_TEMPLOAD (cfg, *sp, temp);
6237                                                 sp++;
6238                                         }
6239                                 } else if (no_spill) {
6240                                         ins = (MonoInst*)mono_emit_rgctx_method_call (cfg, bblock, cmethod, fsig, sp,
6241                                                         vtable_arg, imt_arg, ip, virtual ? sp [0] : NULL);
6242                                         *sp++ = ins;
6243                                 } else {
6244                                         if ((temp = mono_emit_rgctx_method_call_spilled (cfg, bblock, cmethod, fsig, sp,
6245                                                         vtable_arg, imt_arg, ip, virtual ? sp [0] : NULL)) != -1) {
6246                                                 MonoInst *load;
6247                                                 NEW_TEMPLOAD (cfg, load, temp);
6248
6249 #ifdef MONO_ARCH_SOFT_FLOAT
6250                                                 if (load->opcode == CEE_LDIND_R4) {
6251                                                         NEW_TEMPLOADA (cfg, load, temp);
6252                                                         temp = handle_load_float (cfg, bblock, load, ip);
6253                                                         NEW_TEMPLOAD (cfg, load, temp);
6254                                                 }
6255 #endif
6256                                                 *sp++ = load;
6257                                         }
6258                                 }
6259                         }
6260
6261                         ip += 5;
6262                         ins_flag = 0;
6263                         break;
6264                 }
6265                 case CEE_RET:
6266                         if (cfg->method != method) {
6267                                 /* return from inlined method */
6268                                 if (return_var) {
6269                                         MonoInst *store;
6270                                         CHECK_STACK (1);
6271                                         --sp;
6272                                         //g_assert (returnvar != -1);
6273                                         NEW_TEMPSTORE (cfg, store, return_var->inst_c0, *sp);
6274                                         store->cil_code = sp [0]->cil_code;
6275                                         if (store->opcode == CEE_STOBJ) {
6276                                                 g_assert_not_reached ();
6277                                                 NEW_TEMPLOADA (cfg, store, return_var->inst_c0);
6278                                                 /* FIXME: it is possible some optimization will pass the a heap pointer for the struct address, so we'll need the write barrier */
6279                                                 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, return_var->klass, FALSE, FALSE, FALSE);
6280 #ifdef MONO_ARCH_SOFT_FLOAT
6281                                         } else if (store->opcode == CEE_STIND_R4) {
6282                                                 NEW_TEMPLOADA (cfg, store, return_var->inst_c0);
6283                                                 handle_store_float (cfg, bblock, store, *sp, sp [0]->cil_code);
6284 #endif
6285                                         } else
6286                                                 MONO_ADD_INS (bblock, store);
6287                                 } 
6288                         } else {
6289                                 if (cfg->ret) {
6290                                         g_assert (!return_var);
6291                                         CHECK_STACK (1);
6292                                         --sp;
6293                                         MONO_INST_NEW (cfg, ins, OP_NOP);
6294                                         ins->opcode = mini_type_to_stind (cfg, mono_method_signature (method)->ret);
6295                                         if (ins->opcode == CEE_STOBJ) {
6296                                                 NEW_RETLOADA (cfg, ins);
6297                                                 /* FIXME: it is possible some optimization will pass the a heap pointer for the struct address, so we'll need the write barrier */
6298                                                 handle_stobj (cfg, bblock, ins, *sp, ip, cfg->ret->klass, FALSE, FALSE, FALSE);
6299                                         } else {
6300                                                 ins->opcode = OP_SETRET;
6301                                                 ins->inst_i0 = *sp;;
6302                                                 ins->inst_i1 = NULL;
6303                                                 MONO_ADD_INS (bblock, ins);
6304                                         }
6305                                 }
6306                         }
6307                         if (sp != stack_start)
6308                                 UNVERIFIED;
6309                         MONO_INST_NEW (cfg, ins, OP_BR);
6310                         ip++;
6311                         ins->inst_target_bb = end_bblock;
6312                         MONO_ADD_INS (bblock, ins);
6313                         link_bblock (cfg, bblock, end_bblock);
6314                         start_new_bblock = 1;
6315                         break;
6316                 case CEE_BR_S:
6317                         CHECK_OPSIZE (2);
6318                         MONO_INST_NEW (cfg, ins, OP_BR);
6319                         ip++;
6320                         MONO_ADD_INS (bblock, ins);
6321                         target = ip + 1 + (signed char)(*ip);
6322                         ++ip;
6323                         GET_BBLOCK (cfg, tblock, target);
6324                         link_bblock (cfg, bblock, tblock);
6325                         CHECK_BBLOCK (target, ip, tblock);
6326                         ins->inst_target_bb = tblock;
6327                         if (sp != stack_start) {
6328                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6329                                 sp = stack_start;
6330                                 CHECK_UNVERIFIABLE (cfg);
6331                         }
6332                         start_new_bblock = 1;
6333                         inline_costs += BRANCH_COST;
6334                         break;
6335                 case CEE_BRFALSE_S:
6336                 case CEE_BRTRUE_S:
6337                         CHECK_OPSIZE (2);
6338                         CHECK_STACK (1);
6339                         if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
6340                                 UNVERIFIED;
6341                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
6342                         ip++;
6343                         target = ip + 1 + *(signed char*)ip;
6344                         ip++;
6345                         ADD_UNCOND (ins->opcode == CEE_BRTRUE);
6346                         if (sp != stack_start) {
6347                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6348                                 sp = stack_start;
6349                                 CHECK_UNVERIFIABLE (cfg);
6350                         }
6351                         inline_costs += BRANCH_COST;
6352                         break;
6353                 case CEE_BEQ_S:
6354                 case CEE_BGE_S:
6355                 case CEE_BGT_S:
6356                 case CEE_BLE_S:
6357                 case CEE_BLT_S:
6358                 case CEE_BNE_UN_S:
6359                 case CEE_BGE_UN_S:
6360                 case CEE_BGT_UN_S:
6361                 case CEE_BLE_UN_S:
6362                 case CEE_BLT_UN_S:
6363                         CHECK_OPSIZE (2);
6364                         CHECK_STACK (2);
6365                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
6366                         ip++;
6367                         target = ip + 1 + *(signed char*)ip;
6368                         ip++;
6369 #ifdef MONO_ARCH_SOFT_FLOAT
6370                         if (sp [-1]->type == STACK_R8 || sp [-2]->type == STACK_R8) {
6371                                 ins->opcode = condbr_to_fp_br (ins->opcode);
6372                                 sp -= 2;
6373                                 ins->inst_left = sp [0];
6374                                 ins->inst_right = sp [1];
6375                                 ins->type = STACK_I4;
6376                                 *sp++ = emit_tree (cfg, bblock, ins, ins->cil_code);
6377                                 MONO_INST_NEW (cfg, ins, CEE_BRTRUE);
6378                                 ADD_UNCOND (TRUE);
6379                         } else {
6380                                 ADD_BINCOND (NULL);
6381                         }
6382 #else
6383                         ADD_BINCOND (NULL);
6384 #endif
6385                         if (sp != stack_start) {
6386                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6387                                 sp = stack_start;
6388                                 CHECK_UNVERIFIABLE (cfg);
6389                         }
6390                         inline_costs += BRANCH_COST;
6391                         break;
6392                 case CEE_BR:
6393                         CHECK_OPSIZE (5);
6394                         MONO_INST_NEW (cfg, ins, OP_BR);
6395                         ip++;
6396                         MONO_ADD_INS (bblock, ins);
6397                         target = ip + 4 + (gint32)read32(ip);
6398                         ip += 4;
6399                         GET_BBLOCK (cfg, tblock, target);
6400                         link_bblock (cfg, bblock, tblock);
6401                         CHECK_BBLOCK (target, ip, tblock);
6402                         ins->inst_target_bb = tblock;
6403                         if (sp != stack_start) {
6404                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6405                                 sp = stack_start;
6406                                 CHECK_UNVERIFIABLE (cfg);
6407                         }
6408                         start_new_bblock = 1;
6409                         inline_costs += BRANCH_COST;
6410                         break;
6411                 case CEE_BRFALSE:
6412                 case CEE_BRTRUE:
6413                         CHECK_OPSIZE (5);
6414                         CHECK_STACK (1);
6415                         if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
6416                                 UNVERIFIED;
6417                         MONO_INST_NEW (cfg, ins, *ip);
6418                         ip++;
6419                         target = ip + 4 + (gint32)read32(ip);
6420                         ip += 4;
6421                         ADD_UNCOND(ins->opcode == CEE_BRTRUE);
6422                         if (sp != stack_start) {
6423                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6424                                 sp = stack_start;
6425                                 CHECK_UNVERIFIABLE (cfg);
6426                         }
6427                         inline_costs += BRANCH_COST;
6428                         break;
6429                 case CEE_BEQ:
6430                 case CEE_BGE:
6431                 case CEE_BGT:
6432                 case CEE_BLE:
6433                 case CEE_BLT:
6434                 case CEE_BNE_UN:
6435                 case CEE_BGE_UN:
6436                 case CEE_BGT_UN:
6437                 case CEE_BLE_UN:
6438                 case CEE_BLT_UN:
6439                         CHECK_OPSIZE (5);
6440                         CHECK_STACK (2);
6441                         MONO_INST_NEW (cfg, ins, *ip);
6442                         ip++;
6443                         target = ip + 4 + (gint32)read32(ip);
6444                         ip += 4;
6445 #ifdef MONO_ARCH_SOFT_FLOAT
6446                         if (sp [-1]->type == STACK_R8 || sp [-2]->type == STACK_R8) {
6447                                 ins->opcode = condbr_to_fp_br (ins->opcode);
6448                                 sp -= 2;
6449                                 ins->inst_left = sp [0];
6450                                 ins->inst_right = sp [1];
6451                                 ins->type = STACK_I4;
6452                                 *sp++ = emit_tree (cfg, bblock, ins, ins->cil_code);
6453                                 MONO_INST_NEW (cfg, ins, CEE_BRTRUE);
6454                                 ADD_UNCOND (TRUE);
6455                         } else {
6456                                 ADD_BINCOND (NULL);
6457                         }
6458 #else
6459                         ADD_BINCOND (NULL);
6460 #endif
6461                         if (sp != stack_start) {
6462                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6463                                 sp = stack_start;
6464                                 CHECK_UNVERIFIABLE (cfg);
6465                         }
6466                         inline_costs += BRANCH_COST;
6467                         break;
6468                 case CEE_SWITCH:
6469                         CHECK_OPSIZE (5);
6470                         CHECK_STACK (1);
6471                         n = read32 (ip + 1);
6472                         MONO_INST_NEW (cfg, ins, OP_SWITCH);
6473                         --sp;
6474                         ins->inst_left = *sp;
6475                         if ((ins->inst_left->type != STACK_I4) && (ins->inst_left->type != STACK_PTR)) 
6476                                 UNVERIFIED;
6477                         ip += 5;
6478                         CHECK_OPSIZE (n * sizeof (guint32));
6479                         target = ip + n * sizeof (guint32);
6480                         MONO_ADD_INS (bblock, ins);
6481                         GET_BBLOCK (cfg, tblock, target);
6482                         link_bblock (cfg, bblock, tblock);
6483                         ins->klass = GUINT_TO_POINTER (n);
6484                         ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (n + 1));
6485                         ins->inst_many_bb [n] = tblock;
6486
6487                         for (i = 0; i < n; ++i) {
6488                                 GET_BBLOCK (cfg, tblock, target + (gint32)read32(ip));
6489                                 link_bblock (cfg, bblock, tblock);
6490                                 ins->inst_many_bb [i] = tblock;
6491                                 ip += 4;
6492                         }
6493                         if (sp != stack_start) {
6494                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6495                                 sp = stack_start;
6496                                 CHECK_UNVERIFIABLE (cfg);
6497                         }
6498                         /* Needed by the code generated in inssel.brg */
6499                         mono_get_got_var (cfg);
6500                         inline_costs += (BRANCH_COST * 2);
6501                         break;
6502                 case CEE_LDIND_I1:
6503                 case CEE_LDIND_U1:
6504                 case CEE_LDIND_I2:
6505                 case CEE_LDIND_U2:
6506                 case CEE_LDIND_I4:
6507                 case CEE_LDIND_U4:
6508                 case CEE_LDIND_I8:
6509                 case CEE_LDIND_I:
6510                 case CEE_LDIND_R4:
6511                 case CEE_LDIND_R8:
6512                 case CEE_LDIND_REF:
6513                         CHECK_STACK (1);
6514                         MONO_INST_NEW (cfg, ins, *ip);
6515                         --sp;
6516                         ins->inst_i0 = *sp;
6517                         *sp++ = ins;
6518                         ins->type = ldind_type [*ip - CEE_LDIND_I1];
6519                         ins->flags |= ins_flag;
6520                         ins_flag = 0;
6521                         if (ins->type == STACK_OBJ)
6522                                 ins->klass = mono_defaults.object_class;
6523 #ifdef MONO_ARCH_SOFT_FLOAT
6524                         if (*ip == CEE_LDIND_R4) {
6525                                 int temp;
6526                                 --sp;
6527                                 temp = handle_load_float (cfg, bblock, ins->inst_i0, ip);
6528                                 NEW_TEMPLOAD (cfg, *sp, temp);
6529                                 sp++;
6530                         }
6531 #endif
6532                         ++ip;
6533                         break;
6534                 case CEE_STIND_REF:
6535                 case CEE_STIND_I1:
6536                 case CEE_STIND_I2:
6537                 case CEE_STIND_I4:
6538                 case CEE_STIND_I8:
6539                 case CEE_STIND_R4:
6540                 case CEE_STIND_R8:
6541                         CHECK_STACK (2);
6542 #ifdef MONO_ARCH_SOFT_FLOAT
6543                         if (*ip == CEE_STIND_R4) {
6544                                 sp -= 2;
6545                                 handle_store_float (cfg, bblock, sp [0], sp [1], ip);
6546                                 ip++;
6547                                 break;
6548                         }
6549 #endif
6550 #if HAVE_WRITE_BARRIERS
6551                         if (*ip == CEE_STIND_REF && method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER && !((sp [-1]->opcode == OP_PCONST) && (sp [-1]->inst_p0 == 0))) {
6552                                 /* insert call to write barrier */
6553                                 MonoMethod *write_barrier = mono_marshal_get_write_barrier ();
6554                                 sp -= 2;
6555                                 mono_emit_method_call_spilled (cfg, bblock, write_barrier, mono_method_signature (write_barrier), sp, ip, NULL);
6556                                 ip++;
6557                                 break;
6558                         }
6559 #endif
6560                         MONO_INST_NEW (cfg, ins, *ip);
6561                         ip++;
6562                         sp -= 2;
6563                         handle_loaded_temps (cfg, bblock, stack_start, sp);
6564                         MONO_ADD_INS (bblock, ins);
6565                         ins->inst_i0 = sp [0];
6566                         ins->inst_i1 = sp [1];
6567                         ins->flags |= ins_flag;
6568                         ins_flag = 0;
6569                         inline_costs += 1;
6570                         break;
6571                 case CEE_MUL:
6572                         CHECK_STACK (2);
6573                         ADD_BINOP (*ip);
6574
6575 #ifdef MONO_ARCH_NO_EMULATE_MUL_IMM
6576                         /* FIXME: This breaks with ssapre (mono -O=ssapre loader.exe) */
6577                         if ((ins->inst_right->opcode == OP_ICONST) && !(cfg->opt & MONO_OPT_SSAPRE)) {
6578                                 switch (ins->opcode) {
6579                                 case CEE_MUL:
6580                                         ins->opcode = OP_IMUL_IMM;
6581                                         ins->inst_imm = ins->inst_right->inst_c0;
6582                                         break;
6583                                 case OP_LMUL:
6584                                         ins->opcode = OP_LMUL_IMM;
6585                                         ins->inst_imm = ins->inst_right->inst_c0;
6586                                         break;
6587                                 default:
6588                                         g_assert_not_reached ();
6589                                 }
6590                         }
6591 #endif
6592
6593                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
6594                                 --sp;
6595                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
6596                         }
6597                         ip++;
6598                         break;
6599                 case CEE_ADD:
6600                 case CEE_SUB:
6601                 case CEE_DIV:
6602                 case CEE_DIV_UN:
6603                 case CEE_REM:
6604                 case CEE_REM_UN:
6605                 case CEE_AND:
6606                 case CEE_OR:
6607                 case CEE_XOR:
6608                 case CEE_SHL:
6609                 case CEE_SHR:
6610                 case CEE_SHR_UN:
6611                         CHECK_STACK (2);
6612                         ADD_BINOP (*ip);
6613                         /* special case that gives a nice speedup and happens to workaorund a ppc jit but (for the release)
6614                          * later apply the speedup to the left shift as well
6615                          * See BUG# 57957.
6616                          */
6617                         if ((ins->opcode == OP_LSHR_UN) && (ins->type == STACK_I8) 
6618                                         && (ins->inst_right->opcode == OP_ICONST) && (ins->inst_right->inst_c0 == 32)) {
6619                                 ins->opcode = OP_LONG_SHRUN_32;
6620                                 /*g_print ("applied long shr speedup to %s\n", cfg->method->name);*/
6621                                 ip++;
6622                                 break;
6623                         }
6624                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
6625                                 --sp;
6626                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
6627                         }
6628                         ip++;
6629                         break;
6630                 case CEE_NEG:
6631                 case CEE_NOT:
6632                 case CEE_CONV_I1:
6633                 case CEE_CONV_I2:
6634                 case CEE_CONV_I4:
6635                 case CEE_CONV_R4:
6636                 case CEE_CONV_R8:
6637                 case CEE_CONV_U4:
6638                 case CEE_CONV_I8:
6639                 case CEE_CONV_U8:
6640                 case CEE_CONV_OVF_I8:
6641                 case CEE_CONV_OVF_U8:
6642                 case CEE_CONV_R_UN:
6643                         CHECK_STACK (1);
6644                         ADD_UNOP (*ip);
6645
6646 #ifdef MONO_ARCH_SOFT_FLOAT
6647                         /*
6648                          * Its rather hard to emit the soft float code during the decompose
6649                          * pass, so avoid it in some specific cases.
6650                          */
6651                         if (ins->opcode == OP_LCONV_TO_R4) {
6652                                 MonoInst *conv;
6653
6654                                 ins->opcode = OP_LCONV_TO_R8;
6655                                 ins->type = STACK_R8;
6656
6657                                 --sp;
6658                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
6659
6660                                 MONO_INST_NEW (cfg, conv, CEE_CONV_R4);
6661                                 conv->inst_left = sp [-1];
6662                                 conv->type = STACK_R8;
6663                                 sp [-1] = ins;
6664
6665                                 ip++;
6666                                 break;
6667                         }
6668 #endif
6669
6670                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
6671                                 --sp;
6672                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
6673                         }
6674                         ip++;                   
6675                         break;
6676                 case CEE_CONV_OVF_I4:
6677                 case CEE_CONV_OVF_I1:
6678                 case CEE_CONV_OVF_I2:
6679                 case CEE_CONV_OVF_I:
6680                 case CEE_CONV_OVF_U:
6681                         CHECK_STACK (1);
6682
6683                         if (sp [-1]->type == STACK_R8) {
6684                                 ADD_UNOP (CEE_CONV_OVF_I8);
6685                                 ADD_UNOP (*ip);
6686                         } else {
6687                                 ADD_UNOP (*ip);
6688                         }
6689
6690                         ip++;
6691                         break;
6692                 case CEE_CONV_OVF_U1:
6693                 case CEE_CONV_OVF_U2:
6694                 case CEE_CONV_OVF_U4:
6695                         CHECK_STACK (1);
6696
6697                         if (sp [-1]->type == STACK_R8) {
6698                                 ADD_UNOP (CEE_CONV_OVF_U8);
6699                                 ADD_UNOP (*ip);
6700                         } else {
6701                                 ADD_UNOP (*ip);
6702                         }
6703
6704                         ip++;
6705                         break;
6706                 case CEE_CONV_OVF_I1_UN:
6707                 case CEE_CONV_OVF_I2_UN:
6708                 case CEE_CONV_OVF_I4_UN:
6709                 case CEE_CONV_OVF_I8_UN:
6710                 case CEE_CONV_OVF_U1_UN:
6711                 case CEE_CONV_OVF_U2_UN:
6712                 case CEE_CONV_OVF_U4_UN:
6713                 case CEE_CONV_OVF_U8_UN:
6714                 case CEE_CONV_OVF_I_UN:
6715                 case CEE_CONV_OVF_U_UN:
6716                         CHECK_STACK (1);
6717                         ADD_UNOP (*ip);
6718                         ip++;
6719                         break;
6720                 case CEE_CPOBJ:
6721                         CHECK_OPSIZE (5);
6722                         CHECK_STACK (2);
6723                         token = read32 (ip + 1);
6724                         klass = mini_get_class (method, token, generic_context);
6725                         CHECK_TYPELOAD (klass);
6726                         sp -= 2;
6727                         if (generic_class_is_reference_type (cfg, klass)) {
6728                                 MonoInst *store, *load;
6729                                 MONO_INST_NEW (cfg, load, CEE_LDIND_REF);
6730                                 load->inst_i0 = sp [1];
6731                                 load->type = STACK_OBJ;
6732                                 load->klass = klass;
6733                                 load->flags |= ins_flag;
6734                                 MONO_INST_NEW (cfg, store, CEE_STIND_REF);
6735                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
6736                                 MONO_ADD_INS (bblock, store);
6737                                 store->inst_i0 = sp [0];
6738                                 store->inst_i1 = load;
6739                                 store->flags |= ins_flag;
6740                         } else {
6741                                 guint32 align;
6742
6743                                 n = mono_class_value_size (klass, &align);
6744                                 if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
6745                                         MonoInst *copy;
6746                                         NEW_MEMCPY (cfg, copy, sp [0], sp [1], n, align);
6747                                         MONO_ADD_INS (bblock, copy);
6748                                 } else {
6749                                         MonoMethod *memcpy_method = get_memcpy_method ();
6750                                         MonoInst *iargs [3];
6751                                         iargs [0] = sp [0];
6752                                         iargs [1] = sp [1];
6753                                         NEW_ICONST (cfg, iargs [2], n);
6754
6755                                         mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
6756                                 }
6757                         }
6758                         ins_flag = 0;
6759                         ip += 5;
6760                         break;
6761                 case CEE_LDOBJ: {
6762                         MonoInst *iargs [3];
6763                         int loc_index = -1;
6764                         int stloc_len = 0;
6765                         guint32 align;
6766
6767                         CHECK_OPSIZE (5);
6768                         CHECK_STACK (1);
6769                         --sp;
6770                         token = read32 (ip + 1);
6771                         klass = mini_get_class (method, token, generic_context);
6772                         CHECK_TYPELOAD (klass);
6773                         if (generic_class_is_reference_type (cfg, klass)) {
6774                                 MONO_INST_NEW (cfg, ins, CEE_LDIND_REF);
6775                                 ins->inst_i0 = sp [0];
6776                                 ins->type = STACK_OBJ;
6777                                 ins->klass = klass;
6778                                 ins->flags |= ins_flag;
6779                                 ins_flag = 0;
6780                                 *sp++ = ins;
6781                                 ip += 5;
6782                                 break;
6783                         }
6784
6785                         /* Optimize the common ldobj+stloc combination */
6786                         switch (ip [5]) {
6787                         case CEE_STLOC_S:
6788                                 loc_index = ip [6];
6789                                 stloc_len = 2;
6790                                 break;
6791                         case CEE_STLOC_0:
6792                         case CEE_STLOC_1:
6793                         case CEE_STLOC_2:
6794                         case CEE_STLOC_3:
6795                                 loc_index = ip [5] - CEE_STLOC_0;
6796                                 stloc_len = 1;
6797                                 break;
6798                         default:
6799                                 break;
6800                         }
6801
6802                         if ((loc_index != -1) && ip_in_bb (cfg, bblock, ip + 5)) {
6803                                 CHECK_LOCAL (loc_index);
6804                                 NEW_LOCSTORE (cfg, ins, loc_index, *sp);
6805
6806                                 /* FIXME: handle CEE_STIND_R4 */
6807                                 if (ins->opcode == CEE_STOBJ) {
6808                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
6809                                         g_assert (ins->opcode == CEE_STOBJ);
6810                                         NEW_LOCLOADA (cfg, ins, loc_index);
6811                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
6812                                         ip += 5;
6813                                         ip += stloc_len;
6814                                         break;
6815                                 }
6816                         }
6817
6818                         n = mono_class_value_size (klass, &align);
6819                         ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
6820                         NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
6821                         if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
6822                                 MonoInst *copy;
6823                                 NEW_MEMCPY (cfg, copy, iargs [0], *sp, n, align);
6824                                 MONO_ADD_INS (bblock, copy);
6825                         } else {
6826                                 MonoMethod *memcpy_method = get_memcpy_method ();
6827                                 iargs [1] = *sp;
6828                                 NEW_ICONST (cfg, iargs [2], n);
6829
6830                                 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
6831                         }
6832                         NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
6833                         ++sp;
6834                         ip += 5;
6835                         ins_flag = 0;
6836                         inline_costs += 1;
6837                         break;
6838                 }
6839                 case CEE_LDSTR:
6840                         CHECK_STACK_OVF (1);
6841                         CHECK_OPSIZE (5);
6842                         n = read32 (ip + 1);
6843
6844                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
6845                                 /* FIXME: moving GC */
6846                                 NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, n));
6847                                 ins->type = STACK_OBJ;
6848                                 ins->klass = mono_defaults.string_class;
6849                                 *sp = ins;
6850                         }
6851                         else if (method->wrapper_type != MONO_WRAPPER_NONE) {
6852                                 int temp;
6853                                 MonoInst *iargs [1];
6854
6855                                 NEW_PCONST (cfg, iargs [0], mono_method_get_wrapper_data (method, n));                          
6856                                 temp = mono_emit_jit_icall (cfg, bblock, mono_string_new_wrapper, iargs, ip);
6857                                 NEW_TEMPLOAD (cfg, *sp, temp);
6858
6859                         } else {
6860
6861                                 if (cfg->opt & MONO_OPT_SHARED) {
6862                                         int temp;
6863                                         MonoInst *iargs [3];
6864                                         MonoInst* domain_var;
6865                                         
6866                                         if (cfg->compile_aot) {
6867                                                 /* FIXME: bug when inlining methods from different assemblies (n is a token valid just in one). */
6868                                                 cfg->ldstr_list = g_list_prepend (cfg->ldstr_list, GINT_TO_POINTER (n));
6869                                         }
6870                                         /* avoid depending on undefined C behavior in sequence points */
6871                                         domain_var = mono_get_domainvar (cfg);
6872                                         NEW_TEMPLOAD (cfg, iargs [0], domain_var->inst_c0);
6873                                         NEW_IMAGECONST (cfg, iargs [1], image);
6874                                         NEW_ICONST (cfg, iargs [2], mono_metadata_token_index (n));
6875                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldstr, iargs, ip);
6876                                         NEW_TEMPLOAD (cfg, *sp, temp);
6877                                         mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
6878                                 } else {
6879                                         if (bblock->out_of_line) {
6880                                                 MonoInst *iargs [2];
6881                                                 int temp;
6882
6883                                                 if (cfg->method->klass->image == mono_defaults.corlib) {
6884                                                         /* 
6885                                                          * Avoid relocations and save some code size by using a 
6886                                                          * version of helper_ldstr specialized to mscorlib.
6887                                                          */
6888                                                         NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (n));
6889                                                         temp = mono_emit_jit_icall (cfg, bblock, mono_helper_ldstr_mscorlib, iargs, ip);
6890                                                 } else {
6891                                                         /* Avoid creating the string object */
6892                                                         NEW_IMAGECONST (cfg, iargs [0], image);
6893                                                         NEW_ICONST (cfg, iargs [1], mono_metadata_token_index (n));
6894                                                         temp = mono_emit_jit_icall (cfg, bblock, mono_helper_ldstr, iargs, ip);
6895                                                 }
6896                                                 NEW_TEMPLOAD (cfg, *sp, temp);
6897                                         } 
6898                                         else
6899                                         if (cfg->compile_aot) {
6900                                                 NEW_LDSTRCONST (cfg, ins, image, n);
6901                                                 *sp = ins;
6902                                         } 
6903                                         else {
6904                                                 NEW_PCONST (cfg, ins, NULL);
6905                                                 ins->type = STACK_OBJ;
6906                                                 ins->inst_p0 = mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
6907                                                 ins->klass = mono_defaults.string_class;
6908                                                 *sp = ins;
6909                                         }
6910                                 }
6911                         }
6912
6913                         sp++;
6914                         ip += 5;
6915                         break;
6916                 case CEE_NEWOBJ: {
6917                         MonoInst *iargs [2];
6918                         MonoMethodSignature *fsig;
6919                         MonoInst this_ins;
6920                         int temp;
6921
6922                         CHECK_OPSIZE (5);
6923                         token = read32 (ip + 1);
6924                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
6925                         if (!cmethod)
6926                                 goto load_error;
6927                         fsig = mono_method_get_signature (cmethod, image, token);
6928
6929                         mono_save_token_info (cfg, image, token, cmethod);
6930
6931                         if (!mono_class_init (cmethod->klass))
6932                                 goto load_error;
6933
6934                         if (cfg->generic_sharing_context)
6935                                 context_used = mono_method_check_context_used (cmethod);
6936
6937                         if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
6938                                 if (check_linkdemand (cfg, method, cmethod, bblock, ip))
6939                                         INLINE_FAILURE;
6940                                 CHECK_CFG_EXCEPTION;
6941                         } else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
6942                                 ensure_method_is_allowed_to_call_method (cfg, method, cmethod, bblock, ip);
6943                         }
6944
6945                         n = fsig->param_count;
6946                         CHECK_STACK (n);
6947  
6948                         /* 
6949                          * Generate smaller code for the common newobj <exception> instruction in
6950                          * argument checking code.
6951                          */
6952                         if (bblock->out_of_line && cmethod->klass->image == mono_defaults.corlib && n <= 2 && 
6953                                 ((n < 1) || (!fsig->params [0]->byref && fsig->params [0]->type == MONO_TYPE_STRING)) && 
6954                                 ((n < 2) || (!fsig->params [1]->byref && fsig->params [1]->type == MONO_TYPE_STRING))) {
6955                                 MonoInst *iargs [3];
6956                                 int temp;
6957                                 
6958                                 sp -= n;
6959
6960                                 NEW_ICONST (cfg, iargs [0], cmethod->klass->type_token);
6961                                 switch (n) {
6962                                 case 0:
6963                                         temp = mono_emit_jit_icall (cfg, bblock, mono_create_corlib_exception_0, iargs, ip);
6964                                         break;
6965                                 case 1:
6966                                         iargs [1] = sp [0];
6967                                         temp = mono_emit_jit_icall (cfg, bblock, mono_create_corlib_exception_1, iargs, ip);
6968                                         break;
6969                                 case 2:
6970                                         iargs [1] = sp [0];
6971                                         iargs [2] = sp [1];
6972                                         temp = mono_emit_jit_icall (cfg, bblock, mono_create_corlib_exception_2, iargs, ip);
6973                                         break;
6974                                 default:
6975                                         g_assert_not_reached ();
6976                                 }
6977                                 NEW_TEMPLOAD (cfg, ins, temp);
6978                                 *sp ++ = ins;
6979
6980                                 ip += 5;
6981                                 inline_costs += 5;
6982                                 break;
6983                         }
6984
6985                         /* move the args to allow room for 'this' in the first position */
6986                         while (n--) {
6987                                 --sp;
6988                                 sp [1] = sp [0];
6989                         }
6990
6991                         /* check_call_signature () requires sp[0] to be set */
6992                         this_ins.type = STACK_OBJ;
6993                         sp [0] = &this_ins;
6994                         if (check_call_signature (cfg, fsig, sp))
6995                                 UNVERIFIED;
6996
6997                         handle_loaded_temps (cfg, bblock, stack_start, sp);
6998
6999                         if (mini_class_is_system_array (cmethod->klass)) {
7000                                 g_assert (!context_used);
7001
7002                                 NEW_METHODCONST (cfg, *sp, cmethod);
7003                                 temp = handle_array_new (cfg, bblock, fsig->param_count, sp, ip);
7004                         } else if (cmethod->string_ctor) {
7005                                 g_assert (!context_used);
7006
7007                                 /* we simply pass a null pointer */
7008                                 NEW_PCONST (cfg, *sp, NULL); 
7009                                 /* now call the string ctor */
7010                                 temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, NULL);
7011                         } else {
7012                                 MonoInst* callvirt_this_arg = NULL;
7013                                 
7014                                 if (cmethod->klass->valuetype) {
7015                                         iargs [0] = mono_compile_create_var (cfg, &cmethod->klass->byval_arg, OP_LOCAL);
7016                                         temp = iargs [0]->inst_c0;
7017
7018                                         NEW_TEMPLOADA (cfg, *sp, temp);
7019
7020                                         handle_initobj (cfg, bblock, *sp, NULL, cmethod->klass, stack_start, sp);
7021
7022                                         NEW_TEMPLOADA (cfg, *sp, temp);
7023
7024                                         /* 
7025                                          * The code generated by mini_emit_virtual_call () expects
7026                                          * iargs [0] to be a boxed instance, but luckily the vcall
7027                                          * will be transformed into a normal call there.
7028                                          */
7029                                 } else if (context_used) {
7030                                         MonoInst *rgctx, *data;
7031                                         int rgctx_info;
7032
7033                                         GET_RGCTX (rgctx, context_used);
7034                                         if (cfg->opt & MONO_OPT_SHARED)
7035                                                 rgctx_info = MONO_RGCTX_INFO_KLASS;
7036                                         else
7037                                                 rgctx_info = MONO_RGCTX_INFO_VTABLE;
7038                                         data = get_runtime_generic_context_ptr (cfg, method, context_used, bblock,
7039                                                 cmethod->klass, generic_context, rgctx, rgctx_info, ip);
7040
7041                                         temp = handle_alloc_from_inst (cfg, bblock, cmethod->klass, data, FALSE, ip);
7042                                         NEW_TEMPLOAD (cfg, *sp, temp);
7043                                 } else {
7044                                         MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
7045
7046                                         CHECK_TYPELOAD (cmethod->klass);
7047                                         if (mini_field_access_needs_cctor_run (cfg, method, vtable) && !(g_slist_find (class_inits, vtable))) {
7048                                                 guint8 *tramp = mono_create_class_init_trampoline (vtable);
7049                                                 mono_emit_native_call (cfg, bblock, tramp, 
7050                                                                                            helper_sig_class_init_trampoline,
7051                                                                                            NULL, ip, FALSE, FALSE);
7052                                                 if (cfg->verbose_level > 2)
7053                                                         g_print ("class %s.%s needs init call for ctor\n", cmethod->klass->name_space, cmethod->klass->name);
7054                                                 class_inits = g_slist_prepend (class_inits, vtable);
7055                                         }
7056                                         temp = handle_alloc (cfg, bblock, cmethod->klass, FALSE, ip);
7057                                         NEW_TEMPLOAD (cfg, *sp, temp);
7058                                 }
7059
7060                                 /* Avoid virtual calls to ctors if possible */
7061                                 if (cmethod->klass->marshalbyref)
7062                                         callvirt_this_arg = sp [0];
7063                                 
7064                                 if ((cfg->opt & MONO_OPT_INLINE) && cmethod && !context_used &&
7065                                     mono_method_check_inlining (cfg, cmethod) &&
7066                                     !mono_class_is_subclass_of (cmethod->klass, mono_defaults.exception_class, FALSE) &&
7067                                     !g_list_find (dont_inline, cmethod)) {
7068                                         int costs;
7069                                         MonoBasicBlock *ebblock;
7070                                         if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock, FALSE))) {
7071
7072                                                 ip += 5;
7073                                                 real_offset += 5;
7074                                                 
7075                                                 GET_BBLOCK (cfg, bblock, ip);
7076                                                 ebblock->next_bb = bblock;
7077                                                 link_bblock (cfg, ebblock, bblock);
7078
7079                                                 NEW_TEMPLOAD (cfg, *sp, temp);
7080                                                 sp++;
7081
7082                                                 /* indicates start of a new block, and triggers a load 
7083                                                    of all stack arguments at bb boundarie */
7084                                                 bblock = ebblock;
7085
7086                                                 inline_costs += costs;
7087                                                 break;
7088                                                 
7089                                         } else {
7090                                                 /* Prevent inlining of methods which call other methods */
7091                                                 INLINE_FAILURE;
7092                                                 mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, callvirt_this_arg);
7093                                         }
7094                                 } else if (context_used &&
7095                                                 (cmethod->klass->valuetype ||
7096                                                 !mono_method_is_generic_sharable_impl (cmethod, TRUE))) {
7097                                         MonoInst *rgctx, *cmethod_addr;
7098
7099                                         g_assert (!callvirt_this_arg);
7100
7101                                         GET_RGCTX (rgctx, context_used);
7102                                         cmethod_addr = get_runtime_generic_context_method (cfg, method, context_used,
7103                                                         bblock, cmethod,
7104                                                         generic_context, rgctx, MONO_RGCTX_INFO_GENERIC_METHOD_CODE, ip);
7105
7106                                         mono_emit_calli_spilled (cfg, bblock, fsig, sp, cmethod_addr, ip);
7107                                 } else {
7108                                         /* Prevent inlining of methods which call other methods */
7109                                         INLINE_FAILURE;
7110                                         /* now call the actual ctor */
7111                                         mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, callvirt_this_arg);
7112                                 }
7113                         }
7114
7115                         NEW_TEMPLOAD (cfg, *sp, temp);
7116                         sp++;
7117                         
7118                         ip += 5;
7119                         inline_costs += 5;
7120                         break;
7121                 }
7122                 case CEE_ISINST:
7123                         CHECK_STACK (1);
7124                         --sp;
7125                         CHECK_OPSIZE (5);
7126                         token = read32 (ip + 1);
7127                         klass = mini_get_class (method, token, generic_context);
7128                         CHECK_TYPELOAD (klass);
7129                         if (sp [0]->type != STACK_OBJ)
7130                                 UNVERIFIED;
7131
7132                         if (cfg->generic_sharing_context)
7133                                 context_used = mono_class_check_context_used (klass);
7134
7135                         /* Needed by the code generated in inssel.brg */
7136                         if (!context_used)
7137                                 mono_get_got_var (cfg);
7138
7139                         if (context_used) {
7140                                 MonoInst *rgctx, *args [2];
7141                                 int temp;
7142
7143                                 /* obj */
7144                                 args [0] = *sp;
7145
7146                                 /* klass */
7147                                 GET_RGCTX (rgctx, context_used);
7148                                 args [1] = get_runtime_generic_context_ptr (cfg, method, context_used, bblock, klass,
7149                                         generic_context, rgctx, MONO_RGCTX_INFO_KLASS, ip);
7150
7151                                 temp = mono_emit_jit_icall (cfg, bblock, mono_object_isinst, args, ip);
7152                                 NEW_TEMPLOAD (cfg, *sp, temp);
7153
7154                                 sp++;
7155                                 ip += 5;
7156                                 inline_costs += 2;
7157                         } else if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
7158                         
7159                                 MonoMethod *mono_isinst;
7160                                 MonoInst *iargs [1];
7161                                 MonoBasicBlock *ebblock;
7162                                 int costs;
7163                                 int temp;
7164                                 
7165                                 mono_isinst = mono_marshal_get_isinst (klass); 
7166                                 iargs [0] = sp [0];
7167                                 
7168                                 costs = inline_method (cfg, mono_isinst, mono_method_signature (mono_isinst), bblock, 
7169                                                        iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
7170                         
7171                                 g_assert (costs > 0);
7172                                 
7173                                 ip += 5;
7174                                 real_offset += 5;
7175                         
7176                                 GET_BBLOCK (cfg, bblock, ip);
7177                                 ebblock->next_bb = bblock;
7178                                 link_bblock (cfg, ebblock, bblock);
7179
7180                                 temp = iargs [0]->inst_i0->inst_c0;
7181                                 NEW_TEMPLOAD (cfg, *sp, temp);
7182                                 
7183                                 sp++;
7184                                 bblock = ebblock;
7185                                 inline_costs += costs;
7186                         } else {
7187                                 MONO_INST_NEW (cfg, ins, *ip);
7188                                 ins->type = STACK_OBJ;
7189                                 ins->inst_left = *sp;
7190                                 ins->inst_newa_class = klass;
7191                                 ins->klass = klass;
7192                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 5);
7193                                 ip += 5;
7194                         }
7195                         break;
7196                 case CEE_UNBOX_ANY: {
7197                         MonoInst *iargs [3];
7198                         guint32 align;
7199
7200                         CHECK_STACK (1);
7201                         --sp;
7202                         CHECK_OPSIZE (5);
7203                         token = read32 (ip + 1);
7204                         klass = mini_get_class (method, token, generic_context);
7205                         CHECK_TYPELOAD (klass);
7206
7207                         if (cfg->generic_sharing_context)
7208                                 context_used = mono_class_check_context_used (klass);
7209
7210                         if (generic_class_is_reference_type (cfg, klass)) {
7211                                 switch (emit_castclass (klass, token, context_used, FALSE,
7212                                                 cfg, method, arg_array, param_types, dont_inline, end, header,
7213                                                 generic_context, &bblock, &ip, &sp, &inline_costs, &real_offset)) {
7214                                 case 0: break;
7215                                 case -1: goto unverified;
7216                                 case -2: goto exception_exit;
7217                                 default: g_assert_not_reached ();
7218                                 }
7219                                 break;
7220                         }
7221
7222                         if (mono_class_is_nullable (klass)) {
7223                                 int v;
7224                                 MonoInst *rgctx = NULL;
7225
7226                                 if (context_used)
7227                                         GET_RGCTX (rgctx, context_used);
7228
7229                                 v = handle_unbox_nullable (cfg, method, context_used, bblock, *sp, ip, klass,
7230                                         generic_context, rgctx);
7231                                 NEW_TEMPLOAD (cfg, *sp, v);
7232                                 sp ++;
7233                                 ip += 5;
7234                                 break;
7235                         }
7236
7237                         switch (emit_unbox (klass, token, context_used,
7238                                         cfg, method, arg_array, param_types, dont_inline, end, header,
7239                                         generic_context, &bblock, &ip, &sp, &inline_costs, &real_offset)) {
7240                         case 0: break;
7241                         case -1: goto unverified;
7242                         case -2: goto exception_exit;
7243                         default: g_assert_not_reached ();
7244                         }
7245                         ip += 5;
7246                         /* LDOBJ impl */
7247                         n = mono_class_value_size (klass, &align);
7248                         ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
7249                         NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
7250                         if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
7251                                 MonoInst *copy;
7252                                 NEW_MEMCPY (cfg, copy, iargs [0], *sp, n, align);
7253                                 MONO_ADD_INS (bblock, copy);
7254                         } else {
7255                                 MonoMethod *memcpy_method = get_memcpy_method ();
7256                                 iargs [1] = *sp;
7257                                 NEW_ICONST (cfg, iargs [2], n);
7258
7259                                 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
7260                         }
7261                         NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
7262                         ++sp;
7263                         inline_costs += 2;
7264                         break;
7265                 }
7266                 case CEE_UNBOX:
7267                         CHECK_STACK (1);
7268                         --sp;
7269                         CHECK_OPSIZE (5);
7270                         token = read32 (ip + 1);
7271                         klass = mini_get_class (method, token, generic_context);
7272                         CHECK_TYPELOAD (klass);
7273
7274                         if (cfg->generic_sharing_context)
7275                                 context_used = mono_class_check_context_used (klass);
7276
7277                         if (mono_class_is_nullable (klass)) {
7278                                 int v;
7279                                 MonoInst *rgctx = NULL;
7280
7281                                 if (context_used)
7282                                         GET_RGCTX (rgctx, context_used);
7283                                 v = handle_unbox_nullable (cfg, method, context_used, bblock, *sp, ip, klass,
7284                                         generic_context, rgctx);
7285                                 NEW_TEMPLOAD (cfg, *sp, v);
7286                                 sp ++;
7287                                 ip += 5;
7288                                 break;
7289                         }
7290
7291                         switch (emit_unbox (klass, token, context_used,
7292                                         cfg, method, arg_array, param_types, dont_inline, end, header,
7293                                         generic_context, &bblock, &ip, &sp, &inline_costs, &real_offset)) {
7294                         case 0: break;
7295                         case -1: goto unverified;
7296                         case -2: goto exception_exit;
7297                         default: g_assert_not_reached ();
7298                         }
7299
7300                         sp++;
7301                         ip += 5;
7302                         inline_costs += 2;
7303                         break;
7304                 case CEE_CASTCLASS:
7305                         CHECK_STACK (1);
7306                         --sp;
7307                         CHECK_OPSIZE (5);
7308                         token = read32 (ip + 1);
7309                         klass = mini_get_class (method, token, generic_context);
7310                         CHECK_TYPELOAD (klass);
7311                         if (sp [0]->type != STACK_OBJ)
7312                                 UNVERIFIED;
7313
7314                         if (cfg->generic_sharing_context)
7315                                 context_used = mono_class_check_context_used (klass);
7316
7317                         switch (emit_castclass (klass, token, context_used, TRUE,
7318                                         cfg, method, arg_array, param_types, dont_inline, end, header,
7319                                         generic_context, &bblock, &ip, &sp, &inline_costs, &real_offset)) {
7320                         case 0: break;
7321                         case -1: goto unverified;
7322                         case -2: goto exception_exit;
7323                         default: g_assert_not_reached ();
7324                         }
7325                         break;
7326                 case CEE_THROW:
7327                         CHECK_STACK (1);
7328                         MONO_INST_NEW (cfg, ins, OP_THROW);
7329                         --sp;
7330                         ins->inst_left = *sp;
7331                         ip++;
7332                         bblock->out_of_line = TRUE;
7333                         MONO_ADD_INS (bblock, ins);
7334                         MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
7335                         ins->cil_code = ip - 1;
7336                         MONO_ADD_INS (bblock, ins);
7337                         sp = stack_start;
7338                         
7339                         link_bblock (cfg, bblock, end_bblock);
7340                         start_new_bblock = 1;
7341                         break;
7342                 case CEE_LDFLD:
7343                 case CEE_LDFLDA:
7344                 case CEE_STFLD: {
7345                         MonoInst *offset_ins;
7346                         MonoClassField *field;
7347                         MonoBasicBlock *ebblock;
7348                         int costs;
7349                         guint foffset;
7350
7351                         if (*ip == CEE_STFLD) {
7352                                 CHECK_STACK (2);
7353                                 sp -= 2;
7354                         } else {
7355                                 CHECK_STACK (1);
7356                                 --sp;
7357                         }
7358                         if (sp [0]->type == STACK_I4 || sp [0]->type == STACK_I8 || sp [0]->type == STACK_R8)
7359                                 UNVERIFIED;
7360                         if (*ip != CEE_LDFLD && sp [0]->type == STACK_VTYPE)
7361                                 UNVERIFIED;
7362                         CHECK_OPSIZE (5);
7363                         token = read32 (ip + 1);
7364                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
7365                                 field = mono_method_get_wrapper_data (method, token);
7366                                 klass = field->parent;
7367                         } else {
7368                                 field = mono_field_from_token (image, token, &klass, generic_context);
7369                         }
7370                         if (!field)
7371                                 goto load_error;
7372                         mono_class_init (klass);
7373                         if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_field (method, field))
7374                                 FIELD_ACCESS_FAILURE;
7375
7376                         foffset = klass->valuetype? field->offset - sizeof (MonoObject): field->offset;
7377                         /* FIXME: mark instructions for use in SSA */
7378                         if (*ip == CEE_STFLD) {
7379                                 if (target_type_is_incompatible (cfg, field->type, sp [1]))
7380                                         UNVERIFIED;
7381                                 if ((klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) || klass->contextbound || klass == mono_defaults.marshalbyrefobject_class) {
7382                                         MonoMethod *stfld_wrapper = mono_marshal_get_stfld_wrapper (field->type); 
7383                                         MonoInst *iargs [5];
7384
7385                                         iargs [0] = sp [0];
7386                                         NEW_CLASSCONST (cfg, iargs [1], klass);
7387                                         NEW_FIELDCONST (cfg, iargs [2], field);
7388                                         NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : 
7389                                                     field->offset);
7390                                         iargs [4] = sp [1];
7391
7392                                         if (cfg->opt & MONO_OPT_INLINE) {
7393                                                 costs = inline_method (cfg, stfld_wrapper, mono_method_signature (stfld_wrapper), bblock, 
7394                                                                 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
7395                                                 g_assert (costs > 0);
7396                                                       
7397                                                 ip += 5;
7398                                                 real_offset += 5;
7399
7400                                                 GET_BBLOCK (cfg, bblock, ip);
7401                                                 ebblock->next_bb = bblock;
7402                                                 link_bblock (cfg, ebblock, bblock);
7403
7404                                                 /* indicates start of a new block, and triggers a load 
7405                                                    of all stack arguments at bb boundarie */
7406                                                 bblock = ebblock;
7407
7408                                                 inline_costs += costs;
7409                                                 break;
7410                                         } else {
7411                                                 mono_emit_method_call_spilled (cfg, bblock, stfld_wrapper, mono_method_signature (stfld_wrapper), iargs, ip, NULL);
7412                                         }
7413 #if HAVE_WRITE_BARRIERS
7414                                 } else if (mini_type_to_stind (cfg, field->type) == CEE_STIND_REF && !(sp [1]->opcode == OP_PCONST && sp [1]->inst_c0 == 0)) {
7415                                         /* insert call to write barrier */
7416                                         MonoMethod *write_barrier = mono_marshal_get_write_barrier ();
7417                                         MonoInst *iargs [2];
7418                                         NEW_ICONST (cfg, offset_ins, foffset);
7419                                         MONO_INST_NEW (cfg, ins, OP_PADD);
7420                                         ins->inst_left = *sp;
7421                                         ins->inst_right = offset_ins;
7422                                         ins->type = STACK_MP;
7423                                         ins->klass = mono_defaults.object_class;
7424                                         iargs [0] = ins;
7425                                         iargs [1] = sp [1];
7426                                         mono_emit_method_call_spilled (cfg, bblock, write_barrier, mono_method_signature (write_barrier), iargs, ip, NULL);
7427 #endif
7428 #ifdef MONO_ARCH_SOFT_FLOAT
7429                                 } else if (mini_type_to_stind (cfg, field->type) == CEE_STIND_R4) {
7430                                         NEW_ICONST (cfg, offset_ins, foffset);
7431                                         MONO_INST_NEW (cfg, ins, OP_PADD);
7432                                         ins->inst_left = *sp;
7433                                         ins->inst_right = offset_ins;
7434                                         ins->type = STACK_MP;
7435                                         ins->klass = mono_defaults.object_class;
7436                                         handle_store_float (cfg, bblock, ins, sp [1], ip);
7437 #endif
7438                                 } else {
7439                                         MonoInst *store;
7440                                         NEW_ICONST (cfg, offset_ins, foffset);
7441                                         MONO_INST_NEW (cfg, ins, OP_PADD);
7442                                         ins->inst_left = *sp;
7443                                         ins->inst_right = offset_ins;
7444                                         ins->type = STACK_MP;
7445
7446                                         MONO_INST_NEW (cfg, store, mini_type_to_stind (cfg, field->type));
7447                                         store->inst_left = ins;
7448                                         store->inst_right = sp [1];
7449                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
7450                                         store->flags |= ins_flag;
7451                                         ins_flag = 0;
7452                                         if (store->opcode == CEE_STOBJ) {
7453                                                 handle_stobj (cfg, bblock, ins, sp [1], ip, 
7454                                                               mono_class_from_mono_type (field->type), FALSE, FALSE, TRUE);
7455                                         } else
7456                                                 MONO_ADD_INS (bblock, store);
7457                                 }
7458                         } else {
7459                                 if ((klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) || klass->contextbound || klass == mono_defaults.marshalbyrefobject_class) {
7460                                         MonoMethod *wrapper = (*ip == CEE_LDFLDA) ? mono_marshal_get_ldflda_wrapper (field->type) : mono_marshal_get_ldfld_wrapper (field->type); 
7461                                         MonoInst *iargs [4];
7462                                         int temp;
7463                                         
7464                                         iargs [0] = sp [0];
7465                                         NEW_CLASSCONST (cfg, iargs [1], klass);
7466                                         NEW_FIELDCONST (cfg, iargs [2], field);
7467                                         NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
7468                                         if ((cfg->opt & MONO_OPT_INLINE) && !MONO_TYPE_ISSTRUCT (mono_method_signature (wrapper)->ret)) {
7469                                                 costs = inline_method (cfg, wrapper, mono_method_signature (wrapper), bblock, 
7470                                                                 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
7471                                                 g_assert (costs > 0);
7472                                                       
7473                                                 ip += 5;
7474                                                 real_offset += 5;
7475
7476                                                 GET_BBLOCK (cfg, bblock, ip);
7477                                                 ebblock->next_bb = bblock;
7478                                                 link_bblock (cfg, ebblock, bblock);
7479
7480                                                 temp = iargs [0]->inst_i0->inst_c0;
7481
7482                                                 NEW_TEMPLOAD (cfg, *sp, temp);
7483                                                 sp++;
7484
7485                                                 /* indicates start of a new block, and triggers a load of
7486                                                    all stack arguments at bb boundarie */
7487                                                 bblock = ebblock;
7488                                                 
7489                                                 inline_costs += costs;
7490                                                 break;
7491                                         } else {
7492                                                 temp = mono_emit_method_call_spilled (cfg, bblock, wrapper, mono_method_signature (wrapper), iargs, ip, NULL);
7493                                                 NEW_TEMPLOAD (cfg, *sp, temp);
7494                                                 NEW_TEMPLOAD_SOFT_FLOAT (cfg, bblock, *sp, temp);
7495                                                 sp++;
7496                                         }
7497                                 } else {
7498                                         NEW_ICONST (cfg, offset_ins, foffset);
7499                                         MONO_INST_NEW (cfg, ins, OP_PADD);
7500                                         ins->inst_left = *sp;
7501                                         ins->inst_right = offset_ins;
7502                                         ins->type = STACK_MP;
7503
7504                                         if (*ip == CEE_LDFLDA) {
7505                                                 ins->klass = mono_class_from_mono_type (field->type);
7506                                                 *sp++ = ins;
7507                                         } else {
7508                                                 MonoInst *load;
7509                                                 MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, field->type));
7510                                                 type_to_eval_stack_type (cfg, field->type, load);
7511                                                 load->inst_left = ins;
7512                                                 load->flags |= ins_flag;
7513                                                 ins_flag = 0;
7514 #ifdef MONO_ARCH_SOFT_FLOAT
7515                                                 if (mini_type_to_ldind (cfg, field->type) == CEE_LDIND_R4) {
7516                                                         int temp;
7517                                                         temp = handle_load_float (cfg, bblock, ins, ip);
7518                                                         NEW_TEMPLOAD (cfg, *sp, temp);
7519                                                         sp++;
7520                                                 } else
7521 #endif
7522                                                 *sp++ = load;
7523                                         }
7524                                 }
7525                         }
7526                         ip += 5;
7527                         break;
7528                 }
7529                 case CEE_LDSFLD:
7530                 case CEE_LDSFLDA:
7531                 case CEE_STSFLD: {
7532                         MonoClassField *field;
7533                         gboolean is_special_static;
7534                         gpointer addr = NULL;
7535
7536                         CHECK_OPSIZE (5);
7537                         token = read32 (ip + 1);
7538                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
7539                                 field = mono_method_get_wrapper_data (method, token);
7540                                 klass = field->parent;
7541                         }
7542                         else
7543                                 field = mono_field_from_token (image, token, &klass, generic_context);
7544                         if (!field)
7545                                 goto load_error;
7546                         mono_class_init (klass);
7547                         if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_field (method, field))
7548                                 FIELD_ACCESS_FAILURE;
7549
7550                         /*
7551                          * We can only support shared generic static
7552                          * field access on architectures where the
7553                          * trampoline code has been extended to handle
7554                          * the generic class init.
7555                          */
7556 #ifndef MONO_ARCH_VTABLE_REG
7557                         GENERIC_SHARING_FAILURE (*ip);
7558 #endif
7559
7560                         if (cfg->generic_sharing_context)
7561                                 context_used = mono_class_check_context_used (klass);
7562
7563                         g_assert (!(field->type->attrs & FIELD_ATTRIBUTE_LITERAL));
7564
7565                         if ((*ip) == CEE_STSFLD)
7566                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
7567
7568                         is_special_static = mono_class_field_is_special_static (field);
7569
7570                         if ((cfg->opt & MONO_OPT_SHARED) ||
7571                                         (cfg->compile_aot && is_special_static) ||
7572                                         (context_used && is_special_static)) {
7573                                 int temp;
7574                                 MonoInst *iargs [2];
7575
7576                                 g_assert (field->parent);
7577                                 if ((cfg->opt & MONO_OPT_SHARED) || cfg->compile_aot) {
7578                                         MonoInst *domain_var;
7579                                         /* avoid depending on undefined C behavior in sequence points */
7580                                         domain_var = mono_get_domainvar (cfg);
7581                                         NEW_TEMPLOAD (cfg, iargs [0], domain_var->inst_c0);
7582                                 } else {
7583                                         NEW_DOMAINCONST (cfg, iargs [0]);
7584                                 }
7585                                 if (context_used) {
7586                                         MonoInst *rgctx;
7587
7588                                         GET_RGCTX (rgctx, context_used);
7589                                         iargs [1] = get_runtime_generic_context_field (cfg, method, context_used,
7590                                                         bblock, field,
7591                                                         generic_context, rgctx, MONO_RGCTX_INFO_CLASS_FIELD, ip);
7592                                 } else {
7593                                         NEW_FIELDCONST (cfg, iargs [1], field);
7594                                 }
7595                                 temp = mono_emit_jit_icall (cfg, bblock, mono_class_static_field_address, iargs, ip);
7596                                 NEW_TEMPLOAD (cfg, ins, temp);
7597                         } else if (context_used) {
7598                                 MonoInst *rgctx, *static_data;
7599
7600                                 /*
7601                                 g_print ("sharing static field access in %s.%s.%s - depth %d offset %d\n",
7602                                         method->klass->name_space, method->klass->name, method->name,
7603                                         depth, field->offset);
7604                                 */
7605
7606                                 if (mono_class_needs_cctor_run (klass, method)) {
7607                                         MonoMethodSignature *sig = helper_sig_generic_class_init_trampoline;
7608                                         MonoCallInst *call;
7609                                         MonoInst *vtable, *rgctx;
7610
7611                                         GET_RGCTX (rgctx, context_used);
7612                                         vtable = get_runtime_generic_context_ptr (cfg, method, context_used, bblock, klass,
7613                                                         generic_context, rgctx, MONO_RGCTX_INFO_VTABLE, ip);
7614
7615                                         call = mono_emit_call_args (cfg, bblock, sig, NULL, FALSE, FALSE, ip, FALSE);
7616                                         call->inst.opcode = OP_TRAMPCALL_VTABLE;
7617                                         call->fptr = mono_get_trampoline_code (MONO_TRAMPOLINE_GENERIC_CLASS_INIT);
7618
7619                                         call->inst.inst_left = vtable;
7620
7621                                         mono_spill_call (cfg, bblock, call, sig, FALSE, ip, FALSE);
7622                                 }
7623
7624                                 /*
7625                                  * The pointer we're computing here is
7626                                  *
7627                                  *   super_info.static_data + field->offset
7628                                  */
7629                                 GET_RGCTX (rgctx, context_used);
7630                                 static_data = get_runtime_generic_context_ptr (cfg, method, context_used, bblock, klass,
7631                                         generic_context, rgctx, MONO_RGCTX_INFO_STATIC_DATA, ip);
7632
7633                                 if (field->offset == 0) {
7634                                         ins = static_data;
7635                                 } else {
7636                                         MonoInst *field_offset;
7637
7638                                         NEW_ICONST (cfg, field_offset, field->offset);
7639
7640                                         MONO_INST_NEW (cfg, ins, OP_PADD);
7641                                         ins->inst_left = static_data;
7642                                         ins->inst_right = field_offset;
7643                                         ins->type = STACK_PTR;
7644                                         ins->klass = klass;
7645                                 }
7646                         } else {
7647                                 MonoVTable *vtable;
7648
7649                                 vtable = mono_class_vtable (cfg->domain, klass);
7650                                 CHECK_TYPELOAD (klass);
7651                                 if (!is_special_static) {
7652                                         if (mini_field_access_needs_cctor_run (cfg, method, vtable) && !(g_slist_find (class_inits, vtable))) {
7653                                                 guint8 *tramp = mono_create_class_init_trampoline (vtable);
7654                                                 mono_emit_native_call (cfg, bblock, tramp, 
7655                                                                                            helper_sig_class_init_trampoline,
7656                                                                                            NULL, ip, FALSE, FALSE);
7657                                                 if (cfg->verbose_level > 2)
7658                                                         g_print ("class %s.%s needs init call for %s\n", klass->name_space, klass->name, field->name);
7659                                                 class_inits = g_slist_prepend (class_inits, vtable);
7660                                         } else {
7661                                                 if (cfg->run_cctors) {
7662                                                         /* This makes so that inline cannot trigger */
7663                                                         /* .cctors: too many apps depend on them */
7664                                                         /* running with a specific order... */
7665                                                         if (! vtable->initialized)
7666                                                                 INLINE_FAILURE;
7667                                                         mono_runtime_class_init (vtable);
7668                                                 }
7669                                         }
7670                                         addr = (char*)vtable->data + field->offset;
7671
7672                                         if (cfg->compile_aot)
7673                                                 NEW_SFLDACONST (cfg, ins, field);
7674                                         else
7675                                                 NEW_PCONST (cfg, ins, addr);
7676                                 } else {
7677                                         int temp;
7678                                         MonoInst *iargs [1];
7679
7680                                         /* The special_static_fields
7681                                          * field is init'd in
7682                                          * mono_class_vtable, so it
7683                                          * needs to be called here.
7684                                          */
7685                                         if (!(cfg->opt & MONO_OPT_SHARED)) {
7686                                                 mono_class_vtable (cfg->domain, klass);
7687                                                 CHECK_TYPELOAD (klass);
7688                                         }
7689                                         mono_domain_lock (cfg->domain);
7690                                         if (cfg->domain->special_static_fields)
7691                                                 addr = g_hash_table_lookup (cfg->domain->special_static_fields, field);
7692                                         mono_domain_unlock (cfg->domain);
7693
7694                                         /* 
7695                                          * insert call to mono_threads_get_static_data (GPOINTER_TO_UINT (addr)) 
7696                                          * This could be later optimized to do just a couple of
7697                                          * memory dereferences with constant offsets.
7698                                          */
7699                                         NEW_ICONST (cfg, iargs [0], GPOINTER_TO_UINT (addr));
7700                                         temp = mono_emit_jit_icall (cfg, bblock, mono_get_special_static_data, iargs, ip);
7701                                         NEW_TEMPLOAD (cfg, ins, temp);
7702                                 }
7703                         }
7704
7705                         /* FIXME: mark instructions for use in SSA */
7706                         if (*ip == CEE_LDSFLDA) {
7707                                 ins->klass = mono_class_from_mono_type (field->type);
7708                                 *sp++ = ins;
7709                         } else if (*ip == CEE_STSFLD) {
7710                                 MonoInst *store;
7711                                 CHECK_STACK (1);
7712                                 sp--;
7713                                 MONO_INST_NEW (cfg, store, mini_type_to_stind (cfg, field->type));
7714                                 store->inst_left = ins;
7715                                 store->inst_right = sp [0];
7716                                 store->flags |= ins_flag;
7717                                 ins_flag = 0;
7718
7719 #ifdef MONO_ARCH_SOFT_FLOAT
7720                                 if (store->opcode == CEE_STIND_R4)
7721                                         handle_store_float (cfg, bblock, ins, sp [0], ip);
7722                                 else
7723 #endif
7724                                 if (store->opcode == CEE_STOBJ) {
7725                                         handle_stobj (cfg, bblock, ins, sp [0], ip, mono_class_from_mono_type (field->type), FALSE, FALSE, FALSE);
7726                                 } else
7727                                         MONO_ADD_INS (bblock, store);
7728                         } else {
7729                                 gboolean is_const = FALSE;
7730                                 MonoVTable *vtable = NULL;
7731
7732                                 if (!context_used)
7733                                         vtable = mono_class_vtable (cfg->domain, klass);
7734
7735                                 CHECK_TYPELOAD (klass);
7736                                 if (!context_used && !((cfg->opt & MONO_OPT_SHARED) || cfg->compile_aot) && 
7737                                     vtable->initialized && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY)) {
7738                                         gpointer addr = (char*)vtable->data + field->offset;
7739                                         int ro_type = field->type->type;
7740                                         if (ro_type == MONO_TYPE_VALUETYPE && field->type->data.klass->enumtype) {
7741                                                 ro_type = field->type->data.klass->enum_basetype->type;
7742                                         }
7743                                         /* g_print ("RO-FIELD %s.%s:%s\n", klass->name_space, klass->name, field->name);*/
7744                                         is_const = TRUE;
7745                                         switch (ro_type) {
7746                                         case MONO_TYPE_BOOLEAN:
7747                                         case MONO_TYPE_U1:
7748                                                 NEW_ICONST (cfg, *sp, *((guint8 *)addr));
7749                                                 sp++;
7750                                                 break;
7751                                         case MONO_TYPE_I1:
7752                                                 NEW_ICONST (cfg, *sp, *((gint8 *)addr));
7753                                                 sp++;
7754                                                 break;                                          
7755                                         case MONO_TYPE_CHAR:
7756                                         case MONO_TYPE_U2:
7757                                                 NEW_ICONST (cfg, *sp, *((guint16 *)addr));
7758                                                 sp++;
7759                                                 break;
7760                                         case MONO_TYPE_I2:
7761                                                 NEW_ICONST (cfg, *sp, *((gint16 *)addr));
7762                                                 sp++;
7763                                                 break;
7764                                                 break;
7765                                         case MONO_TYPE_I4:
7766                                                 NEW_ICONST (cfg, *sp, *((gint32 *)addr));
7767                                                 sp++;
7768                                                 break;                                          
7769                                         case MONO_TYPE_U4:
7770                                                 NEW_ICONST (cfg, *sp, *((guint32 *)addr));
7771                                                 sp++;
7772                                                 break;
7773 #ifndef HAVE_MOVING_COLLECTOR
7774                                         case MONO_TYPE_I:
7775                                         case MONO_TYPE_U:
7776                                         case MONO_TYPE_STRING:
7777                                         case MONO_TYPE_OBJECT:
7778                                         case MONO_TYPE_CLASS:
7779                                         case MONO_TYPE_SZARRAY:
7780                                         case MONO_TYPE_PTR:
7781                                         case MONO_TYPE_FNPTR:
7782                                         case MONO_TYPE_ARRAY:
7783                                                 NEW_PCONST (cfg, *sp, *((gpointer *)addr));
7784                                                 type_to_eval_stack_type (cfg, field->type, *sp);
7785                                                 sp++;
7786                                                 break;
7787 #endif
7788                                         case MONO_TYPE_I8:
7789                                         case MONO_TYPE_U8:
7790                                                 MONO_INST_NEW (cfg, *sp, OP_I8CONST);
7791                                                 sp [0]->type = STACK_I8;
7792                                                 sp [0]->inst_l = *((gint64 *)addr);
7793                                                 sp++;
7794                                                 break;
7795                                         case MONO_TYPE_R4:
7796                                         case MONO_TYPE_R8:
7797                                         case MONO_TYPE_VALUETYPE:
7798                                         default:
7799                                                 is_const = FALSE;
7800                                                 break;
7801                                         }
7802                                 }
7803
7804                                 if (!is_const) {
7805                                         MonoInst *load;
7806                                         CHECK_STACK_OVF (1);
7807                                         MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, field->type));
7808                                         type_to_eval_stack_type (cfg, field->type, load);
7809                                         load->inst_left = ins;
7810                                         load->flags |= ins_flag;
7811 #ifdef MONO_ARCH_SOFT_FLOAT
7812                                         if (load->opcode == CEE_LDIND_R4) {
7813                                                 int temp;
7814                                                 temp = handle_load_float (cfg, bblock, ins, ip);
7815                                                 NEW_TEMPLOAD (cfg, load, temp);
7816                                         }
7817 #endif
7818                                         *sp++ = load;
7819                                         ins_flag = 0;
7820                                 }
7821                         }
7822                         ip += 5;
7823                         break;
7824                 }
7825                 case CEE_STOBJ:
7826                         CHECK_STACK (2);
7827                         sp -= 2;
7828                         CHECK_OPSIZE (5);
7829                         token = read32 (ip + 1);
7830                         klass = mini_get_class (method, token, generic_context);
7831                         CHECK_TYPELOAD (klass);
7832                         n = mini_type_to_stind (cfg, &klass->byval_arg);
7833                         /* FIXME: handle CEE_STIND_R4 */
7834                         if (n == CEE_STOBJ) {
7835                                 handle_stobj (cfg, bblock, sp [0], sp [1], ip, klass, FALSE, FALSE, TRUE);
7836                         } else {
7837                                 /* FIXME: should check item at sp [1] is compatible with the type of the store. */
7838                                 MonoInst *store;
7839                                 MONO_INST_NEW (cfg, store, n);
7840                                 store->inst_left = sp [0];
7841                                 store->inst_right = sp [1];
7842                                 store->flags |= ins_flag;
7843                                 MONO_ADD_INS (bblock, store);
7844                         }
7845                         ins_flag = 0;
7846                         ip += 5;
7847                         inline_costs += 1;
7848                         break;
7849                 case CEE_BOX: {
7850                         MonoInst *val;
7851
7852                         CHECK_STACK (1);
7853                         --sp;
7854                         val = *sp;
7855                         CHECK_OPSIZE (5);
7856                         token = read32 (ip + 1);
7857                         klass = mini_get_class (method, token, generic_context);
7858                         CHECK_TYPELOAD (klass);
7859
7860                         if (cfg->generic_sharing_context)
7861                                 context_used =  mono_class_check_context_used (klass);
7862
7863                         if (generic_class_is_reference_type (cfg, klass)) {
7864                                 *sp++ = val;
7865                                 ip += 5;
7866                                 break;
7867                         }
7868                         if (klass == mono_defaults.void_class)
7869                                 UNVERIFIED;
7870                         if (target_type_is_incompatible (cfg, &klass->byval_arg, *sp))
7871                                 UNVERIFIED;
7872                         /* frequent check in generic code: box (struct), brtrue */
7873                         if (!mono_class_is_nullable (klass) &&
7874                             ip + 5 < end && ip_in_bb (cfg, bblock, ip + 5) && (ip [5] == CEE_BRTRUE || ip [5] == CEE_BRTRUE_S)) {
7875                                 /*g_print ("box-brtrue opt at 0x%04x in %s\n", real_offset, method->name);*/
7876                                 MONO_INST_NEW (cfg, ins, CEE_POP);
7877                                 MONO_ADD_INS (bblock, ins);
7878                                 ins->inst_i0 = *sp;
7879                                 ip += 5;
7880                                 cfg->ip = ip;
7881                                 MONO_INST_NEW (cfg, ins, OP_BR);
7882                                 MONO_ADD_INS (bblock, ins);
7883                                 if (*ip == CEE_BRTRUE_S) {
7884                                         CHECK_OPSIZE (2);
7885                                         ip++;
7886                                         target = ip + 1 + (signed char)(*ip);
7887                                         ip++;
7888                                 } else {
7889                                         CHECK_OPSIZE (5);
7890                                         ip++;
7891                                         target = ip + 4 + (gint)(read32 (ip));
7892                                         ip += 4;
7893                                 }
7894                                 GET_BBLOCK (cfg, tblock, target);
7895                                 link_bblock (cfg, bblock, tblock);
7896                                 CHECK_BBLOCK (target, ip, tblock);
7897                                 ins->inst_target_bb = tblock;
7898                                 GET_BBLOCK (cfg, tblock, ip);
7899                                 link_bblock (cfg, bblock, tblock);
7900                                 if (sp != stack_start) {
7901                                         handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
7902                                         sp = stack_start;
7903                                         CHECK_UNVERIFIABLE (cfg);
7904                                 }
7905                                 start_new_bblock = 1;
7906                                 break;
7907                         }
7908                         if (context_used) {
7909                                 MonoInst *rgctx;
7910
7911                                 if (mono_class_is_nullable (klass)) {
7912                                         GET_RGCTX (rgctx, context_used);
7913                                         *sp++ = handle_box_nullable_from_inst (cfg, method, context_used, bblock, val,
7914                                                         ip, klass, generic_context, rgctx);
7915                                 } else {
7916                                         MonoInst *data;
7917                                         int rgctx_info;
7918
7919                                         GET_RGCTX (rgctx, context_used);
7920                                         if (cfg->opt & MONO_OPT_SHARED)
7921                                                 rgctx_info = MONO_RGCTX_INFO_KLASS;
7922                                         else
7923                                                 rgctx_info = MONO_RGCTX_INFO_VTABLE;
7924                                         data = get_runtime_generic_context_ptr (cfg, method, context_used, bblock, klass,
7925                                                         generic_context, rgctx, rgctx_info, ip);
7926
7927                                         *sp++ = handle_box_from_inst (cfg, bblock, val, ip, klass, data);
7928                                 }
7929                         } else {
7930                                 *sp++ = handle_box (cfg, bblock, val, ip, klass);
7931                         }
7932                         ip += 5;
7933                         inline_costs += 1;
7934                         break;
7935                 }
7936                 case CEE_NEWARR:
7937                         CHECK_STACK (1);
7938                         --sp;
7939
7940                         CHECK_OPSIZE (5);
7941                         token = read32 (ip + 1);
7942
7943                         /* allocate the domainvar - becaus this is used in decompose_foreach */
7944                         if (cfg->opt & MONO_OPT_SHARED) {
7945                                 mono_get_domainvar (cfg);
7946                                 /* LAME-IR: Mark it as used since otherwise it will be optimized away */
7947                                 cfg->domainvar->flags |= MONO_INST_VOLATILE;
7948                         }
7949
7950                         /* Ditto */
7951                         mono_get_got_var (cfg);
7952
7953                         klass = mini_get_class (method, token, generic_context);
7954                         CHECK_TYPELOAD (klass);
7955
7956                         if (cfg->generic_sharing_context)
7957                                 context_used = mono_class_check_context_used (klass);
7958
7959                         if (context_used) {
7960                                 MonoInst *rgctx, *args [3];
7961                                 int temp;
7962
7963                                 /* domain */
7964                                 /* FIXME: what about domain-neutral code? */
7965                                 NEW_DOMAINCONST (cfg, args [0]);
7966
7967                                 /* klass */
7968                                 GET_RGCTX (rgctx, context_used);
7969                                 args [1] = get_runtime_generic_context_ptr (cfg, method, context_used, bblock, klass,
7970                                         generic_context, rgctx, MONO_RGCTX_INFO_KLASS, ip);
7971
7972                                 /* array len */
7973                                 args [2] = *sp;
7974
7975                                 temp = mono_emit_jit_icall (cfg, bblock, mono_array_new, args, ip);
7976                                 NEW_TEMPLOAD (cfg, ins, temp);
7977                         } else {
7978                                 MONO_INST_NEW (cfg, ins, *ip);
7979                                 ins->inst_newa_class = klass;
7980                                 ins->inst_newa_len = *sp;
7981                                 ins->type = STACK_OBJ;
7982                                 ins->klass = mono_array_class_get (klass, 1);
7983                         }
7984
7985                         ip += 5;
7986                         *sp++ = ins;
7987                         /* 
7988                          * we store the object so calls to create the array are not interleaved
7989                          * with the arguments of other calls.
7990                          */
7991                         if (1) {
7992                                 MonoInst *store, *temp, *load;
7993                                 const char *data_ptr;
7994                                 int data_size = 0;
7995                                 --sp;
7996                                 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
7997                                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
7998                                 store->cil_code = ins->cil_code;
7999                                 MONO_ADD_INS (bblock, store);
8000                                 /* 
8001                                  * we inline/optimize the initialization sequence if possible.
8002                                  * we should also allocate the array as not cleared, since we spend as much time clearing to 0 as initializing
8003                                  * for small sizes open code the memcpy
8004                                  * ensure the rva field is big enough
8005                                  */
8006                                 if ((cfg->opt & MONO_OPT_INTRINS) && ip + 6 < end && ip_in_bb (cfg, bblock, ip + 6) && (data_ptr = initialize_array_data (method, cfg->compile_aot, ip, ins, &data_size))) {
8007                                         MonoMethod *memcpy_method = get_memcpy_method ();
8008                                         MonoInst *data_offset, *add;
8009                                         MonoInst *iargs [3];
8010                                         NEW_ICONST (cfg, iargs [2], data_size);
8011                                         NEW_TEMPLOAD (cfg, load, temp->inst_c0);
8012                                         load->cil_code = ins->cil_code;
8013                                         NEW_ICONST (cfg, data_offset, G_STRUCT_OFFSET (MonoArray, vector));
8014                                         MONO_INST_NEW (cfg, add, OP_PADD);
8015                                         add->inst_left = load;
8016                                         add->inst_right = data_offset;
8017                                         iargs [0] = add;
8018                                         if (cfg->compile_aot) {
8019                                                 NEW_AOTCONST_TOKEN (cfg, iargs [1], MONO_PATCH_INFO_RVA, method->klass->image, GPOINTER_TO_UINT(data_ptr), STACK_PTR, NULL);
8020                                         } else {
8021                                                 NEW_PCONST (cfg, iargs [1], (char*)data_ptr);
8022                                         }
8023                                         mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
8024                                         ip += 11;
8025                                 }
8026                                 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
8027                                 load->cil_code = ins->cil_code;
8028                                 *sp++ = load;
8029                         }
8030                         inline_costs += 1;
8031                         break;
8032                 case CEE_LDLEN:
8033                         CHECK_STACK (1);
8034                         --sp;
8035                         if (sp [0]->type != STACK_OBJ)
8036                                 UNVERIFIED;
8037                         MONO_INST_NEW (cfg, ins, *ip);
8038                         ip++;
8039                         ins->inst_left = *sp;
8040                         ins->type = STACK_PTR;
8041                         *sp++ = ins;
8042                         break;
8043                 case CEE_LDELEMA:
8044                         CHECK_STACK (2);
8045                         sp -= 2;
8046                         CHECK_OPSIZE (5);
8047                         if (sp [0]->type != STACK_OBJ)
8048                                 UNVERIFIED;
8049
8050                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
8051                         CHECK_TYPELOAD (klass);
8052                         /* we need to make sure that this array is exactly the type it needs
8053                          * to be for correctness. the wrappers are lax with their usage
8054                          * so we need to ignore them here
8055                          */
8056                         if (!klass->valuetype && method->wrapper_type == MONO_WRAPPER_NONE && !readonly) {
8057                                 MonoInst* check;
8058
8059                                 /* Needed by the code generated in inssel.brg */
8060                                 mono_get_got_var (cfg);
8061
8062                                 MONO_INST_NEW (cfg, check, OP_CHECK_ARRAY_TYPE);
8063                                 check->klass = mono_array_class_get (klass, 1);
8064                                 check->inst_left = sp [0];
8065                                 check->type = STACK_OBJ;
8066                                 sp [0] = check;
8067                         }
8068                         
8069                         readonly = FALSE;
8070                         mono_class_init (klass);
8071                         NEW_LDELEMA (cfg, ins, sp, klass);
8072                         *sp++ = ins;
8073                         ip += 5;
8074                         break;
8075                 case CEE_LDELEM_ANY: {
8076                         MonoInst *load;
8077                         CHECK_STACK (2);
8078                         sp -= 2;
8079                         if (sp [0]->type != STACK_OBJ)
8080                                 UNVERIFIED;
8081                         CHECK_OPSIZE (5);
8082                         token = read32 (ip + 1);
8083                         klass = mini_get_class (method, token, generic_context);
8084                         CHECK_TYPELOAD (klass);
8085                         mono_class_init (klass);
8086                         NEW_LDELEMA (cfg, load, sp, klass);
8087                         MONO_INST_NEW (cfg, ins, mini_type_to_ldind (cfg, &klass->byval_arg));
8088                         ins->inst_left = load;
8089                         *sp++ = ins;
8090                         type_to_eval_stack_type (cfg, &klass->byval_arg, ins);
8091                         ip += 5;
8092                         break;
8093                 }
8094                 case CEE_LDELEM_I1:
8095                 case CEE_LDELEM_U1:
8096                 case CEE_LDELEM_I2:
8097                 case CEE_LDELEM_U2:
8098                 case CEE_LDELEM_I4:
8099                 case CEE_LDELEM_U4:
8100                 case CEE_LDELEM_I8:
8101                 case CEE_LDELEM_I:
8102                 case CEE_LDELEM_R4:
8103                 case CEE_LDELEM_R8:
8104                 case CEE_LDELEM_REF: {
8105                         MonoInst *load;
8106                         /*
8107                          * translate to:
8108                          * ldind.x (ldelema (array, index))
8109                          * ldelema does the bounds check
8110                          */
8111                         CHECK_STACK (2);
8112                         sp -= 2;
8113                         if (sp [0]->type != STACK_OBJ)
8114                                 UNVERIFIED;
8115                         klass = array_access_to_klass (*ip, sp [0]);
8116                         NEW_LDELEMA (cfg, load, sp, klass);
8117 #ifdef MONO_ARCH_SOFT_FLOAT
8118                         if (*ip == CEE_LDELEM_R4) {
8119                                 int temp;
8120                                 temp = handle_load_float (cfg, bblock, load, ip);
8121                                 NEW_TEMPLOAD (cfg, *sp, temp);
8122                                 sp++;
8123                                 ++ip;
8124                                 break;
8125                         }
8126 #endif
8127                         MONO_INST_NEW (cfg, ins, ldelem_to_ldind [*ip - CEE_LDELEM_I1]);
8128                         ins->inst_left = load;
8129                         *sp++ = ins;
8130                         ins->type = ldind_type [ins->opcode - CEE_LDIND_I1];
8131                         ins->klass = klass;
8132                         ++ip;
8133                         break;
8134                 }
8135                 case CEE_STELEM_I:
8136                 case CEE_STELEM_I1:
8137                 case CEE_STELEM_I2:
8138                 case CEE_STELEM_I4:
8139                 case CEE_STELEM_I8:
8140                 case CEE_STELEM_R4:
8141                 case CEE_STELEM_R8: {
8142                         MonoInst *load;
8143                         /*
8144                          * translate to:
8145                          * stind.x (ldelema (array, index), val)
8146                          * ldelema does the bounds check
8147                          */
8148                         CHECK_STACK (3);
8149                         sp -= 3;
8150                         if (sp [0]->type != STACK_OBJ)
8151                                 UNVERIFIED;
8152                         klass = array_access_to_klass (*ip, sp [0]);
8153                         NEW_LDELEMA (cfg, load, sp, klass);
8154 #ifdef MONO_ARCH_SOFT_FLOAT
8155                         if (*ip == CEE_STELEM_R4) {
8156                                 handle_store_float (cfg, bblock, load, sp [2], ip);
8157                                 ip++;
8158                                 break;
8159                         }
8160 #endif
8161                         MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
8162                         ins->inst_left = load;
8163                         ins->inst_right = sp [2];
8164                         ++ip;
8165                         handle_loaded_temps (cfg, bblock, stack_start, sp);
8166                         MONO_ADD_INS (bblock, ins);
8167                         inline_costs += 1;
8168                         break;
8169                 }
8170                 case CEE_STELEM_ANY: {
8171                         MonoInst *load;
8172                         /*
8173                          * translate to:
8174                          * stind.x (ldelema (array, index), val)
8175                          * ldelema does the bounds check
8176                          */
8177                         CHECK_STACK (3);
8178                         sp -= 3;
8179                         if (sp [0]->type != STACK_OBJ)
8180                                 UNVERIFIED;
8181                         CHECK_OPSIZE (5);
8182                         token = read32 (ip + 1);
8183                         klass = mini_get_class (method, token, generic_context);
8184                         CHECK_TYPELOAD (klass);
8185                         mono_class_init (klass);
8186                         if (generic_class_is_reference_type (cfg, klass)) {
8187                                 /* storing a NULL doesn't need any of the complex checks in stelemref */
8188                                 if (sp [2]->opcode == OP_PCONST && sp [2]->inst_p0 == NULL) {
8189                                         MonoInst *load;
8190                                         NEW_LDELEMA (cfg, load, sp, mono_defaults.object_class);
8191                                         MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
8192                                         ins->inst_left = load;
8193                                         ins->inst_right = sp [2];
8194                                         MONO_ADD_INS (bblock, ins);
8195                                 } else {
8196                                         MonoMethod* helper = mono_marshal_get_stelemref ();
8197                                         MonoInst *iargs [3];
8198                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
8199
8200                                         iargs [2] = sp [2];
8201                                         iargs [1] = sp [1];
8202                                         iargs [0] = sp [0];
8203
8204                                         mono_emit_method_call_spilled (cfg, bblock, helper, mono_method_signature (helper), iargs, ip, NULL);
8205                                 }
8206                         } else {
8207                                 NEW_LDELEMA (cfg, load, sp, klass);
8208
8209                                 n = mini_type_to_stind (cfg, &klass->byval_arg);
8210                                 /* FIXME: CEE_STIND_R4 */
8211                                 if (n == CEE_STOBJ)
8212                                         handle_stobj (cfg, bblock, load, sp [2], ip, klass, FALSE, FALSE, TRUE);
8213                                 else {
8214                                         MONO_INST_NEW (cfg, ins, n);
8215                                         ins->inst_left = load;
8216                                         ins->inst_right = sp [2];
8217                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
8218                                         MONO_ADD_INS (bblock, ins);
8219                                 }
8220                         }
8221                         ip += 5;
8222                         inline_costs += 1;
8223                         break;
8224                 }
8225                 case CEE_STELEM_REF: {
8226                         MonoInst *iargs [3];
8227                         MonoMethod* helper = mono_marshal_get_stelemref ();
8228
8229                         CHECK_STACK (3);
8230                         sp -= 3;
8231                         if (sp [0]->type != STACK_OBJ)
8232                                 UNVERIFIED;
8233                         if (sp [2]->type != STACK_OBJ)
8234                                 UNVERIFIED;
8235
8236                         handle_loaded_temps (cfg, bblock, stack_start, sp);
8237
8238                         /* storing a NULL doesn't need any of the complex checks in stelemref */
8239                         if (sp [2]->opcode == OP_PCONST && sp [2]->inst_p0 == NULL) {
8240                                 MonoInst *load;
8241                                 NEW_LDELEMA (cfg, load, sp, mono_defaults.object_class);
8242                                 MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
8243                                 ins->inst_left = load;
8244                                 ins->inst_right = sp [2];
8245                                 MONO_ADD_INS (bblock, ins);
8246                         } else {
8247                                 iargs [2] = sp [2];
8248                                 iargs [1] = sp [1];
8249                                 iargs [0] = sp [0];
8250                         
8251                                 mono_emit_method_call_spilled (cfg, bblock, helper, mono_method_signature (helper), iargs, ip, NULL);
8252                                 inline_costs += 1;
8253                         }
8254
8255                         ++ip;
8256                         break;
8257                 }
8258                 case CEE_CKFINITE: {
8259                         MonoInst *store, *temp;
8260                         CHECK_STACK (1);
8261
8262                         /* this instr. can throw exceptions as side effect,
8263                          * so we cant eliminate dead code which contains CKFINITE opdodes.
8264                          * Spilling to memory makes sure that we always perform
8265                          * this check */
8266
8267                         
8268                         MONO_INST_NEW (cfg, ins, OP_CKFINITE);
8269                         ins->inst_left = sp [-1];
8270                         temp = mono_compile_create_var (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL);
8271
8272                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
8273                         MONO_ADD_INS (bblock, store);
8274
8275                         NEW_TEMPLOAD (cfg, sp [-1], temp->inst_c0);
8276                        
8277                         ++ip;
8278                         break;
8279                 }
8280                 case CEE_REFANYVAL:
8281                         CHECK_STACK (1);
8282                         --sp;
8283                         CHECK_OPSIZE (5);
8284                         token = read32 (ip + 1);
8285                         klass = mono_class_get_full (image, token, generic_context);
8286                         CHECK_TYPELOAD (klass);
8287                         mono_class_init (klass);
8288
8289                         if (cfg->generic_sharing_context) {
8290                                 context_used = mono_class_check_context_used (klass);
8291                                 if (context_used && cfg->compile_aot)
8292                                         GENERIC_SHARING_FAILURE (*ip);
8293                         }
8294
8295                         if (context_used) {
8296                                 MonoInst *rgctx;
8297
8298                                 MONO_INST_NEW (cfg, ins, OP_REFANYVAL_REG);
8299                                 ins->type = STACK_MP;
8300                                 ins->inst_left = *sp;
8301                                 ins->klass = klass;
8302
8303                                 GET_RGCTX (rgctx, context_used);
8304                                 ins->inst_right = get_runtime_generic_context_ptr (cfg, method, context_used,
8305                                                 bblock, klass, generic_context, rgctx, MONO_RGCTX_INFO_KLASS, ip);
8306                         } else {
8307                                 MONO_INST_NEW (cfg, ins, *ip);
8308                                 ins->type = STACK_MP;
8309                                 ins->inst_left = *sp;
8310                                 ins->klass = klass;
8311                                 ins->inst_newa_class = klass;
8312                         }
8313                         ip += 5;
8314                         *sp++ = ins;
8315                         break;
8316                 case CEE_MKREFANY: {
8317                         MonoInst *loc;
8318
8319                         CHECK_STACK (1);
8320                         --sp;
8321                         CHECK_OPSIZE (5);
8322                         token = read32 (ip + 1);
8323                         klass = mono_class_get_full (image, token, generic_context);
8324                         CHECK_TYPELOAD (klass);
8325                         mono_class_init (klass);
8326
8327                         if (cfg->generic_sharing_context) {
8328                                 context_used = mono_class_check_context_used (klass);
8329                                 if (context_used && cfg->compile_aot)
8330                                         GENERIC_SHARING_FAILURE (CEE_MKREFANY);
8331                         }
8332
8333                         loc = mono_compile_create_var (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL);
8334                         if (context_used) {
8335                                 MonoInst *rgctx, *klass_type, *klass_klass, *loc_load;
8336
8337                                 GET_RGCTX (rgctx, context_used);
8338                                 klass_klass = get_runtime_generic_context_ptr (cfg, method, context_used, bblock, klass,
8339                                                 generic_context, rgctx, MONO_RGCTX_INFO_KLASS, ip);
8340                                 GET_RGCTX (rgctx, context_used);
8341                                 klass_type = get_runtime_generic_context_ptr (cfg, method, context_used, bblock, klass,
8342                                                 generic_context, rgctx, MONO_RGCTX_INFO_TYPE, ip);
8343
8344                                 NEW_TEMPLOADA (cfg, loc_load, loc->inst_c0);
8345
8346                                 MONO_INST_NEW (cfg, ins, OP_MKREFANY_REGS);
8347                                 NEW_GROUP (cfg, ins->inst_left, klass_type, klass_klass);
8348                                 NEW_GROUP (cfg, ins->inst_right, *sp, loc_load);
8349                         } else {
8350                                 MonoInst *klassconst;
8351
8352                                 NEW_PCONST (cfg, klassconst, klass);
8353
8354                                 MONO_INST_NEW (cfg, ins, *ip);
8355                                 NEW_TEMPLOADA (cfg, ins->inst_right, loc->inst_c0);
8356                                 NEW_GROUP (cfg, ins->inst_left, *sp, klassconst);
8357                         }
8358
8359                         MONO_ADD_INS (bblock, ins);
8360
8361                         NEW_TEMPLOAD (cfg, *sp, loc->inst_c0);
8362                         ++sp;
8363                         ip += 5;
8364                         break;
8365                 }
8366                 case CEE_LDTOKEN: {
8367                         gpointer handle;
8368                         MonoClass *handle_class;
8369
8370                         CHECK_STACK_OVF (1);
8371
8372                         CHECK_OPSIZE (5);
8373                         n = read32 (ip + 1);
8374
8375                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8376                                 handle = mono_method_get_wrapper_data (method, n);
8377                                 handle_class = mono_method_get_wrapper_data (method, n + 1);
8378                                 if (handle_class == mono_defaults.typehandle_class)
8379                                         handle = &((MonoClass*)handle)->byval_arg;
8380                         }
8381                         else {
8382                                 handle = mono_ldtoken (image, n, &handle_class, generic_context);
8383                         }
8384                         if (!handle)
8385                                 goto load_error;
8386                         mono_class_init (handle_class);
8387
8388                         if (cfg->generic_sharing_context) {
8389                                 if (handle_class == mono_defaults.typehandle_class) {
8390                                         /* If we get a MONO_TYPE_CLASS
8391                                            then we need to provide the
8392                                            open type, not an
8393                                            instantiation of it. */
8394                                         if (mono_type_get_type (handle) == MONO_TYPE_CLASS)
8395                                                 context_used = 0;
8396                                         else
8397                                                 context_used = mono_class_check_context_used (mono_class_from_mono_type (handle));
8398                                 } else if (handle_class == mono_defaults.fieldhandle_class)
8399                                         context_used = mono_class_check_context_used (((MonoClassField*)handle)->parent);
8400                                 else if (handle_class == mono_defaults.methodhandle_class)
8401                                         context_used = mono_method_check_context_used (handle);
8402                                 else
8403                                         g_assert_not_reached ();
8404                         }
8405
8406                         if (cfg->opt & MONO_OPT_SHARED) {
8407                                 int temp;
8408                                 MonoInst *res, *store, *addr, *vtvar, *iargs [3];
8409                                 int method_context_used;
8410
8411                                 if (cfg->generic_sharing_context)
8412                                         method_context_used = mono_method_check_context_used (method);
8413                                 else
8414                                         method_context_used = 0;
8415
8416                                 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL); 
8417
8418                                 NEW_IMAGECONST (cfg, iargs [0], image);
8419                                 NEW_ICONST (cfg, iargs [1], n);
8420                                 if (method_context_used) {
8421                                         MonoInst *rgctx;
8422
8423                                         GET_RGCTX (rgctx, method_context_used);
8424                                         iargs [2] = get_runtime_generic_context_method (cfg, method, method_context_used,
8425                                                         bblock, method,
8426                                                         generic_context, rgctx, MONO_RGCTX_INFO_METHOD, ip);
8427                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldtoken_wrapper_generic_shared,
8428                                                         iargs, ip);
8429                                 } else {
8430                                         NEW_PCONST (cfg, iargs [2], generic_context);
8431                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldtoken_wrapper, iargs, ip);
8432                                 }
8433                                 NEW_TEMPLOAD (cfg, res, temp);
8434                                 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
8435                                 NEW_INDSTORE (cfg, store, addr, res, &mono_defaults.int_class->byval_arg);
8436                                 MONO_ADD_INS (bblock, store);
8437                                 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
8438                         } else {
8439                                 if ((ip + 10 < end) && ip_in_bb (cfg, bblock, ip + 5) &&
8440                                         handle_class == mono_defaults.typehandle_class &&
8441                                         ((ip [5] == CEE_CALL) || (ip [5] == CEE_CALLVIRT)) && 
8442                                         (cmethod = mini_get_method (cfg, method, read32 (ip + 6), NULL, generic_context)) &&
8443                                         (cmethod->klass == mono_defaults.monotype_class->parent) &&
8444                                         (strcmp (cmethod->name, "GetTypeFromHandle") == 0)) {
8445                                         MonoClass *tclass = mono_class_from_mono_type (handle);
8446                                         mono_class_init (tclass);
8447                                         if (context_used) {
8448                                                 MonoInst *rgctx;
8449
8450                                                 g_assert (!cfg->compile_aot);
8451
8452                                                 GET_RGCTX (rgctx, context_used);
8453                                                 ins = get_runtime_generic_context_ptr (cfg, method, context_used, bblock, tclass,
8454                                                         generic_context, rgctx, MONO_RGCTX_INFO_REFLECTION_TYPE, ip);
8455                                         } else if (cfg->compile_aot) {
8456                                                 NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, image, n);
8457                                         } else {
8458                                                 NEW_PCONST (cfg, ins, mono_type_get_object (cfg->domain, handle));
8459                                         }
8460                                         ins->type = STACK_OBJ;
8461                                         ins->klass = cmethod->klass;
8462                                         ip += 5;
8463                                 } else {
8464                                         MonoInst *store, *addr, *vtvar;
8465
8466                                         if (context_used) {
8467                                                         MonoInst *rgctx;
8468
8469                                                 g_assert (!cfg->compile_aot);
8470
8471                                                 GET_RGCTX (rgctx, context_used);
8472                                                 if (handle_class == mono_defaults.typehandle_class) {
8473                                                         ins = get_runtime_generic_context_ptr (cfg, method,
8474                                                                         context_used, bblock,
8475                                                                         mono_class_from_mono_type (handle), generic_context,
8476                                                                         rgctx, MONO_RGCTX_INFO_TYPE, ip);
8477                                                 } else if (handle_class == mono_defaults.methodhandle_class) {
8478                                                         ins = get_runtime_generic_context_method (cfg, method,
8479                                                                         context_used, bblock, handle, generic_context,
8480                                                                         rgctx, MONO_RGCTX_INFO_METHOD, ip);
8481                                                 } else if (handle_class == mono_defaults.fieldhandle_class) {
8482                                                         ins = get_runtime_generic_context_field (cfg, method,
8483                                                                         context_used, bblock, handle, generic_context,
8484                                                                         rgctx, MONO_RGCTX_INFO_CLASS_FIELD, ip);
8485                                                 } else {
8486                                                         g_assert_not_reached ();
8487                                                 }
8488                                         }
8489                                         else if (cfg->compile_aot) {
8490                                                 NEW_LDTOKENCONST (cfg, ins, image, n);
8491                                         } else {
8492                                                 NEW_PCONST (cfg, ins, handle);
8493                                         }
8494                                         vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL);
8495                                         NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
8496                                         NEW_INDSTORE (cfg, store, addr, ins, &mono_defaults.int_class->byval_arg);
8497                                         MONO_ADD_INS (bblock, store);
8498                                         NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
8499                                 }
8500                         }
8501
8502                         *sp++ = ins;
8503                         ip += 5;
8504                         break;
8505                 }
8506                 case CEE_CONV_U2:
8507                 case CEE_CONV_U1:
8508                 case CEE_CONV_I:
8509                         CHECK_STACK (1);
8510                         ADD_UNOP (*ip);
8511                         ip++;
8512                         break;
8513                 case CEE_ADD_OVF:
8514                 case CEE_ADD_OVF_UN:
8515                 case CEE_MUL_OVF:
8516                 case CEE_MUL_OVF_UN:
8517                 case CEE_SUB_OVF:
8518                 case CEE_SUB_OVF_UN:
8519                         CHECK_STACK (2);
8520                         ADD_BINOP (*ip);
8521                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
8522                                 --sp;
8523                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
8524                         }
8525                         ip++;
8526                         break;
8527                 case CEE_ENDFINALLY:
8528                         MONO_INST_NEW (cfg, ins, OP_ENDFINALLY);
8529                         MONO_ADD_INS (bblock, ins);
8530                         ip++;
8531                         start_new_bblock = 1;
8532
8533                         /*
8534                          * Control will leave the method so empty the stack, otherwise
8535                          * the next basic block will start with a nonempty stack.
8536                          */
8537                         while (sp != stack_start) {
8538                                 MONO_INST_NEW (cfg, ins, CEE_POP);
8539                                 sp--;
8540                                 ins->inst_i0 = *sp;
8541                                 MONO_ADD_INS (bblock, ins);
8542                         }
8543                         break;
8544                 case CEE_LEAVE:
8545                 case CEE_LEAVE_S: {
8546                         GList *handlers;
8547
8548                         if (*ip == CEE_LEAVE) {
8549                                 CHECK_OPSIZE (5);
8550                                 target = ip + 5 + (gint32)read32(ip + 1);
8551                         } else {
8552                                 CHECK_OPSIZE (2);
8553                                 target = ip + 2 + (signed char)(ip [1]);
8554                         }
8555
8556                         /* empty the stack */
8557                         while (sp != stack_start) {
8558                                 MONO_INST_NEW (cfg, ins, CEE_POP);
8559                                 sp--;
8560                                 ins->inst_i0 = *sp;
8561                                 MONO_ADD_INS (bblock, ins);
8562                         }
8563
8564                         /* 
8565                          * If this leave statement is in a catch block, check for a
8566                          * pending exception, and rethrow it if necessary.
8567                          */
8568                         for (i = 0; i < header->num_clauses; ++i) {
8569                                 MonoExceptionClause *clause = &header->clauses [i];
8570
8571                                 /* 
8572                                  * Use <= in the final comparison to handle clauses with multiple
8573                                  * leave statements, like in bug #78024.
8574                                  * The ordering of the exception clauses guarantees that we find the
8575                                  * innermost clause.
8576                                  */
8577                                 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)) {
8578                                         int temp;
8579                                         MonoInst *load;
8580
8581                                         NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, clause->handler_offset)->inst_c0);
8582
8583                                         temp = mono_emit_jit_icall (cfg, bblock, mono_thread_get_undeniable_exception, NULL, ip);
8584                                         NEW_TEMPLOAD (cfg, *sp, temp);
8585                                 
8586                                         MONO_INST_NEW (cfg, ins, OP_THROW_OR_NULL);
8587                                         ins->inst_left = *sp;
8588                                         ins->inst_right = load;
8589                                         MONO_ADD_INS (bblock, ins);
8590                                 }
8591                         }
8592
8593                         if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
8594                                 GList *tmp;
8595                                 for (tmp = handlers; tmp; tmp = tmp->next) {
8596                                         tblock = tmp->data;
8597                                         link_bblock (cfg, bblock, tblock);
8598                                         MONO_INST_NEW (cfg, ins, OP_CALL_HANDLER);
8599                                         ins->inst_target_bb = tblock;
8600                                         MONO_ADD_INS (bblock, ins);
8601                                 }
8602                                 g_list_free (handlers);
8603                         } 
8604
8605                         MONO_INST_NEW (cfg, ins, OP_BR);
8606                         MONO_ADD_INS (bblock, ins);
8607                         GET_BBLOCK (cfg, tblock, target);
8608                         link_bblock (cfg, bblock, tblock);
8609                         CHECK_BBLOCK (target, ip, tblock);
8610                         ins->inst_target_bb = tblock;
8611                         start_new_bblock = 1;
8612
8613                         if (*ip == CEE_LEAVE)
8614                                 ip += 5;
8615                         else
8616                                 ip += 2;
8617
8618                         break;
8619                 }
8620                 case CEE_STIND_I:
8621                         CHECK_STACK (2);
8622                         MONO_INST_NEW (cfg, ins, *ip);
8623                         sp -= 2;
8624                         handle_loaded_temps (cfg, bblock, stack_start, sp);
8625                         MONO_ADD_INS (bblock, ins);
8626                         ip++;
8627                         ins->inst_i0 = sp [0];
8628                         ins->inst_i1 = sp [1];
8629                         inline_costs += 1;
8630                         break;
8631                 case CEE_CONV_U:
8632                         CHECK_STACK (1);
8633                         ADD_UNOP (*ip);
8634                         ip++;
8635                         break;
8636                 /* trampoline mono specific opcodes */
8637                 case MONO_CUSTOM_PREFIX: {
8638
8639                         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
8640
8641                         CHECK_OPSIZE (2);
8642                         switch (ip [1]) {
8643
8644                         case CEE_MONO_ICALL: {
8645                                 int temp;
8646                                 gpointer func;
8647                                 MonoJitICallInfo *info;
8648
8649                                 token = read32 (ip + 2);
8650                                 func = mono_method_get_wrapper_data (method, token);
8651                                 info = mono_find_jit_icall_by_addr (func);
8652                                 if (info == NULL){
8653                                         g_error ("An attempt has been made to perform an icall to address %p, "
8654                                                  "but the address has not been registered as an icall\n", info);
8655                                         g_assert_not_reached ();
8656                                 }
8657
8658                                 CHECK_STACK (info->sig->param_count);
8659                                 sp -= info->sig->param_count;
8660
8661                                 temp = mono_emit_jit_icall (cfg, bblock, info->func, sp, ip);
8662                                 if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
8663                                         NEW_TEMPLOAD (cfg, *sp, temp);
8664                                         sp++;
8665                                 }
8666
8667                                 ip += 6;
8668                                 inline_costs += 10 * num_calls++;
8669
8670                                 break;
8671                         }
8672                         case CEE_MONO_LDPTR: {
8673                                 gpointer ptr;
8674
8675                                 CHECK_STACK_OVF (1);
8676                                 CHECK_OPSIZE (6);
8677                                 token = read32 (ip + 2);
8678
8679                                 ptr = mono_method_get_wrapper_data (method, token);
8680                                 if (cfg->compile_aot && (cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE || cfg->method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE)) {
8681                                         MonoMethod *wrapped = mono_marshal_method_from_wrapper (cfg->method);
8682
8683                                         if (wrapped && ptr != NULL && mono_lookup_internal_call (wrapped) == ptr) {
8684                                                 NEW_AOTCONST (cfg, ins, MONO_PATCH_INFO_ICALL_ADDR, wrapped);
8685                                                 *sp++ = ins;
8686                                                 ip += 6;
8687                                                 break;
8688                                         }
8689
8690                                         if ((method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && (strstr (method->name, "__icall_wrapper_") == method->name)) {
8691                                                 MonoJitICallInfo *callinfo;
8692                                                 const char *icall_name;
8693
8694                                                 icall_name = method->name + strlen ("__icall_wrapper_");
8695                                                 g_assert (icall_name);
8696                                                 callinfo = mono_find_jit_icall_by_name (icall_name);
8697                                                 g_assert (callinfo);
8698
8699                                                 if (ptr == callinfo->func) {
8700                                                         /* Will be transformed into an AOTCONST later */
8701                                                         NEW_PCONST (cfg, ins, ptr);
8702                                                         *sp++ = ins;
8703                                                         ip += 6;
8704                                                         break;
8705                                                 }
8706                                         }
8707                                 }
8708                                 /* FIXME: Generalize this */
8709                                 if (cfg->compile_aot && ptr == mono_thread_interruption_request_flag ()) {
8710                                         NEW_AOTCONST (cfg, ins, MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG, NULL);
8711                                         *sp++ = ins;
8712                                         ip += 6;
8713                                         break;
8714                                 }
8715                                 NEW_PCONST (cfg, ins, ptr);
8716                                 *sp++ = ins;
8717                                 ip += 6;
8718                                 inline_costs += 10 * num_calls++;
8719                                 /* Can't embed random pointers into AOT code */
8720                                 cfg->disable_aot = 1;
8721                                 break;
8722                         }
8723                         case CEE_MONO_VTADDR:
8724                                 CHECK_STACK (1);
8725                                 --sp;
8726                                 MONO_INST_NEW (cfg, ins, OP_VTADDR);
8727                                 ins->type = STACK_MP;
8728                                 ins->inst_left = *sp;
8729                                 *sp++ = ins;
8730                                 ip += 2;
8731                                 break;
8732                         case CEE_MONO_NEWOBJ: {
8733                                 MonoInst *iargs [2];
8734                                 int temp;
8735                                 CHECK_STACK_OVF (1);
8736                                 CHECK_OPSIZE (6);
8737                                 token = read32 (ip + 2);
8738                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
8739                                 mono_class_init (klass);
8740                                 NEW_DOMAINCONST (cfg, iargs [0]);
8741                                 NEW_CLASSCONST (cfg, iargs [1], klass);
8742                                 temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
8743                                 NEW_TEMPLOAD (cfg, *sp, temp);
8744                                 sp++;
8745                                 ip += 6;
8746                                 inline_costs += 10 * num_calls++;
8747                                 break;
8748                         }
8749                         case CEE_MONO_OBJADDR:
8750                                 CHECK_STACK (1);
8751                                 --sp;
8752                                 MONO_INST_NEW (cfg, ins, OP_OBJADDR);
8753                                 ins->type = STACK_MP;
8754                                 ins->inst_left = *sp;
8755                                 *sp++ = ins;
8756                                 ip += 2;
8757                                 break;
8758                         case CEE_MONO_LDNATIVEOBJ:
8759                                 CHECK_STACK (1);
8760                                 CHECK_OPSIZE (6);
8761                                 token = read32 (ip + 2);
8762                                 klass = mono_method_get_wrapper_data (method, token);
8763                                 g_assert (klass->valuetype);
8764                                 mono_class_init (klass);
8765                                 NEW_INDLOAD (cfg, ins, sp [-1], &klass->byval_arg);
8766                                 sp [-1] = ins;
8767                                 ip += 6;
8768                                 break;
8769                         case CEE_MONO_RETOBJ:
8770                                 g_assert (cfg->ret);
8771                                 g_assert (mono_method_signature (method)->pinvoke); 
8772                                 CHECK_STACK (1);
8773                                 --sp;
8774                                 
8775                                 CHECK_OPSIZE (6);
8776                                 token = read32 (ip + 2);    
8777                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
8778
8779                                 NEW_RETLOADA (cfg, ins);
8780                                 handle_stobj (cfg, bblock, ins, *sp, ip, klass, FALSE, TRUE, FALSE);
8781                                 
8782                                 if (sp != stack_start)
8783                                         UNVERIFIED;
8784                                 
8785                                 MONO_INST_NEW (cfg, ins, OP_BR);
8786                                 ins->inst_target_bb = end_bblock;
8787                                 MONO_ADD_INS (bblock, ins);
8788                                 link_bblock (cfg, bblock, end_bblock);
8789                                 start_new_bblock = 1;
8790                                 ip += 6;
8791                                 break;
8792                         case CEE_MONO_CISINST:
8793                         case CEE_MONO_CCASTCLASS: {
8794                                 int token;
8795                                 CHECK_STACK (1);
8796                                 --sp;
8797                                 CHECK_OPSIZE (6);
8798                                 token = read32 (ip + 2);
8799                                 /* Needed by the code generated in inssel.brg */
8800                                 mono_get_got_var (cfg);
8801                 
8802                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
8803                                 MONO_INST_NEW (cfg, ins, (ip [1] == CEE_MONO_CISINST) ? OP_CISINST : OP_CCASTCLASS);
8804                                 ins->type = STACK_I4;
8805                                 ins->inst_left = *sp;
8806                                 ins->inst_newa_class = klass;
8807                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 6);
8808                                 ip += 6;
8809                                 break;
8810                         }
8811                         case CEE_MONO_SAVE_LMF:
8812                         case CEE_MONO_RESTORE_LMF:
8813 #ifdef MONO_ARCH_HAVE_LMF_OPS
8814                                 MONO_INST_NEW (cfg, ins, (ip [1] == CEE_MONO_SAVE_LMF) ? OP_SAVE_LMF : OP_RESTORE_LMF);
8815                                 MONO_ADD_INS (bblock, ins);
8816                                 cfg->need_lmf_area = TRUE;
8817 #endif
8818                                 ip += 2;
8819                                 break;
8820                         case CEE_MONO_CLASSCONST:
8821                                 CHECK_STACK_OVF (1);
8822                                 CHECK_OPSIZE (6);
8823                                 token = read32 (ip + 2);
8824                                 NEW_CLASSCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
8825                                 *sp++ = ins;
8826                                 ip += 6;
8827                                 inline_costs += 10 * num_calls++;
8828                                 break;
8829                         case CEE_MONO_NOT_TAKEN:
8830                                 bblock->out_of_line = TRUE;
8831                                 ip += 2;
8832                                 break;
8833                         case CEE_MONO_TLS:
8834                                 CHECK_STACK_OVF (1);
8835                                 CHECK_OPSIZE (6);
8836                                 MONO_INST_NEW (cfg, ins, OP_TLS_GET);
8837                                 ins->inst_offset = (gint32)read32 (ip + 2);
8838                                 ins->type = STACK_PTR;
8839                                 *sp++ = ins;
8840                                 ip += 6;
8841                                 break;
8842                         default:
8843                                 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
8844                                 break;
8845                         }
8846                         break;
8847                 }
8848                 case CEE_PREFIX1: {
8849                         CHECK_OPSIZE (2);
8850                         switch (ip [1]) {
8851                         case CEE_ARGLIST: {
8852                                 /* somewhat similar to LDTOKEN */
8853                                 MonoInst *addr, *vtvar;
8854                                 CHECK_STACK_OVF (1);
8855                                 vtvar = mono_compile_create_var (cfg, &mono_defaults.argumenthandle_class->byval_arg, OP_LOCAL); 
8856
8857                                 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
8858                                 MONO_INST_NEW (cfg, ins, OP_ARGLIST);
8859                                 ins->inst_left = addr;
8860                                 MONO_ADD_INS (bblock, ins);
8861                                 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
8862                                 *sp++ = ins;
8863                                 ip += 2;
8864                                 break;
8865                         }
8866                         case CEE_CEQ:
8867                         case CEE_CGT:
8868                         case CEE_CGT_UN:
8869                         case CEE_CLT:
8870                         case CEE_CLT_UN: {
8871                                 MonoInst *cmp;
8872                                 CHECK_STACK (2);
8873                                 /*
8874                                  * The following transforms:
8875                                  *    CEE_CEQ    into OP_CEQ
8876                                  *    CEE_CGT    into OP_CGT
8877                                  *    CEE_CGT_UN into OP_CGT_UN
8878                                  *    CEE_CLT    into OP_CLT
8879                                  *    CEE_CLT_UN into OP_CLT_UN
8880                                  */
8881                                 MONO_INST_NEW (cfg, cmp, (OP_CEQ - CEE_CEQ) + ip [1]);
8882                                 
8883                                 MONO_INST_NEW (cfg, ins, cmp->opcode);
8884                                 sp -= 2;
8885                                 cmp->inst_i0 = sp [0];
8886                                 cmp->inst_i1 = sp [1];
8887                                 type_from_op (cmp);
8888                                 CHECK_TYPE (cmp);
8889                                 ins->type = STACK_I4;
8890                                 ins->inst_i0 = cmp;
8891 #if MONO_ARCH_SOFT_FLOAT
8892                                 if (sp [0]->type == STACK_R8) {
8893                                         cmp->type = STACK_I4;
8894                                         *sp++ = emit_tree (cfg, bblock, cmp, ip + 2);
8895                                         ip += 2;
8896                                         break;
8897                                 }
8898 #endif
8899                                 if ((sp [0]->type == STACK_I8) || ((sizeof (gpointer) == 8) && ((sp [0]->type == STACK_PTR) || (sp [0]->type == STACK_OBJ) || (sp [0]->type == STACK_MP))))
8900                                         cmp->opcode = OP_LCOMPARE;
8901                                 else
8902                                         cmp->opcode = OP_COMPARE;
8903                                 *sp++ = ins;
8904                                 /* spill it to reduce the expression complexity
8905                                  * and workaround bug 54209 
8906                                  */
8907                                 if (cmp->inst_left->type == STACK_I8) {
8908                                         --sp;
8909                                         *sp++ = emit_tree (cfg, bblock, ins, ip + 2);
8910                                 }
8911                                 ip += 2;
8912                                 break;
8913                         }
8914                         case CEE_LDFTN: {
8915                                 MonoInst *argconst;
8916                                 MonoMethod *cil_method, *ctor_method;
8917                                 int temp;
8918                                 gboolean is_shared = FALSE;
8919
8920                                 CHECK_STACK_OVF (1);
8921                                 CHECK_OPSIZE (6);
8922                                 n = read32 (ip + 2);
8923                                 cmethod = mini_get_method (cfg, method, n, NULL, generic_context);
8924                                 if (!cmethod)
8925                                         goto load_error;
8926                                 mono_class_init (cmethod->klass);
8927
8928                                 if (cfg->generic_sharing_context)
8929                                         context_used = mono_method_check_context_used (cmethod);
8930
8931                                 if (mono_class_generic_sharing_enabled (cmethod->klass)) {
8932                                         if ((cmethod->flags & METHOD_ATTRIBUTE_STATIC) &&
8933                                                         (cmethod->klass->generic_class ||
8934                                                         cmethod->klass->generic_container)) {
8935                                                 is_shared = TRUE;
8936                                         }
8937                                         if (cmethod->is_inflated && mono_method_get_context (cmethod)->method_inst)
8938                                                 is_shared = TRUE;
8939                                 }
8940
8941                                 cil_method = cmethod;
8942                                 if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_method (method, cmethod))
8943                                         METHOD_ACCESS_FAILURE;
8944                                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
8945                                         if (check_linkdemand (cfg, method, cmethod, bblock, ip))
8946                                                 INLINE_FAILURE;
8947                                         CHECK_CFG_EXCEPTION;
8948                                 } else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
8949                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod, bblock, ip);
8950                                 }
8951
8952                                 /* 
8953                                  * Optimize the common case of ldftn+delegate creation
8954                                  */
8955 #if defined(MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE) && !defined(HAVE_WRITE_BARRIERS)
8956                                 /* FIXME: SGEN support */
8957                                 /* FIXME: handle shared static generic methods */
8958                                 /* FIXME: handle this in shared code */
8959                                 if (!is_shared && !context_used && (sp > stack_start) && (ip + 6 + 5 < end) && ip_in_bb (cfg, bblock, ip + 6) && (ip [6] == CEE_NEWOBJ) && (ctor_method = mini_get_method (cfg, method, read32 (ip + 7), NULL, generic_context)) && (ctor_method->klass->parent == mono_defaults.multicastdelegate_class)) {
8960                                         MonoInst *target_ins;
8961
8962                                         ip += 6;
8963                                         if (cfg->verbose_level > 3)
8964                                                 g_print ("converting (in B%d: stack: %d) %s", bblock->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
8965                                         target_ins = sp [-1];
8966                                         sp --;
8967                                         *sp = handle_delegate_ctor (cfg, bblock, ctor_method->klass, target_ins, cmethod, ip);
8968                                         ip += 5;                                        
8969                                         sp ++;
8970                                         break;
8971                                 }
8972 #endif
8973
8974                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
8975
8976                                 if (context_used) {
8977                                         MonoInst *rgctx;
8978
8979                                         if (is_shared)
8980                                                 cmethod = mono_marshal_get_static_rgctx_invoke (cmethod);
8981
8982                                         GET_RGCTX (rgctx, context_used);
8983                                         argconst = get_runtime_generic_context_method (cfg, method, context_used,
8984                                                         bblock, cmethod,
8985                                                         generic_context, rgctx, MONO_RGCTX_INFO_METHOD, ip);
8986                                 } else if (is_shared) {
8987                                         NEW_METHODCONST (cfg, argconst, mono_marshal_get_static_rgctx_invoke (cmethod));
8988                                 } else {
8989                                         NEW_METHODCONST (cfg, argconst, cmethod);
8990                                 }
8991                                 if (method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED)
8992                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn, &argconst, ip);
8993                                 else
8994                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn_nosync, &argconst, ip);
8995                                 NEW_TEMPLOAD (cfg, *sp, temp);
8996                                 sp ++;
8997                                 
8998                                 ip += 6;
8999                                 inline_costs += 10 * num_calls++;
9000                                 break;
9001                         }
9002                         case CEE_LDVIRTFTN: {
9003                                 MonoInst *args [2];
9004                                 int temp;
9005
9006                                 CHECK_STACK (1);
9007                                 CHECK_OPSIZE (6);
9008                                 n = read32 (ip + 2);
9009                                 cmethod = mini_get_method (cfg, method, n, NULL, generic_context);
9010                                 if (!cmethod)
9011                                         goto load_error;
9012                                 mono_class_init (cmethod->klass);
9013
9014                                 if (cfg->generic_sharing_context)
9015                                         context_used = mono_method_check_context_used (cmethod);
9016
9017                                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
9018                                         if (check_linkdemand (cfg, method, cmethod, bblock, ip))
9019                                                 INLINE_FAILURE;
9020                                         CHECK_CFG_EXCEPTION;
9021                                 } else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
9022                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod, bblock, ip);
9023                                 }
9024
9025                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
9026
9027                                 --sp;
9028                                 args [0] = *sp;
9029                                 if (context_used) {
9030                                         MonoInst *rgctx;
9031
9032                                         GET_RGCTX (rgctx, context_used);
9033                                         args [1] = get_runtime_generic_context_method (cfg, method, context_used,
9034                                                         bblock, cmethod,
9035                                                         generic_context, rgctx, MONO_RGCTX_INFO_METHOD, ip);
9036                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldvirtfn_gshared, args, ip);
9037                                 } else {
9038                                         NEW_METHODCONST (cfg, args [1], cmethod);
9039                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldvirtfn, args, ip);
9040                                 }
9041                                 NEW_TEMPLOAD (cfg, *sp, temp);
9042                                 sp ++;
9043
9044                                 ip += 6;
9045                                 inline_costs += 10 * num_calls++;
9046                                 break;
9047                         }
9048                         case CEE_LDARG:
9049                                 CHECK_STACK_OVF (1);
9050                                 CHECK_OPSIZE (4);
9051                                 n = read16 (ip + 2);
9052                                 CHECK_ARG (n);
9053                                 NEW_ARGLOAD (cfg, ins, n);
9054                                 LDARG_SOFT_FLOAT (cfg, ins, n, ip);
9055                                 *sp++ = ins;
9056                                 ip += 4;
9057                                 break;
9058                         case CEE_LDARGA:
9059                                 CHECK_STACK_OVF (1);
9060                                 CHECK_OPSIZE (4);
9061                                 n = read16 (ip + 2);
9062                                 CHECK_ARG (n);
9063                                 NEW_ARGLOADA (cfg, ins, n);
9064                                 *sp++ = ins;
9065                                 ip += 4;
9066                                 break;
9067                         case CEE_STARG:
9068                                 CHECK_STACK (1);
9069                                 --sp;
9070                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
9071                                 CHECK_OPSIZE (4);
9072                                 n = read16 (ip + 2);
9073                                 CHECK_ARG (n);
9074                                 NEW_ARGSTORE (cfg, ins, n, *sp);
9075                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [n], *sp))
9076                                         UNVERIFIED;
9077                                 STARG_SOFT_FLOAT (cfg, ins, n, ip);
9078                                 if (ins->opcode == CEE_STOBJ) {
9079                                         NEW_ARGLOADA (cfg, ins, n);
9080                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
9081                                 } else
9082                                         MONO_ADD_INS (bblock, ins);
9083                                 ip += 4;
9084                                 break;
9085                         case CEE_LDLOC:
9086                                 CHECK_STACK_OVF (1);
9087                                 CHECK_OPSIZE (4);
9088                                 n = read16 (ip + 2);
9089                                 CHECK_LOCAL (n);
9090                                 NEW_LOCLOAD (cfg, ins, n);
9091                                 LDLOC_SOFT_FLOAT (cfg, ins, n, ip);
9092                                 *sp++ = ins;
9093                                 ip += 4;
9094                                 break;
9095                         case CEE_LDLOCA:
9096                                 CHECK_STACK_OVF (1);
9097                                 CHECK_OPSIZE (4);
9098                                 n = read16 (ip + 2);
9099                                 CHECK_LOCAL (n);
9100                                 NEW_LOCLOADA (cfg, ins, n);
9101                                 *sp++ = ins;
9102                                 ip += 4;
9103                                 break;
9104                         case CEE_STLOC:
9105                                 CHECK_STACK (1);
9106                                 --sp;
9107                                 CHECK_OPSIZE (4);
9108                                 n = read16 (ip + 2);
9109                                 CHECK_LOCAL (n);
9110                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
9111                                 NEW_LOCSTORE (cfg, ins, n, *sp);
9112                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
9113                                         UNVERIFIED;
9114                                 STLOC_SOFT_FLOAT (cfg, ins, n, ip);
9115                                 if (ins->opcode == CEE_STOBJ) {
9116                                         NEW_LOCLOADA (cfg, ins, n);
9117                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
9118                                 } else
9119                                         MONO_ADD_INS (bblock, ins);
9120                                 ip += 4;
9121                                 inline_costs += 1;
9122                                 break;
9123                         case CEE_LOCALLOC:
9124                                 CHECK_STACK (1);
9125                                 --sp;
9126                                 if (sp != stack_start) 
9127                                         UNVERIFIED;
9128                                 if (cfg->method != method) 
9129                                         /* 
9130                                          * Inlining this into a loop in a parent could lead to 
9131                                          * stack overflows which is different behavior than the
9132                                          * non-inlined case, thus disable inlining in this case.
9133                                          */
9134                                         goto inline_failure;
9135                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
9136                                 ins->inst_left = *sp;
9137                                 ins->type = STACK_PTR;
9138
9139                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
9140                                 if (header->init_locals)
9141                                         ins->flags |= MONO_INST_INIT;
9142
9143                                 *sp++ = ins;
9144                                 ip += 2;
9145                                 /* FIXME: set init flag if locals init is set in this method */
9146                                 break;
9147                         case CEE_ENDFILTER: {
9148                                 MonoExceptionClause *clause, *nearest;
9149                                 int cc, nearest_num;
9150
9151                                 CHECK_STACK (1);
9152                                 --sp;
9153                                 if ((sp != stack_start) || (sp [0]->type != STACK_I4)) 
9154                                         UNVERIFIED;
9155                                 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
9156                                 ins->inst_left = *sp;
9157                                 MONO_ADD_INS (bblock, ins);
9158                                 start_new_bblock = 1;
9159                                 ip += 2;
9160
9161                                 nearest = NULL;
9162                                 nearest_num = 0;
9163                                 for (cc = 0; cc < header->num_clauses; ++cc) {
9164                                         clause = &header->clauses [cc];
9165                                         if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
9166                                                 ((ip - header->code) > clause->data.filter_offset && (ip - header->code) <= clause->handler_offset) &&
9167                                             (!nearest || (clause->data.filter_offset < nearest->data.filter_offset))) {
9168                                                 nearest = clause;
9169                                                 nearest_num = cc;
9170                                         }
9171                                 }
9172                                 g_assert (nearest);
9173                                 if ((ip - header->code) != nearest->handler_offset)
9174                                         UNVERIFIED;
9175
9176                                 break;
9177                         }
9178                         case CEE_UNALIGNED_:
9179                                 ins_flag |= MONO_INST_UNALIGNED;
9180                                 /* FIXME: record alignment? we can assume 1 for now */
9181                                 CHECK_OPSIZE (3);
9182                                 ip += 3;
9183                                 break;
9184                         case CEE_VOLATILE_:
9185                                 ins_flag |= MONO_INST_VOLATILE;
9186                                 ip += 2;
9187                                 break;
9188                         case CEE_TAIL_:
9189                                 ins_flag   |= MONO_INST_TAILCALL;
9190                                 cfg->flags |= MONO_CFG_HAS_TAIL;
9191                                 /* Can't inline tail calls at this time */
9192                                 inline_costs += 100000;
9193                                 ip += 2;
9194                                 break;
9195                         case CEE_INITOBJ:
9196                                 CHECK_STACK (1);
9197                                 --sp;
9198                                 CHECK_OPSIZE (6);
9199                                 token = read32 (ip + 2);
9200                                 klass = mini_get_class (method, token, generic_context);
9201                                 CHECK_TYPELOAD (klass);
9202
9203                                 if (generic_class_is_reference_type (cfg, klass)) {
9204                                         MonoInst *store, *load;
9205                                         NEW_PCONST (cfg, load, NULL);
9206                                         load->type = STACK_OBJ;
9207                                         load->klass = klass;
9208                                         MONO_INST_NEW (cfg, store, CEE_STIND_REF);
9209                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
9210                                         MONO_ADD_INS (bblock, store);
9211                                         store->inst_i0 = sp [0];
9212                                         store->inst_i1 = load;
9213                                 } else {
9214                                         handle_initobj (cfg, bblock, *sp, NULL, klass, stack_start, sp);
9215                                 }
9216                                 ip += 6;
9217                                 inline_costs += 1;
9218                                 break;
9219                         case CEE_CONSTRAINED_:
9220                                 /* FIXME: implement */
9221                                 CHECK_OPSIZE (6);
9222                                 token = read32 (ip + 2);
9223                                 constrained_call = mono_class_get_full (image, token, generic_context);
9224                                 CHECK_TYPELOAD (constrained_call);
9225                                 ip += 6;
9226                                 break;
9227                         case CEE_CPBLK:
9228                         case CEE_INITBLK: {
9229                                 MonoInst *iargs [3];
9230                                 CHECK_STACK (3);
9231                                 sp -= 3;
9232                                 if ((cfg->opt & MONO_OPT_INTRINS) && (ip [1] == CEE_CPBLK) && (sp [2]->opcode == OP_ICONST) && ((n = sp [2]->inst_c0) <= sizeof (gpointer) * 5)) {
9233                                         MonoInst *copy;
9234                                         NEW_MEMCPY (cfg, copy, sp [0], sp [1], n, 0);
9235                                         MONO_ADD_INS (bblock, copy);
9236                                         ip += 2;
9237                                         break;
9238                                 }
9239                                 iargs [0] = sp [0];
9240                                 iargs [1] = sp [1];
9241                                 iargs [2] = sp [2];
9242                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
9243                                 if (ip [1] == CEE_CPBLK) {
9244                                         MonoMethod *memcpy_method = get_memcpy_method ();
9245                                         mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
9246                                 } else {
9247                                         MonoMethod *memset_method = get_memset_method ();
9248                                         mono_emit_method_call_spilled (cfg, bblock, memset_method, memset_method->signature, iargs, ip, NULL);
9249                                 }
9250                                 ip += 2;
9251                                 inline_costs += 1;
9252                                 break;
9253                         }
9254                         case CEE_NO_:
9255                                 CHECK_OPSIZE (3);
9256                                 if (ip [2] & 0x1)
9257                                         ins_flag |= MONO_INST_NOTYPECHECK;
9258                                 if (ip [2] & 0x2)
9259                                         ins_flag |= MONO_INST_NORANGECHECK;
9260                                 /* we ignore the no-nullcheck for now since we
9261                                  * really do it explicitly only when doing callvirt->call
9262                                  */
9263                                 ip += 3;
9264                                 break;
9265                         case CEE_RETHROW: {
9266                                 MonoInst *load;
9267                                 int handler_offset = -1;
9268
9269                                 for (i = 0; i < header->num_clauses; ++i) {
9270                                         MonoExceptionClause *clause = &header->clauses [i];
9271                                         if (MONO_OFFSET_IN_HANDLER (clause, ip - header->code) && !(clause->flags & MONO_EXCEPTION_CLAUSE_FINALLY))
9272                                                 handler_offset = clause->handler_offset;
9273                                 }
9274
9275                                 bblock->flags |= BB_EXCEPTION_UNSAFE;
9276
9277                                 g_assert (handler_offset != -1);
9278
9279                                 NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, handler_offset)->inst_c0);
9280                                 MONO_INST_NEW (cfg, ins, OP_RETHROW);
9281                                 ins->inst_left = load;
9282                                 MONO_ADD_INS (bblock, ins);
9283                                 sp = stack_start;
9284                                 link_bblock (cfg, bblock, end_bblock);
9285                                 start_new_bblock = 1;
9286                                 ip += 2;
9287                                 break;
9288                         }
9289                         case CEE_SIZEOF:
9290                                 CHECK_STACK_OVF (1);
9291                                 CHECK_OPSIZE (6);
9292                                 token = read32 (ip + 2);
9293                                 /* FIXXME: handle generics. */
9294                                 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC) {
9295                                         MonoType *type = mono_type_create_from_typespec (image, token);
9296                                         token = mono_type_size (type, &ialign);
9297                                 } else {
9298                                         MonoClass *klass = mono_class_get_full (image, token, generic_context);
9299                                         CHECK_TYPELOAD (klass);
9300                                         mono_class_init (klass);
9301                                         token = mono_class_value_size (klass, &align);
9302                                 }
9303                                 NEW_ICONST (cfg, ins, token);
9304                                 *sp++= ins;
9305                                 ip += 6;
9306                                 break;
9307                         case CEE_REFANYTYPE:
9308                                 CHECK_STACK (1);
9309                                 MONO_INST_NEW (cfg, ins, OP_REFANYTYPE);
9310                                 --sp;
9311                                 ins->type = STACK_MP;
9312                                 ins->inst_left = *sp;
9313                                 ins->type = STACK_VTYPE;
9314                                 ins->klass = mono_defaults.typehandle_class;
9315                                 ip += 2;
9316                                 *sp++ = ins;
9317                                 break;
9318                         case CEE_READONLY_:
9319                                 readonly = TRUE;
9320                                 ip += 2;
9321                                 break;
9322                         default:
9323                                 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
9324                         }
9325                         break;
9326                 }
9327                 default:
9328                         g_error ("opcode 0x%02x not handled", *ip);
9329                 }
9330         }
9331         if (start_new_bblock != 1)
9332                 UNVERIFIED;
9333
9334         bblock->cil_length = ip - bblock->cil_code;
9335         bblock->next_bb = end_bblock;
9336
9337         if (cfg->method == method && cfg->domainvar) {
9338                 MonoInst *store;
9339                 MonoInst *get_domain;
9340                 
9341                 if (! (get_domain = mono_arch_get_domain_intrinsic (cfg))) {
9342                         MonoCallInst *call;
9343                         
9344                         MONO_INST_NEW_CALL (cfg, call, OP_CALL);
9345                         call->signature = helper_sig_domain_get;
9346                         call->inst.type = STACK_PTR;
9347                         call->fptr = mono_domain_get;
9348                         get_domain = (MonoInst*)call;
9349                 }
9350                 
9351                 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, get_domain);
9352                 MONO_ADD_INS (init_localsbb, store);
9353         }
9354
9355         if (cfg->method == method && cfg->got_var)
9356                 mono_emit_load_got_addr (cfg);
9357
9358         if (header->init_locals) {
9359                 MonoInst *store;
9360                 cfg->ip = header->code;
9361                 for (i = 0; i < header->num_locals; ++i) {
9362                         MonoType *ptype = header->locals [i];
9363                         int t = ptype->type;
9364                         if (t == MONO_TYPE_VALUETYPE && ptype->data.klass->enumtype)
9365                                 t = ptype->data.klass->enum_basetype->type;
9366                         if (ptype->byref) {
9367                                 NEW_PCONST (cfg, ins, NULL);
9368                                 NEW_LOCSTORE (cfg, store, i, ins);
9369                                 MONO_ADD_INS (init_localsbb, store);
9370                         } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
9371                                 NEW_ICONST (cfg, ins, 0);
9372                                 NEW_LOCSTORE (cfg, store, i, ins);
9373                                 MONO_ADD_INS (init_localsbb, store);
9374                         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
9375                                 MONO_INST_NEW (cfg, ins, OP_I8CONST);
9376                                 ins->type = STACK_I8;
9377                                 ins->inst_l = 0;
9378                                 NEW_LOCSTORE (cfg, store, i, ins);
9379                                 MONO_ADD_INS (init_localsbb, store);
9380                         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
9381 #ifdef MONO_ARCH_SOFT_FLOAT
9382                                 /* FIXME: handle init of R4 */
9383 #else
9384                                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
9385                                 ins->type = STACK_R8;
9386                                 ins->inst_p0 = (void*)&r8_0;
9387                                 NEW_LOCSTORE (cfg, store, i, ins);
9388                                 MONO_ADD_INS (init_localsbb, store);
9389 #endif
9390                         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
9391                                    ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (ptype))) {
9392                                 NEW_LOCLOADA (cfg, ins, i);
9393                                 handle_initobj (cfg, init_localsbb, ins, NULL, mono_class_from_mono_type (ptype), NULL, NULL);
9394                         } else {
9395                                 NEW_PCONST (cfg, ins, NULL);
9396                                 NEW_LOCSTORE (cfg, store, i, ins);
9397                                 MONO_ADD_INS (init_localsbb, store);
9398                         }
9399                 }
9400         }
9401
9402         cfg->ip = NULL;
9403
9404         /* resolve backward branches in the middle of an existing basic block */
9405         for (tmp = bb_recheck; tmp; tmp = tmp->next) {
9406                 bblock = tmp->data;
9407                 /*g_print ("need recheck in %s at IL_%04x\n", method->name, bblock->cil_code - header->code);*/
9408                 tblock = find_previous (cfg->cil_offset_to_bb, header->code_size, start_bblock, bblock->cil_code);
9409                 if (tblock != start_bblock) {
9410                         int l;
9411                         split_bblock (cfg, tblock, bblock);
9412                         l = bblock->cil_code - header->code;
9413                         bblock->cil_length = tblock->cil_length - l;
9414                         tblock->cil_length = l;
9415                 } else {
9416                         g_print ("recheck failed.\n");
9417                 }
9418         }
9419
9420         if (cfg->method == method) {
9421                 MonoBasicBlock *bb;
9422                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
9423                         bb->region = mono_find_block_region (cfg, bb->real_offset);
9424                         if (cfg->spvars)
9425                                 mono_create_spvar_for_region (cfg, bb->region);
9426                         if (cfg->verbose_level > 2)
9427                                 g_print ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
9428                 }
9429         }
9430
9431         g_slist_free (class_inits);
9432         dont_inline = g_list_remove (dont_inline, method);
9433
9434         if (inline_costs < 0) {
9435                 char *mname;
9436
9437                 /* Method is too large */
9438                 mname = mono_method_full_name (method, TRUE);
9439                 cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
9440                 cfg->exception_message = g_strdup_printf ("Method %s is too complex.", mname);
9441                 g_free (mname);
9442                 return -1;
9443         }
9444
9445         return inline_costs;
9446
9447  exception_exit:
9448         g_assert (cfg->exception_type != MONO_EXCEPTION_NONE);
9449         g_slist_free (class_inits);
9450         dont_inline = g_list_remove (dont_inline, method);
9451         return -1;
9452
9453  inline_failure:
9454         g_slist_free (class_inits);
9455         dont_inline = g_list_remove (dont_inline, method);
9456         return -1;
9457
9458  load_error:
9459         g_slist_free (class_inits);
9460         dont_inline = g_list_remove (dont_inline, method);
9461         cfg->exception_type = MONO_EXCEPTION_TYPE_LOAD;
9462         return -1;
9463
9464  unverified:
9465         g_slist_free (class_inits);
9466         dont_inline = g_list_remove (dont_inline, method);
9467         set_exception_type_from_invalid_il (cfg, method, ip);
9468         return -1;
9469 }
9470
9471 void
9472 mono_print_tree (MonoInst *tree) {
9473         int arity;
9474
9475         if (!tree)
9476                 return;
9477
9478         arity = mono_burg_arity [tree->opcode];
9479
9480         printf (" %s%s", arity?"(":"",  mono_inst_name (tree->opcode));
9481
9482         switch (tree->opcode) {
9483         case OP_ICONST:
9484                 printf ("[%d]", (int)tree->inst_c0);
9485                 break;
9486         case OP_I8CONST:
9487                 printf ("[%lld]", (long long)tree->inst_l);
9488                 break;
9489         case OP_R8CONST:
9490                 printf ("[%f]", *(double*)tree->inst_p0);
9491                 break;
9492         case OP_R4CONST:
9493                 printf ("[%f]", *(float*)tree->inst_p0);
9494                 break;
9495         case OP_ARG:
9496         case OP_LOCAL:
9497                 printf ("[%d]", (int)tree->inst_c0);
9498                 break;
9499         case OP_REGOFFSET:
9500                 if (tree->inst_offset < 0)
9501                         printf ("[-0x%x(%s)]", (int)(-tree->inst_offset), mono_arch_regname (tree->inst_basereg));
9502                 else
9503                         printf ("[0x%x(%s)]", (int)(tree->inst_offset), mono_arch_regname (tree->inst_basereg));
9504                 break;
9505         case OP_REGVAR:
9506                 printf ("[%s]", mono_arch_regname (tree->dreg));
9507                 break;
9508         case CEE_NEWARR:
9509                 printf ("[%s]",  tree->inst_newa_class->name);
9510                 mono_print_tree (tree->inst_newa_len);
9511                 break;
9512         case OP_CALL:
9513         case OP_CALLVIRT:
9514         case OP_FCALL:
9515         case OP_FCALLVIRT:
9516         case OP_LCALL:
9517         case OP_LCALLVIRT:
9518         case OP_VCALL:
9519         case OP_VCALLVIRT:
9520         case OP_VOIDCALL:
9521         case OP_VOIDCALLVIRT:
9522         case OP_TRAMPCALL_VTABLE: {
9523                 MonoCallInst *call = (MonoCallInst*)tree;
9524                 if (call->method)
9525                         printf ("[%s]", call->method->name);
9526                 else if (call->fptr) {
9527                         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (call->fptr);
9528                         if (info)
9529                                 printf ("[%s]", info->name);
9530                 }
9531                 break;
9532         }
9533         case OP_PHI: {
9534                 int i;
9535                 printf ("[%d (", (int)tree->inst_c0);
9536                 for (i = 0; i < tree->inst_phi_args [0]; i++) {
9537                         if (i)
9538                                 printf (", ");
9539                         printf ("%d", tree->inst_phi_args [i + 1]);
9540                 }
9541                 printf (")]");
9542                 break;
9543         }
9544         case OP_RENAME:
9545         case OP_RETARG:
9546         case OP_NOP:
9547         case OP_JMP:
9548         case OP_BREAK:
9549                 break;
9550         case OP_LOAD_MEMBASE:
9551         case OP_LOADI4_MEMBASE:
9552         case OP_LOADU4_MEMBASE:
9553         case OP_LOADU1_MEMBASE:
9554         case OP_LOADI1_MEMBASE:
9555         case OP_LOADU2_MEMBASE:
9556         case OP_LOADI2_MEMBASE:
9557                 printf ("[%s] <- [%s + 0x%x]", mono_arch_regname (tree->dreg), mono_arch_regname (tree->inst_basereg), (int)tree->inst_offset);
9558                 break;
9559         case OP_BR:
9560         case OP_CALL_HANDLER:
9561                 printf ("[B%d]", tree->inst_target_bb->block_num);
9562                 break;
9563         case OP_SWITCH:
9564         case CEE_ISINST:
9565         case CEE_CASTCLASS:
9566         case OP_OUTARG:
9567         case OP_CALL_REG:
9568         case OP_FCALL_REG:
9569         case OP_LCALL_REG:
9570         case OP_VCALL_REG:
9571         case OP_VOIDCALL_REG:
9572                 mono_print_tree (tree->inst_left);
9573                 break;
9574         case CEE_BNE_UN:
9575         case CEE_BEQ:
9576         case CEE_BLT:
9577         case CEE_BLT_UN:
9578         case CEE_BGT:
9579         case CEE_BGT_UN:
9580         case CEE_BGE:
9581         case CEE_BGE_UN:
9582         case CEE_BLE:
9583         case CEE_BLE_UN:
9584                 printf ("[B%dB%d]", tree->inst_true_bb->block_num, tree->inst_false_bb->block_num);
9585                 mono_print_tree (tree->inst_left);
9586                 break;
9587         default:
9588                 if (!mono_arch_print_tree(tree, arity)) {
9589                         if (arity) {
9590                                 mono_print_tree (tree->inst_left);
9591                                 if (arity > 1)
9592                                         mono_print_tree (tree->inst_right);
9593                         }
9594                 }
9595                 break;
9596         }
9597
9598         if (arity)
9599                 printf (")");
9600 }
9601
9602 void
9603 mono_print_tree_nl (MonoInst *tree)
9604 {
9605         mono_print_tree (tree);
9606         printf ("\n");
9607 }
9608
9609 static void
9610 create_helper_signature (void)
9611 {
9612         helper_sig_domain_get = mono_create_icall_signature ("ptr");
9613         helper_sig_class_init_trampoline = mono_create_icall_signature ("void");
9614         helper_sig_generic_class_init_trampoline = mono_create_icall_signature ("void");
9615         helper_sig_rgctx_lazy_fetch_trampoline = mono_create_icall_signature ("ptr ptr");
9616 }
9617
9618 gconstpointer
9619 mono_icall_get_wrapper (MonoJitICallInfo* callinfo)
9620 {
9621         char *name;
9622         MonoMethod *wrapper;
9623         gconstpointer trampoline;
9624         MonoDomain *domain = mono_get_root_domain ();
9625         
9626         if (callinfo->wrapper) {
9627                 return callinfo->wrapper;
9628         }
9629
9630         if (callinfo->trampoline)
9631                 return callinfo->trampoline;
9632
9633         /* 
9634          * We use the lock on the root domain instead of the JIT lock to protect 
9635          * callinfo->trampoline, since we do a lot of stuff inside the critical section.
9636          */
9637         mono_domain_lock (domain);
9638
9639         if (callinfo->trampoline) {
9640                 mono_domain_unlock (domain);
9641                 return callinfo->trampoline;
9642         }
9643
9644         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
9645         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
9646         g_free (name);
9647
9648         trampoline = mono_create_ftnptr (domain, mono_create_jit_trampoline_in_domain (domain, wrapper));
9649         mono_register_jit_icall_wrapper (callinfo, trampoline);
9650
9651         callinfo->trampoline = trampoline;
9652
9653         mono_domain_unlock (domain);
9654         
9655         return callinfo->trampoline;
9656 }
9657
9658 static void
9659 mono_dynamic_code_hash_insert (MonoDomain *domain, MonoMethod *method, MonoJitDynamicMethodInfo *ji)
9660 {
9661         if (!domain->dynamic_code_hash)
9662                 domain->dynamic_code_hash = g_hash_table_new (NULL, NULL);
9663         g_hash_table_insert (domain->dynamic_code_hash, method, ji);
9664 }
9665
9666 static MonoJitDynamicMethodInfo*
9667 mono_dynamic_code_hash_lookup (MonoDomain *domain, MonoMethod *method)
9668 {
9669         MonoJitDynamicMethodInfo *res;
9670
9671         if (domain->dynamic_code_hash)
9672                 res = g_hash_table_lookup (domain->dynamic_code_hash, method);
9673         else
9674                 res = NULL;
9675         return res;
9676 }
9677
9678 typedef struct {
9679         MonoClass *vtype;
9680         GList *active;
9681         GSList *slots;
9682 } StackSlotInfo;
9683
9684 static inline GSList*
9685 g_slist_prepend_mempool (MonoMemPool *mp, GSList   *list,
9686                                                  gpointer  data)
9687 {
9688   GSList *new_list;
9689
9690   new_list = mono_mempool_alloc (mp, sizeof (GSList));
9691   new_list->data = data;
9692   new_list->next = list;
9693
9694   return new_list;
9695 }
9696
9697 /*
9698  *  mono_allocate_stack_slots_full:
9699  *
9700  *  Allocate stack slots for all non register allocated variables using a
9701  * linear scan algorithm.
9702  * Returns: an array of stack offsets.
9703  * STACK_SIZE is set to the amount of stack space needed.
9704  * STACK_ALIGN is set to the alignment needed by the locals area.
9705  */
9706 gint32*
9707 mono_allocate_stack_slots_full (MonoCompile *cfg, gboolean backward, guint32 *stack_size, guint32 *stack_align)
9708 {
9709         int i, slot, offset, size;
9710         guint32 align;
9711         MonoMethodVar *vmv;
9712         MonoInst *inst;
9713         gint32 *offsets;
9714         GList *vars = NULL, *l;
9715         StackSlotInfo *scalar_stack_slots, *vtype_stack_slots, *slot_info;
9716         MonoType *t;
9717         int nvtypes;
9718
9719         scalar_stack_slots = mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * MONO_TYPE_PINNED);
9720         vtype_stack_slots = NULL;
9721         nvtypes = 0;
9722
9723         offsets = mono_mempool_alloc (cfg->mempool, sizeof (gint32) * cfg->num_varinfo);
9724         for (i = 0; i < cfg->num_varinfo; ++i)
9725                 offsets [i] = -1;
9726
9727         for (i = cfg->locals_start; i < cfg->num_varinfo; i++) {
9728                 inst = cfg->varinfo [i];
9729                 vmv = MONO_VARINFO (cfg, i);
9730
9731                 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR || inst->opcode == OP_REGOFFSET)
9732                         continue;
9733
9734                 vars = g_list_prepend (vars, vmv);
9735         }
9736
9737         vars = mono_varlist_sort (cfg, vars, 0);
9738         offset = 0;
9739         *stack_align = 0;
9740         for (l = vars; l; l = l->next) {
9741                 vmv = l->data;
9742                 inst = cfg->varinfo [vmv->idx];
9743
9744                 /* inst->backend.is_pinvoke indicates native sized value types, this is used by the
9745                 * pinvoke wrappers when they call functions returning structures */
9746                 if (inst->backend.is_pinvoke && MONO_TYPE_ISSTRUCT (inst->inst_vtype) && inst->inst_vtype->type != MONO_TYPE_TYPEDBYREF)
9747                         size = mono_class_native_size (inst->inst_vtype->data.klass, &align);
9748                 else {
9749                         int ialign;
9750
9751                         size = mono_type_size (inst->inst_vtype, &ialign);
9752                         align = ialign;
9753                 }
9754
9755                 t = mono_type_get_underlying_type (inst->inst_vtype);
9756                 if (t->byref) {
9757                         slot_info = &scalar_stack_slots [MONO_TYPE_I];
9758                 } else {
9759                         switch (t->type) {
9760                         case MONO_TYPE_GENERICINST:
9761                                 if (!mono_type_generic_inst_is_valuetype (t)) {
9762                                         slot_info = &scalar_stack_slots [t->type];
9763                                         break;
9764                                 }
9765                                 /* Fall through */
9766                         case MONO_TYPE_VALUETYPE:
9767                                 if (!vtype_stack_slots)
9768                                         vtype_stack_slots = mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * 256);
9769                                 for (i = 0; i < nvtypes; ++i)
9770                                         if (t->data.klass == vtype_stack_slots [i].vtype)
9771                                                 break;
9772                                 if (i < nvtypes)
9773                                         slot_info = &vtype_stack_slots [i];
9774                                 else {
9775                                         g_assert (nvtypes < 256);
9776                                         vtype_stack_slots [nvtypes].vtype = t->data.klass;
9777                                         slot_info = &vtype_stack_slots [nvtypes];
9778                                         nvtypes ++;
9779                                 }
9780                                 break;
9781                         case MONO_TYPE_CLASS:
9782                         case MONO_TYPE_OBJECT:
9783                         case MONO_TYPE_ARRAY:
9784                         case MONO_TYPE_SZARRAY:
9785                         case MONO_TYPE_STRING:
9786                         case MONO_TYPE_PTR:
9787                         case MONO_TYPE_I:
9788                         case MONO_TYPE_U:
9789 #if SIZEOF_VOID_P == 4
9790                         case MONO_TYPE_I4:
9791 #else
9792                         case MONO_TYPE_I8:
9793 #endif
9794                                 /* Share non-float stack slots of the same size */
9795                                 slot_info = &scalar_stack_slots [MONO_TYPE_CLASS];
9796                                 break;
9797                         default:
9798                                 slot_info = &scalar_stack_slots [t->type];
9799                         }
9800                 }
9801
9802                 slot = 0xffffff;
9803                 if (cfg->comp_done & MONO_COMP_LIVENESS) {
9804                         //printf ("START  %2d %08x %08x\n",  vmv->idx, vmv->range.first_use.abs_pos, vmv->range.last_use.abs_pos);
9805                         
9806                         /* expire old intervals in active */
9807                         while (slot_info->active) {
9808                                 MonoMethodVar *amv = (MonoMethodVar *)slot_info->active->data;
9809
9810                                 if (amv->range.last_use.abs_pos > vmv->range.first_use.abs_pos)
9811                                         break;
9812
9813                                 //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);
9814
9815                                 slot_info->active = g_list_delete_link (slot_info->active, slot_info->active);
9816                                 slot_info->slots = g_slist_prepend_mempool (cfg->mempool, slot_info->slots, GINT_TO_POINTER (offsets [amv->idx]));
9817                         }
9818
9819                         /* 
9820                          * This also handles the case when the variable is used in an
9821                          * exception region, as liveness info is not computed there.
9822                          */
9823                         /* 
9824                          * FIXME: All valuetypes are marked as INDIRECT because of LDADDR
9825                          * opcodes.
9826                          */
9827                         if (! (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
9828                                 if (slot_info->slots) {
9829                                         slot = GPOINTER_TO_INT (slot_info->slots->data);
9830
9831                                         slot_info->slots = slot_info->slots->next;
9832                                 }
9833
9834                                 slot_info->active = mono_varlist_insert_sorted (cfg, slot_info->active, vmv, TRUE);
9835                         }
9836                 }
9837
9838                 {
9839                         static int count = 0;
9840                         count ++;
9841
9842                         /*
9843                         if (count == atoi (getenv ("COUNT")))
9844                                 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
9845                         if (count > atoi (getenv ("COUNT")))
9846                                 slot = 0xffffff;
9847                         else {
9848                                 mono_print_tree_nl (inst);
9849                                 }
9850                         */
9851                 }
9852
9853                 if (cfg->disable_reuse_stack_slots)
9854                         slot = 0xffffff;
9855
9856                 if (slot == 0xffffff) {
9857                         /*
9858                          * Allways allocate valuetypes to sizeof (gpointer) to allow more
9859                          * efficient copying (and to work around the fact that OP_MEMCPY
9860                          * and OP_MEMSET ignores alignment).
9861                          */
9862                         if (MONO_TYPE_ISSTRUCT (t))
9863                                 align = sizeof (gpointer);
9864
9865                         if (backward) {
9866                                 offset += size;
9867                                 offset += align - 1;
9868                                 offset &= ~(align - 1);
9869                                 slot = offset;
9870                         }
9871                         else {
9872                                 offset += align - 1;
9873                                 offset &= ~(align - 1);
9874                                 slot = offset;
9875                                 offset += size;
9876                         }
9877
9878                         if (*stack_align == 0)
9879                                 *stack_align = align;
9880                 }
9881
9882                 offsets [vmv->idx] = slot;
9883         }
9884         g_list_free (vars);
9885         for (i = 0; i < MONO_TYPE_PINNED; ++i) {
9886                 if (scalar_stack_slots [i].active)
9887                         g_list_free (scalar_stack_slots [i].active);
9888         }
9889         for (i = 0; i < nvtypes; ++i) {
9890                 if (vtype_stack_slots [i].active)
9891                         g_list_free (vtype_stack_slots [i].active);
9892         }
9893
9894         mono_jit_stats.locals_stack_size += offset;
9895
9896         *stack_size = offset;
9897         return offsets;
9898 }
9899
9900 gint32*
9901 mono_allocate_stack_slots (MonoCompile *m, guint32 *stack_size, guint32 *stack_align)
9902 {
9903         return mono_allocate_stack_slots_full (m, TRUE, stack_size, stack_align);
9904 }
9905
9906 void
9907 mono_register_opcode_emulation (int opcode, const char *name, const char *sigstr, gpointer func, gboolean no_throw)
9908 {
9909         MonoJitICallInfo *info;
9910         MonoMethodSignature *sig = mono_create_icall_signature (sigstr);
9911
9912         if (!emul_opcode_map)
9913                 emul_opcode_map = g_new0 (MonoJitICallInfo*, OP_LAST + 1);
9914
9915         g_assert (!sig->hasthis);
9916         g_assert (sig->param_count < 3);
9917
9918         info = mono_register_jit_icall (func, name, sig, no_throw);
9919
9920         emul_opcode_map [opcode] = info;
9921 }
9922
9923 static void
9924 register_icall (gpointer func, const char *name, const char *sigstr, gboolean save)
9925 {
9926         MonoMethodSignature *sig;
9927
9928         if (sigstr)
9929                 sig = mono_create_icall_signature (sigstr);
9930         else
9931                 sig = NULL;
9932
9933         mono_register_jit_icall (func, name, sig, save);
9934 }
9935
9936 static void
9937 decompose_foreach (MonoInst *tree, gpointer data) 
9938 {
9939         static MonoJitICallInfo *newarr_info = NULL;
9940         static MonoJitICallInfo *newarr_specific_info = NULL;
9941         MonoJitICallInfo *info;
9942         int i;
9943
9944         switch (tree->opcode) {
9945         case CEE_NEWARR: {
9946                 MonoCompile *cfg = data;
9947                 MonoInst *iargs [3];
9948
9949                 if (!newarr_info) {
9950                         newarr_info = mono_find_jit_icall_by_addr (mono_array_new);
9951                         g_assert (newarr_info);
9952                         newarr_specific_info = mono_find_jit_icall_by_addr (mono_array_new_specific);
9953                         g_assert (newarr_specific_info);
9954                 }
9955
9956                 if (cfg->opt & MONO_OPT_SHARED) {
9957                         NEW_DOMAINCONST (cfg, iargs [0]);
9958                         NEW_CLASSCONST (cfg, iargs [1], tree->inst_newa_class);
9959                         iargs [2] = tree->inst_newa_len;
9960
9961                         info = newarr_info;
9962                 }
9963                 else {
9964                         MonoVTable *vtable = mono_class_vtable (cfg->domain, mono_array_class_get (tree->inst_newa_class, 1));
9965
9966                         g_assert (vtable);
9967                         NEW_VTABLECONST (cfg, iargs [0], vtable);
9968                         iargs [1] = tree->inst_newa_len;
9969
9970                         info = newarr_specific_info;
9971                 }
9972
9973                 mono_emulate_opcode (cfg, tree, iargs, info);
9974
9975                 /* Need to decompose arguments after the the opcode is decomposed */
9976                 for (i = 0; i < info->sig->param_count; ++i)
9977                         dec_foreach (iargs [i], cfg);
9978                 break;
9979         }
9980 #ifdef MONO_ARCH_SOFT_FLOAT
9981         case OP_FBEQ:
9982         case OP_FBGE:
9983         case OP_FBGT:
9984         case OP_FBLE:
9985         case OP_FBLT:
9986         case OP_FBNE_UN:
9987         case OP_FBGE_UN:
9988         case OP_FBGT_UN:
9989         case OP_FBLE_UN:
9990         case OP_FBLT_UN: {
9991                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
9992                         MonoCompile *cfg = data;
9993                         MonoInst *iargs [2];
9994                 
9995                         iargs [0] = tree->inst_i0;
9996                         iargs [1] = tree->inst_i1;
9997                 
9998                         mono_emulate_opcode (cfg, tree, iargs, info);
9999
10000                         dec_foreach (iargs [0], cfg);
10001                         dec_foreach (iargs [1], cfg);
10002                         break;
10003                 } else {
10004                         g_assert_not_reached ();
10005                 }
10006                 break;
10007         }
10008         case OP_FCEQ:
10009         case OP_FCGT:
10010         case OP_FCGT_UN:
10011         case OP_FCLT:
10012         case OP_FCLT_UN: {
10013                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
10014                         MonoCompile *cfg = data;
10015                         MonoInst *iargs [2];
10016
10017                         /* the args are in the compare opcode ... */
10018                         iargs [0] = tree->inst_i0;
10019                         iargs [1] = tree->inst_i1;
10020                 
10021                         mono_emulate_opcode (cfg, tree, iargs, info);
10022
10023                         dec_foreach (iargs [0], cfg);
10024                         dec_foreach (iargs [1], cfg);
10025                         break;
10026                 } else {
10027                         g_assert_not_reached ();
10028                 }
10029                 break;
10030         }
10031 #endif
10032
10033         default:
10034                 break;
10035         }
10036 }
10037
10038 void
10039 mono_inst_foreach (MonoInst *tree, MonoInstFunc func, gpointer data) {
10040
10041         switch (mono_burg_arity [tree->opcode]) {
10042         case 0: break;
10043         case 1: 
10044                 mono_inst_foreach (tree->inst_left, func, data);
10045                 break;
10046         case 2: 
10047                 mono_inst_foreach (tree->inst_left, func, data);
10048                 mono_inst_foreach (tree->inst_right, func, data);
10049                 break;
10050         default:
10051                 g_assert_not_reached ();
10052         }
10053         func (tree, data);
10054 }
10055
10056 G_GNUC_UNUSED
10057 static void
10058 mono_print_bb_code (MonoBasicBlock *bb)
10059 {
10060         MonoInst *c;
10061
10062         MONO_BB_FOR_EACH_INS (bb, c) {
10063                 mono_print_tree (c);
10064                 g_print ("\n");
10065         }
10066 }
10067
10068 static void
10069 print_dfn (MonoCompile *cfg) {
10070         int i, j;
10071         char *code;
10072         MonoBasicBlock *bb;
10073
10074         g_print ("IR code for method %s\n", mono_method_full_name (cfg->method, TRUE));
10075
10076         for (i = 0; i < cfg->num_bblocks; ++i) {
10077                 MonoInst *c;
10078
10079                 bb = cfg->bblocks [i];
10080                 /*if (bb->cil_code) {
10081                         char* code1, *code2;
10082                         code1 = mono_disasm_code_one (NULL, cfg->method, bb->cil_code, NULL);
10083                         if (bb->last_ins->cil_code)
10084                                 code2 = mono_disasm_code_one (NULL, cfg->method, bb->last_ins->cil_code, NULL);
10085                         else
10086                                 code2 = g_strdup ("");
10087
10088                         code1 [strlen (code1) - 1] = 0;
10089                         code = g_strdup_printf ("%s -> %s", code1, code2);
10090                         g_free (code1);
10091                         g_free (code2);
10092                 } else*/
10093                         code = g_strdup ("\n");
10094                 g_print ("\nBB%d DFN%d (len: %d): %s", bb->block_num, i, bb->cil_length, code);
10095                 MONO_BB_FOR_EACH_INS (bb, c) {
10096                         mono_print_tree (c);
10097                         g_print ("\n");
10098                 }
10099
10100                 g_print ("\tprev:");
10101                 for (j = 0; j < bb->in_count; ++j) {
10102                         g_print (" BB%d", bb->in_bb [j]->block_num);
10103                 }
10104                 g_print ("\t\tsucc:");
10105                 for (j = 0; j < bb->out_count; ++j) {
10106                         g_print (" BB%d", bb->out_bb [j]->block_num);
10107                 }
10108                 g_print ("\n\tidom: BB%d\n", bb->idom? bb->idom->block_num: -1);
10109
10110                 if (bb->idom)
10111                         g_assert (mono_bitset_test_fast (bb->dominators, bb->idom->dfn));
10112
10113                 if (bb->dominators)
10114                         mono_blockset_print (cfg, bb->dominators, "\tdominators", bb->idom? bb->idom->dfn: -1);
10115                 if (bb->dfrontier)
10116                         mono_blockset_print (cfg, bb->dfrontier, "\tdfrontier", -1);
10117                 g_free (code);
10118         }
10119
10120         g_print ("\n");
10121 }
10122
10123 void
10124 mono_bblock_add_inst (MonoBasicBlock *bb, MonoInst *inst)
10125 {
10126         MONO_ADD_INS (bb, inst);
10127 }
10128
10129 void
10130 mono_destroy_compile (MonoCompile *cfg)
10131 {
10132         //mono_mempool_stats (cfg->mempool);
10133         mono_free_loop_info (cfg);
10134         if (cfg->rs)
10135                 mono_regstate_free (cfg->rs);
10136         if (cfg->spvars)
10137                 g_hash_table_destroy (cfg->spvars);
10138         if (cfg->exvars)
10139                 g_hash_table_destroy (cfg->exvars);
10140         mono_mempool_destroy (cfg->mempool);
10141         g_list_free (cfg->ldstr_list);
10142         g_hash_table_destroy (cfg->token_info_hash);
10143
10144         g_free (cfg->varinfo);
10145         g_free (cfg->vars);
10146         g_free (cfg->exception_message);
10147         g_free (cfg);
10148 }
10149
10150 #ifdef HAVE_KW_THREAD
10151 static __thread gpointer mono_lmf_addr MONO_TLS_FAST;
10152 #ifdef MONO_ARCH_ENABLE_MONO_LMF_VAR
10153 /* 
10154  * When this is defined, the current lmf is stored in this tls variable instead of in 
10155  * jit_tls->lmf.
10156  */
10157 static __thread gpointer mono_lmf MONO_TLS_FAST;
10158 #endif
10159 #endif
10160
10161 guint32
10162 mono_get_jit_tls_key (void)
10163 {
10164         return mono_jit_tls_id;
10165 }
10166
10167 gint32
10168 mono_get_jit_tls_offset (void)
10169 {
10170 #ifdef HAVE_KW_THREAD
10171         int offset;
10172         MONO_THREAD_VAR_OFFSET (mono_jit_tls, offset);
10173         return offset;
10174 #else
10175         return -1;
10176 #endif
10177 }
10178
10179 gint32
10180 mono_get_lmf_tls_offset (void)
10181 {
10182 #if defined(HAVE_KW_THREAD) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
10183         int offset;
10184         MONO_THREAD_VAR_OFFSET(mono_lmf,offset);
10185         return offset;
10186 #else
10187         return -1;
10188 #endif
10189 }
10190
10191 gint32
10192 mono_get_lmf_addr_tls_offset (void)
10193 {
10194         int offset;
10195         MONO_THREAD_VAR_OFFSET(mono_lmf_addr,offset);
10196         return offset;
10197 }
10198
10199 MonoLMF *
10200 mono_get_lmf (void)
10201 {
10202 #if defined(HAVE_KW_THREAD) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
10203         return mono_lmf;
10204 #else
10205         MonoJitTlsData *jit_tls;
10206
10207         if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
10208                 return jit_tls->lmf;
10209
10210         g_assert_not_reached ();
10211         return NULL;
10212 #endif
10213 }
10214
10215 MonoLMF **
10216 mono_get_lmf_addr (void)
10217 {
10218 #ifdef HAVE_KW_THREAD
10219         return mono_lmf_addr;
10220 #else
10221         MonoJitTlsData *jit_tls;
10222
10223         if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
10224                 return &jit_tls->lmf;
10225
10226         g_assert_not_reached ();
10227         return NULL;
10228 #endif
10229 }
10230
10231 /* Called by native->managed wrappers */
10232 void
10233 mono_jit_thread_attach (MonoDomain *domain)
10234 {
10235 #ifdef HAVE_KW_THREAD
10236         if (!mono_lmf_addr) {
10237                 mono_thread_attach (domain);
10238         }
10239 #else
10240         if (!TlsGetValue (mono_jit_tls_id))
10241                 mono_thread_attach (domain);
10242 #endif
10243         if (mono_domain_get () != domain)
10244                 mono_domain_set (domain, TRUE);
10245 }       
10246
10247 /**
10248  * mono_thread_abort:
10249  * @obj: exception object
10250  *
10251  * abort the thread, print exception information and stack trace
10252  */
10253 static void
10254 mono_thread_abort (MonoObject *obj)
10255 {
10256         /* MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id); */
10257         
10258         /* handle_remove should be eventually called for this thread, too
10259         g_free (jit_tls);*/
10260
10261         if ((mono_runtime_unhandled_exception_policy_get () == MONO_UNHANLED_POLICY_LEGACY) ||
10262                         (obj->vtable->klass == mono_defaults.threadabortexception_class)) {
10263                 mono_thread_exit ();
10264         } else {
10265                 exit (mono_environment_exitcode_get ());
10266         }
10267 }
10268
10269 static void*
10270 setup_jit_tls_data (gpointer stack_start, gpointer abort_func)
10271 {
10272         MonoJitTlsData *jit_tls;
10273         MonoLMF *lmf;
10274
10275         jit_tls = TlsGetValue (mono_jit_tls_id);
10276         if (jit_tls)
10277                 return jit_tls;
10278
10279         jit_tls = g_new0 (MonoJitTlsData, 1);
10280
10281         TlsSetValue (mono_jit_tls_id, jit_tls);
10282
10283 #ifdef HAVE_KW_THREAD
10284         mono_jit_tls = jit_tls;
10285 #endif
10286
10287         jit_tls->abort_func = abort_func;
10288         jit_tls->end_of_stack = stack_start;
10289
10290         lmf = g_new0 (MonoLMF, 1);
10291 #ifdef MONO_ARCH_INIT_TOP_LMF_ENTRY
10292         MONO_ARCH_INIT_TOP_LMF_ENTRY (lmf);
10293 #else
10294         lmf->ebp = -1;
10295 #endif
10296
10297         jit_tls->first_lmf = lmf;
10298
10299 #if defined(HAVE_KW_THREAD) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
10300         /* jit_tls->lmf is unused */
10301         mono_lmf = lmf;
10302         mono_lmf_addr = &mono_lmf;
10303 #else
10304 #if defined(HAVE_KW_THREAD)
10305         mono_lmf_addr = &jit_tls->lmf;  
10306 #endif
10307
10308         jit_tls->lmf = lmf;
10309 #endif
10310
10311         mono_arch_setup_jit_tls_data (jit_tls);
10312         mono_setup_altstack (jit_tls);
10313
10314         return jit_tls;
10315 }
10316
10317 static void
10318 mono_thread_start_cb (gsize tid, gpointer stack_start, gpointer func)
10319 {
10320         MonoThread *thread;
10321         void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort);
10322         thread = mono_thread_current ();
10323         mono_debugger_thread_created (tid, thread, jit_tls);
10324         if (thread)
10325                 thread->jit_data = jit_tls;
10326 }
10327
10328 void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
10329
10330 static void
10331 mono_thread_abort_dummy (MonoObject *obj)
10332 {
10333   if (mono_thread_attach_aborted_cb)
10334     mono_thread_attach_aborted_cb (obj);
10335   else
10336     mono_thread_abort (obj);
10337 }
10338
10339 static void
10340 mono_thread_attach_cb (gsize tid, gpointer stack_start)
10341 {
10342         MonoThread *thread;
10343         void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort_dummy);
10344         thread = mono_thread_current ();
10345         mono_debugger_thread_created (tid, thread, (MonoJitTlsData *) jit_tls);
10346         if (thread)
10347                 thread->jit_data = jit_tls;
10348         if (mono_profiler_get_events () & MONO_PROFILE_STATISTICAL)
10349                 setup_stat_profiler ();
10350 }
10351
10352 static void
10353 mini_thread_cleanup (MonoThread *thread)
10354 {
10355         MonoJitTlsData *jit_tls = thread->jit_data;
10356
10357         if (jit_tls) {
10358                 mono_debugger_thread_cleanup (jit_tls);
10359                 mono_arch_free_jit_tls_data (jit_tls);
10360
10361                 mono_free_altstack (jit_tls);
10362                 g_free (jit_tls->first_lmf);
10363                 g_free (jit_tls);
10364                 thread->jit_data = NULL;
10365                 TlsSetValue (mono_jit_tls_id, NULL);
10366         }
10367 }
10368
10369 static MonoInst*
10370 mono_create_tls_get (MonoCompile *cfg, int offset)
10371 {
10372 #ifdef MONO_ARCH_HAVE_TLS_GET
10373         MonoInst* ins;
10374         
10375         if (offset == -1)
10376                 return NULL;
10377         
10378         MONO_INST_NEW (cfg, ins, OP_TLS_GET);
10379         ins->dreg = mono_regstate_next_int (cfg->rs);
10380         ins->inst_offset = offset;
10381         return ins;
10382 #else
10383         return NULL;
10384 #endif
10385 }
10386
10387 MonoInst*
10388 mono_get_jit_tls_intrinsic (MonoCompile *cfg)
10389 {
10390         return mono_create_tls_get (cfg, mono_get_jit_tls_offset ());
10391 }
10392
10393 void
10394 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
10395 {
10396         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
10397
10398         ji->ip.i = ip;
10399         ji->type = type;
10400         ji->data.target = target;
10401         ji->next = cfg->patch_info;
10402
10403         cfg->patch_info = ji;
10404 }
10405
10406 MonoJumpInfo *
10407 mono_patch_info_list_prepend (MonoJumpInfo *list, int ip, MonoJumpInfoType type, gconstpointer target)
10408 {
10409         MonoJumpInfo *ji = g_new0 (MonoJumpInfo, 1);
10410
10411         ji->ip.i = ip;
10412         ji->type = type;
10413         ji->data.target = target;
10414         ji->next = list;
10415
10416         return ji;
10417 }
10418
10419 void
10420 mono_remove_patch_info (MonoCompile *cfg, int ip)
10421 {
10422         MonoJumpInfo **ji = &cfg->patch_info;
10423
10424         while (*ji) {
10425                 if ((*ji)->ip.i == ip)
10426                         *ji = (*ji)->next;
10427                 else
10428                         ji = &((*ji)->next);
10429         }
10430 }
10431
10432 /**
10433  * mono_patch_info_dup_mp:
10434  *
10435  * Make a copy of PATCH_INFO, allocating memory from the mempool MP.
10436  */
10437 MonoJumpInfo*
10438 mono_patch_info_dup_mp (MonoMemPool *mp, MonoJumpInfo *patch_info)
10439 {
10440         MonoJumpInfo *res = mono_mempool_alloc (mp, sizeof (MonoJumpInfo));
10441         memcpy (res, patch_info, sizeof (MonoJumpInfo));
10442
10443         switch (patch_info->type) {
10444         case MONO_PATCH_INFO_RVA:
10445         case MONO_PATCH_INFO_LDSTR:
10446         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
10447         case MONO_PATCH_INFO_LDTOKEN:
10448         case MONO_PATCH_INFO_DECLSEC:
10449                 res->data.token = mono_mempool_alloc (mp, sizeof (MonoJumpInfoToken));
10450                 memcpy (res->data.token, patch_info->data.token, sizeof (MonoJumpInfoToken));
10451                 break;
10452         case MONO_PATCH_INFO_SWITCH:
10453                 res->data.table = mono_mempool_alloc (mp, sizeof (MonoJumpInfoBBTable));
10454                 memcpy (res->data.table, patch_info->data.table, sizeof (MonoJumpInfoBBTable));
10455                 break;
10456         default:
10457                 break;
10458         }
10459
10460         return res;
10461 }
10462
10463 guint
10464 mono_patch_info_hash (gconstpointer data)
10465 {
10466         const MonoJumpInfo *ji = (MonoJumpInfo*)data;
10467
10468         switch (ji->type) {
10469         case MONO_PATCH_INFO_RVA:
10470         case MONO_PATCH_INFO_LDSTR:
10471         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
10472         case MONO_PATCH_INFO_LDTOKEN:
10473         case MONO_PATCH_INFO_DECLSEC:
10474                 return (ji->type << 8) | ji->data.token->token;
10475         case MONO_PATCH_INFO_VTABLE:
10476         case MONO_PATCH_INFO_CLASS:
10477         case MONO_PATCH_INFO_IID:
10478         case MONO_PATCH_INFO_ADJUSTED_IID:
10479                 return (ji->type << 8) | (gssize)ji->data.klass;
10480         case MONO_PATCH_INFO_FIELD:
10481         case MONO_PATCH_INFO_SFLDA:
10482                 return (ji->type << 8) | (gssize)ji->data.field;
10483         case MONO_PATCH_INFO_METHODCONST:
10484         case MONO_PATCH_INFO_METHOD:
10485         case MONO_PATCH_INFO_METHOD_JUMP:
10486                 return (ji->type << 8) | (gssize)ji->data.method;
10487         case MONO_PATCH_INFO_IMAGE:
10488                 return (ji->type << 8) | (gssize)ji->data.image;                
10489         default:
10490                 return (ji->type << 8);
10491         }
10492 }
10493
10494 /* 
10495  * mono_patch_info_equal:
10496  * 
10497  * This might fail to recognize equivalent patches, i.e. floats, so its only
10498  * usable in those cases where this is not a problem, i.e. sharing GOT slots
10499  * in AOT.
10500  */
10501 gint
10502 mono_patch_info_equal (gconstpointer ka, gconstpointer kb)
10503 {
10504         const MonoJumpInfo *ji1 = (MonoJumpInfo*)ka;
10505         const MonoJumpInfo *ji2 = (MonoJumpInfo*)kb;
10506
10507         if (ji1->type != ji2->type)
10508                 return 0;
10509
10510         switch (ji1->type) {
10511         case MONO_PATCH_INFO_RVA:
10512         case MONO_PATCH_INFO_LDSTR:
10513         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
10514         case MONO_PATCH_INFO_LDTOKEN:
10515         case MONO_PATCH_INFO_DECLSEC:
10516                 if ((ji1->data.token->image != ji2->data.token->image) ||
10517                         (ji1->data.token->token != ji2->data.token->token))
10518                         return 0;
10519                 break;
10520         default:
10521                 if (ji1->data.name != ji2->data.name)
10522                         return 0;
10523                 break;
10524         }
10525
10526         return 1;
10527 }
10528
10529 gpointer
10530 mono_resolve_patch_target (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors)
10531 {
10532         unsigned char *ip = patch_info->ip.i + code;
10533         gconstpointer target = NULL;
10534
10535         switch (patch_info->type) {
10536         case MONO_PATCH_INFO_BB:
10537                 target = patch_info->data.bb->native_offset + code;
10538                 break;
10539         case MONO_PATCH_INFO_ABS:
10540                 target = patch_info->data.target;
10541                 break;
10542         case MONO_PATCH_INFO_LABEL:
10543                 target = patch_info->data.inst->inst_c0 + code;
10544                 break;
10545         case MONO_PATCH_INFO_IP:
10546                 target = ip;
10547                 break;
10548         case MONO_PATCH_INFO_METHOD_REL:
10549                 target = code + patch_info->data.offset;
10550                 break;
10551         case MONO_PATCH_INFO_INTERNAL_METHOD: {
10552                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
10553                 if (!mi) {
10554                         g_warning ("unknown MONO_PATCH_INFO_INTERNAL_METHOD %s", patch_info->data.name);
10555                         g_assert_not_reached ();
10556                 }
10557                 target = mono_icall_get_wrapper (mi);
10558                 break;
10559         }
10560         case MONO_PATCH_INFO_METHOD_JUMP: {
10561                 GSList *list;
10562
10563                 /* get the trampoline to the method from the domain */
10564                 target = mono_create_jump_trampoline (domain, patch_info->data.method, TRUE);
10565                 if (!domain->jump_target_hash)
10566                         domain->jump_target_hash = g_hash_table_new (NULL, NULL);
10567                 list = g_hash_table_lookup (domain->jump_target_hash, patch_info->data.method);
10568                 list = g_slist_prepend (list, ip);
10569                 g_hash_table_insert (domain->jump_target_hash, patch_info->data.method, list);
10570                 break;
10571         }
10572         case MONO_PATCH_INFO_METHOD:
10573                 if (patch_info->data.method == method) {
10574                         target = code;
10575                 } else {
10576                         /* get the trampoline to the method from the domain */
10577                         if (method && method->wrapper_type == MONO_WRAPPER_STATIC_RGCTX_INVOKE)
10578                                 target = mono_ldftn_nosync (patch_info->data.method);
10579                         else
10580                                 target = mono_create_jit_trampoline (patch_info->data.method);
10581                 }
10582                 break;
10583         case MONO_PATCH_INFO_SWITCH: {
10584                 gpointer *jump_table;
10585                 int i;
10586
10587                 if (method && method->dynamic) {
10588                         jump_table = mono_code_manager_reserve (mono_dynamic_code_hash_lookup (domain, method)->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
10589                 } else {
10590                         mono_domain_lock (domain);
10591                         jump_table = mono_code_manager_reserve (domain->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
10592                         mono_domain_unlock (domain);
10593                 }
10594
10595                 for (i = 0; i < patch_info->data.table->table_size; i++) {
10596                         jump_table [i] = code + GPOINTER_TO_INT (patch_info->data.table->table [i]);
10597                 }
10598                 target = jump_table;
10599                 break;
10600         }
10601         case MONO_PATCH_INFO_METHODCONST:
10602         case MONO_PATCH_INFO_CLASS:
10603         case MONO_PATCH_INFO_IMAGE:
10604         case MONO_PATCH_INFO_FIELD:
10605                 target = patch_info->data.target;
10606                 break;
10607         case MONO_PATCH_INFO_IID:
10608                 mono_class_init (patch_info->data.klass);
10609                 target = GINT_TO_POINTER ((int)patch_info->data.klass->interface_id);
10610                 break;
10611         case MONO_PATCH_INFO_ADJUSTED_IID:
10612                 mono_class_init (patch_info->data.klass);
10613                 target = GINT_TO_POINTER ((int)(-((patch_info->data.klass->interface_id + 1) * SIZEOF_VOID_P)));
10614                 break;
10615         case MONO_PATCH_INFO_VTABLE:
10616                 target = mono_class_vtable (domain, patch_info->data.klass);
10617                 g_assert (target);
10618                 break;
10619         case MONO_PATCH_INFO_CLASS_INIT: {
10620                 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.klass);
10621
10622                 g_assert (vtable);
10623                 target = mono_create_class_init_trampoline (vtable);
10624                 break;
10625         }
10626         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
10627                 target = mono_create_delegate_trampoline (patch_info->data.klass);
10628                 break;
10629         case MONO_PATCH_INFO_SFLDA: {
10630                 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.field->parent);
10631
10632                 g_assert (vtable);
10633                 if (!vtable->initialized && !(vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) && (method && mono_class_needs_cctor_run (vtable->klass, method)))
10634                         /* Done by the generated code */
10635                         ;
10636                 else {
10637                         if (run_cctors)
10638                                 mono_runtime_class_init (vtable);
10639                 }
10640                 target = (char*)vtable->data + patch_info->data.field->offset;
10641                 break;
10642         }
10643         case MONO_PATCH_INFO_RVA:
10644                 target = mono_image_rva_map (patch_info->data.token->image, patch_info->data.token->token);
10645                 break;
10646         case MONO_PATCH_INFO_R4:
10647         case MONO_PATCH_INFO_R8:
10648                 target = patch_info->data.target;
10649                 break;
10650         case MONO_PATCH_INFO_EXC_NAME:
10651                 target = patch_info->data.name;
10652                 break;
10653         case MONO_PATCH_INFO_LDSTR:
10654                 target =
10655                         mono_ldstr (domain, patch_info->data.token->image, 
10656                                                 mono_metadata_token_index (patch_info->data.token->token));
10657                 break;
10658         case MONO_PATCH_INFO_TYPE_FROM_HANDLE: {
10659                 gpointer handle;
10660                 MonoClass *handle_class;
10661
10662                 handle = mono_ldtoken (patch_info->data.token->image, 
10663                                        patch_info->data.token->token, &handle_class, NULL);
10664                 mono_class_init (handle_class);
10665                 mono_class_init (mono_class_from_mono_type (handle));
10666
10667                 target =
10668                         mono_type_get_object (domain, handle);
10669                 break;
10670         }
10671         case MONO_PATCH_INFO_LDTOKEN: {
10672                 gpointer handle;
10673                 MonoClass *handle_class;
10674                 
10675                 handle = mono_ldtoken (patch_info->data.token->image,
10676                                        patch_info->data.token->token, &handle_class, NULL);
10677                 mono_class_init (handle_class);
10678                 
10679                 target = handle;
10680                 break;
10681         }
10682         case MONO_PATCH_INFO_DECLSEC:
10683                 target = (mono_metadata_blob_heap (patch_info->data.token->image, patch_info->data.token->token) + 2);
10684                 break;
10685         case MONO_PATCH_INFO_ICALL_ADDR:
10686                 target = mono_lookup_internal_call (patch_info->data.method);
10687                 break;
10688         case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
10689                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
10690                 if (!mi) {
10691                         g_warning ("unknown MONO_PATCH_INFO_JIT_ICALL_ADDR %s", patch_info->data.name);
10692                         g_assert_not_reached ();
10693                 }
10694                 target = mi->func;
10695                 break;
10696         }
10697         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
10698                 target = mono_thread_interruption_request_flag ();
10699                 break;
10700         case MONO_PATCH_INFO_BB_OVF:
10701         case MONO_PATCH_INFO_EXC_OVF:
10702         case MONO_PATCH_INFO_GOT_OFFSET:
10703         case MONO_PATCH_INFO_NONE:
10704                 break;
10705         default:
10706                 g_assert_not_reached ();
10707         }
10708
10709         return (gpointer)target;
10710 }
10711
10712 static void
10713 dec_foreach (MonoInst *tree, MonoCompile *cfg) {
10714         MonoJitICallInfo *info;
10715
10716         decompose_foreach (tree, cfg);
10717
10718         switch (mono_burg_arity [tree->opcode]) {
10719         case 0: break;
10720         case 1: 
10721                 dec_foreach (tree->inst_left, cfg);
10722
10723                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
10724                         MonoInst *iargs [2];
10725                 
10726                         iargs [0] = tree->inst_left;
10727
10728                         mono_emulate_opcode (cfg, tree, iargs, info);
10729                         return;
10730                 }
10731
10732                 break;
10733         case 2:
10734 #ifdef MONO_ARCH_BIGMUL_INTRINS
10735                 if (tree->opcode == OP_LMUL
10736                                 && (cfg->opt & MONO_OPT_INTRINS)
10737                                 && (tree->inst_left->opcode == CEE_CONV_I8 
10738                                         || tree->inst_left->opcode == CEE_CONV_U8)
10739                                 && tree->inst_left->inst_left->type == STACK_I4
10740                                 && (tree->inst_right->opcode == CEE_CONV_I8 
10741                                         || tree->inst_right->opcode == CEE_CONV_U8)
10742                                 && tree->inst_right->inst_left->type == STACK_I4
10743                                 && tree->inst_left->opcode == tree->inst_right->opcode) {
10744                         tree->opcode = (tree->inst_left->opcode == CEE_CONV_I8 ? OP_BIGMUL: OP_BIGMUL_UN);
10745                         tree->inst_left = tree->inst_left->inst_left;
10746                         tree->inst_right = tree->inst_right->inst_left;
10747                         dec_foreach (tree, cfg);
10748                 } else 
10749 #endif
10750                         if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
10751                         MonoInst *iargs [2];
10752                 
10753                         iargs [0] = tree->inst_i0;
10754                         iargs [1] = tree->inst_i1;
10755                 
10756                         mono_emulate_opcode (cfg, tree, iargs, info);
10757
10758                         dec_foreach (iargs [0], cfg);
10759                         dec_foreach (iargs [1], cfg);
10760                         return;
10761                 } else {
10762                         dec_foreach (tree->inst_left, cfg);
10763                         dec_foreach (tree->inst_right, cfg);
10764                 }
10765                 break;
10766         default:
10767                 g_assert_not_reached ();
10768         }
10769 }
10770
10771 static void
10772 decompose_pass (MonoCompile *cfg) {
10773         MonoBasicBlock *bb;
10774
10775         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
10776                 MonoInst *tree;
10777                 cfg->cbb = bb;
10778                 cfg->prev_ins = NULL;
10779                 MONO_BB_FOR_EACH_INS (cfg->cbb, tree) {
10780                         dec_foreach (tree, cfg);
10781                         cfg->prev_ins = tree;
10782                 }
10783         }
10784 }
10785
10786 static void
10787 nullify_basic_block (MonoBasicBlock *bb) 
10788 {
10789         bb->in_count = 0;
10790         bb->out_count = 0;
10791         bb->in_bb = NULL;
10792         bb->out_bb = NULL;
10793         bb->next_bb = NULL;
10794         MONO_INST_LIST_INIT (&bb->ins_list);
10795         bb->cil_code = NULL;
10796 }
10797
10798 static void 
10799 replace_out_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
10800 {
10801         int i;
10802
10803         for (i = 0; i < bb->out_count; i++) {
10804                 MonoBasicBlock *ob = bb->out_bb [i];
10805                 if (ob == orig) {
10806                         if (!repl) {
10807                                 if (bb->out_count > 1) {
10808                                         bb->out_bb [i] = bb->out_bb [bb->out_count - 1];
10809                                 }
10810                                 bb->out_count--;
10811                         } else {
10812                                 bb->out_bb [i] = repl;
10813                         }
10814                 }
10815         }
10816 }
10817
10818 static void 
10819 replace_in_block (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl)
10820 {
10821         int i;
10822
10823         for (i = 0; i < bb->in_count; i++) {
10824                 MonoBasicBlock *ib = bb->in_bb [i];
10825                 if (ib == orig) {
10826                         if (!repl) {
10827                                 if (bb->in_count > 1) {
10828                                         bb->in_bb [i] = bb->in_bb [bb->in_count - 1];
10829                                 }
10830                                 bb->in_count--;
10831                         } else {
10832                                 bb->in_bb [i] = repl;
10833                         }
10834                 }
10835         }
10836 }
10837
10838 static void
10839 replace_out_block_in_code (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl) {
10840         MonoInst *inst;
10841         
10842         MONO_BB_FOR_EACH_INS (bb, inst) {
10843                 if (inst->opcode == OP_CALL_HANDLER) {
10844                         if (inst->inst_target_bb == orig)
10845                                 inst->inst_target_bb = repl;
10846                 }
10847         }
10848
10849         inst = mono_inst_list_last (&bb->ins_list);
10850         if (!inst)
10851                 return;
10852
10853         switch (inst->opcode) {
10854         case OP_BR:
10855                 if (inst->inst_target_bb == orig)
10856                         inst->inst_target_bb = repl;
10857                 break;
10858         case OP_SWITCH: {
10859                 int i;
10860                 int n = GPOINTER_TO_INT (inst->klass);
10861                 for (i = 0; i < n; i++ ) {
10862                         if (inst->inst_many_bb [i] == orig)
10863                                 inst->inst_many_bb [i] = repl;
10864                 }
10865                 break;
10866         }
10867         case CEE_BNE_UN:
10868         case CEE_BEQ:
10869         case CEE_BLT:
10870         case CEE_BLT_UN:
10871         case CEE_BGT:
10872         case CEE_BGT_UN:
10873         case CEE_BGE:
10874         case CEE_BGE_UN:
10875         case CEE_BLE:
10876         case CEE_BLE_UN:
10877                 if (inst->inst_true_bb == orig)
10878                         inst->inst_true_bb = repl;
10879                 if (inst->inst_false_bb == orig)
10880                         inst->inst_false_bb = repl;
10881                 break;
10882         default:
10883                 break;
10884         }
10885 }
10886
10887 static void 
10888 replace_basic_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
10889 {
10890         int i, j;
10891
10892         for (i = 0; i < bb->out_count; i++) {
10893                 MonoBasicBlock *ob = bb->out_bb [i];
10894                 for (j = 0; j < ob->in_count; j++) {
10895                         if (ob->in_bb [j] == orig) {
10896                                 ob->in_bb [j] = repl;
10897                         }
10898                 }
10899         }
10900
10901 }
10902
10903 /**
10904   * Check if a bb is useless (is just made of NOPs and ends with an
10905   * unconditional branch, or nothing).
10906   * If it is so, unlink it from the CFG and nullify it, and return TRUE.
10907   * Otherwise, return FALSE;
10908   */
10909 static gboolean
10910 remove_block_if_useless (MonoCompile *cfg, MonoBasicBlock *bb, MonoBasicBlock *previous_bb) {
10911         MonoBasicBlock *target_bb = NULL;
10912         MonoInst *inst;
10913         
10914         /* Do not touch handlers */
10915         if (bb->region != -1) {
10916                 bb->not_useless = TRUE;
10917                 return FALSE;
10918         }
10919         
10920         MONO_BB_FOR_EACH_INS (bb, inst) {
10921                 switch (inst->opcode) {
10922                 case OP_NOP:
10923                         break;
10924                 case OP_BR:
10925                         target_bb = inst->inst_target_bb;
10926                         break;
10927                 default:
10928                         bb->not_useless = TRUE;
10929                         return FALSE;
10930                 }
10931         }
10932         
10933         if (target_bb == NULL) {
10934                 if ((bb->out_count == 1) && (bb->out_bb [0] == bb->next_bb)) {
10935                         target_bb = bb->next_bb;
10936                 } else {
10937                         /* Do not touch empty BBs that do not "fall through" to their next BB (like the exit BB) */
10938                         return FALSE;
10939                 }
10940         }
10941         
10942         /* Do not touch BBs following a switch (they are the "default" branch) */
10943         inst = mono_inst_list_last (&previous_bb->ins_list);
10944         if (inst && inst->opcode == OP_SWITCH)
10945                 return FALSE;
10946         
10947         /* Do not touch BBs following the entry BB and jumping to something that is not */
10948         /* thiry "next" bb (the entry BB cannot contain the branch) */
10949         if ((previous_bb == cfg->bb_entry) && (bb->next_bb != target_bb)) {
10950                 return FALSE;
10951         }
10952
10953         /* 
10954          * Do not touch BBs following a try block as the code in 
10955          * mini_method_compile needs them to compute the length of the try block.
10956          */
10957         if (MONO_BBLOCK_IS_IN_REGION (previous_bb, MONO_REGION_TRY))
10958                 return FALSE;
10959         
10960         /* Check that there is a target BB, and that bb is not an empty loop (Bug 75061) */
10961         if ((target_bb != NULL) && (target_bb != bb)) {
10962                 MonoInst *last_ins;
10963                 int i;
10964
10965                 if (cfg->verbose_level > 1) {
10966                         printf ("remove_block_if_useless, removed BB%d\n", bb->block_num);
10967                 }
10968                 
10969                 /* unlink_bblock () modifies the bb->in_bb array so can't use a for loop here */
10970                 while (bb->in_count) {
10971                         MonoBasicBlock *in_bb = bb->in_bb [0];
10972                         mono_unlink_bblock (cfg, in_bb, bb);
10973                         link_bblock (cfg, in_bb, target_bb);
10974                         replace_out_block_in_code (in_bb, bb, target_bb);
10975                 }
10976                 
10977                 mono_unlink_bblock (cfg, bb, target_bb);
10978                 
10979                 last_ins = mono_inst_list_last (&previous_bb->ins_list);
10980
10981                 if ((previous_bb != cfg->bb_entry) &&
10982                                 (previous_bb->region == bb->region) &&
10983                                 ((last_ins == NULL) ||
10984                                 ((last_ins->opcode != OP_BR) &&
10985                                 (!(MONO_IS_COND_BRANCH_OP (last_ins))) &&
10986                                 (last_ins->opcode != OP_SWITCH)))) {
10987                         for (i = 0; i < previous_bb->out_count; i++) {
10988                                 if (previous_bb->out_bb [i] == target_bb) {
10989                                         MonoInst *jump;
10990                                         MONO_INST_NEW (cfg, jump, OP_BR);
10991                                         MONO_ADD_INS (previous_bb, jump);
10992                                         jump->cil_code = previous_bb->cil_code;
10993                                         jump->inst_target_bb = target_bb;
10994                                         break;
10995                                 }
10996                         }
10997                 }
10998                 
10999                 previous_bb->next_bb = bb->next_bb;
11000                 nullify_basic_block (bb);
11001                 
11002                 return TRUE;
11003         } else {
11004                 return FALSE;
11005         }
11006 }
11007
11008 static void
11009 merge_basic_blocks (MonoBasicBlock *bb, MonoBasicBlock *bbn) 
11010 {
11011         MonoInst *last_ins;
11012
11013         bb->out_count = bbn->out_count;
11014         bb->out_bb = bbn->out_bb;
11015
11016         replace_basic_block (bb, bbn, bb);
11017
11018         last_ins = mono_inst_list_last (&bb->ins_list);
11019
11020         /* Nullify branch at the end of bb */
11021         if (last_ins && MONO_IS_BRANCH_OP (last_ins))
11022                 last_ins->opcode = OP_NOP;
11023
11024         MONO_INST_LIST_SPLICE_TAIL_INIT (&bbn->ins_list, &bb->ins_list);
11025
11026         bb->next_bb = bbn->next_bb;
11027         nullify_basic_block (bbn);
11028 }
11029
11030 static void
11031 move_basic_block_to_end (MonoCompile *cfg, MonoBasicBlock *bb)
11032 {
11033         MonoBasicBlock *bbn, *next;
11034         MonoInst *last_ins;
11035
11036         next = bb->next_bb;
11037
11038         /* Find the previous */
11039         for (bbn = cfg->bb_entry; bbn->next_bb && bbn->next_bb != bb; bbn = bbn->next_bb)
11040                 ;
11041         if (bbn->next_bb) {
11042                 bbn->next_bb = bb->next_bb;
11043         }
11044
11045         /* Find the last */
11046         for (bbn = cfg->bb_entry; bbn->next_bb; bbn = bbn->next_bb)
11047                 ;
11048         bbn->next_bb = bb;
11049         bb->next_bb = NULL;
11050
11051         last_ins = mono_inst_list_last (&bb->ins_list);
11052
11053         /* Add a branch */
11054         if (next && (!last_ins || (last_ins->opcode != OP_NOT_REACHED))) {
11055                 MonoInst *ins;
11056
11057                 MONO_INST_NEW (cfg, ins, OP_BR);
11058                 MONO_ADD_INS (bb, ins);
11059                 link_bblock (cfg, bb, next);
11060                 ins->inst_target_bb = next;
11061         }               
11062 }
11063
11064 /* checks that a and b represent the same instructions, conservatively,
11065  * it can return FALSE also for two trees that are equal.
11066  * FIXME: also make sure there are no side effects.
11067  */
11068 static int
11069 same_trees (MonoInst *a, MonoInst *b)
11070 {
11071         int arity;
11072         if (a->opcode != b->opcode)
11073                 return FALSE;
11074         arity = mono_burg_arity [a->opcode];
11075         if (arity == 1) {
11076                 if (a->ssa_op == b->ssa_op && a->ssa_op == MONO_SSA_LOAD && a->inst_i0 == b->inst_i0)
11077                         return TRUE;
11078                 return same_trees (a->inst_left, b->inst_left);
11079         } else if (arity == 2) {
11080                 return same_trees (a->inst_left, b->inst_left) && same_trees (a->inst_right, b->inst_right);
11081         } else if (arity == 0) {
11082                 switch (a->opcode) {
11083                 case OP_ICONST:
11084                         return a->inst_c0 == b->inst_c0;
11085                 default:
11086                         return FALSE;
11087                 }
11088         }
11089         return FALSE;
11090 }
11091
11092 static int
11093 get_unsigned_condbranch (int opcode)
11094 {
11095         switch (opcode) {
11096         case CEE_BLE: return CEE_BLE_UN;
11097         case CEE_BLT: return CEE_BLT_UN;
11098         case CEE_BGE: return CEE_BGE_UN;
11099         case CEE_BGT: return CEE_BGT_UN;
11100         }
11101         g_assert_not_reached ();
11102         return 0;
11103 }
11104
11105 static int
11106 tree_is_unsigned (MonoInst* ins) {
11107         switch (ins->opcode) {
11108         case OP_ICONST:
11109                 return (int)ins->inst_c0 >= 0;
11110         /* array lengths are positive as are string sizes */
11111         case CEE_LDLEN:
11112         case OP_STRLEN:
11113                 return TRUE;
11114         case CEE_CONV_U1:
11115         case CEE_CONV_U2:
11116         case CEE_CONV_U4:
11117         case CEE_CONV_OVF_U1:
11118         case CEE_CONV_OVF_U2:
11119         case CEE_CONV_OVF_U4:
11120                 return TRUE;
11121         case CEE_LDIND_U1:
11122         case CEE_LDIND_U2:
11123         case CEE_LDIND_U4:
11124                 return TRUE;
11125         default:
11126                 return FALSE;
11127         }
11128 }
11129
11130 /* check if an unsigned compare can be used instead of two signed compares
11131  * for (val < 0 || val > limit) conditionals.
11132  * Returns TRUE if the optimization has been applied.
11133  * Note that this can't be applied if the second arg is not positive...
11134  */
11135 static int
11136 try_unsigned_compare (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *bb_last)
11137 {
11138         MonoBasicBlock *truet, *falset;
11139         MonoInst *cmp_inst = bb_last->inst_left;
11140         MonoInst *condb;
11141         if (!cmp_inst->inst_right->inst_c0 == 0)
11142                 return FALSE;
11143         truet = bb_last->inst_true_bb;
11144         falset = bb_last->inst_false_bb;
11145         if (falset->in_count != 1)
11146                 return FALSE;
11147         condb = mono_inst_list_last (&falset->ins_list);
11148         /* target bb must have one instruction */
11149         if (!condb || (condb->node.next != &falset->ins_list))
11150                 return FALSE;
11151         if ((((condb->opcode == CEE_BLE || condb->opcode == CEE_BLT) && (condb->inst_false_bb == truet))
11152                         || ((condb->opcode == CEE_BGE || condb->opcode == CEE_BGT) && (condb->inst_true_bb == truet)))
11153                         && same_trees (cmp_inst->inst_left, condb->inst_left->inst_left)) {
11154                 if (!tree_is_unsigned (condb->inst_left->inst_right))
11155                         return FALSE;
11156                 condb->opcode = get_unsigned_condbranch (condb->opcode);
11157                 /* change the original condbranch to just point to the new unsigned check */
11158                 bb_last->opcode = OP_BR;
11159                 bb_last->inst_target_bb = falset;
11160                 replace_out_block (bb, truet, NULL);
11161                 replace_in_block (truet, bb, NULL);
11162                 return TRUE;
11163         }
11164         return FALSE;
11165 }
11166
11167 /*
11168  * Optimizes the branches on the Control Flow Graph
11169  *
11170  */
11171 static void
11172 optimize_branches (MonoCompile *cfg)
11173 {
11174         int i, changed = FALSE;
11175         MonoBasicBlock *bb, *bbn;
11176         guint32 niterations;
11177
11178         /*
11179          * Some crazy loops could cause the code below to go into an infinite
11180          * loop, see bug #53003 for an example. To prevent this, we put an upper
11181          * bound on the number of iterations.
11182          */
11183         if (cfg->num_bblocks > 1000)
11184                 niterations = cfg->num_bblocks * 2;
11185         else
11186                 niterations = 1000;
11187
11188         do {
11189                 MonoBasicBlock *previous_bb;
11190                 changed = FALSE;
11191                 niterations --;
11192
11193                 /* we skip the entry block (exit is handled specially instead ) */
11194                 for (previous_bb = cfg->bb_entry, bb = cfg->bb_entry->next_bb; bb; previous_bb = bb, bb = bb->next_bb) {
11195                         MonoInst *last_ins;
11196
11197                         /* dont touch code inside exception clauses */
11198                         if (bb->region != -1)
11199                                 continue;
11200
11201                         if (!bb->not_useless && remove_block_if_useless (cfg, bb, previous_bb)) {
11202                                 changed = TRUE;
11203                                 continue;
11204                         }
11205
11206                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
11207                                 if (cfg->verbose_level > 2)
11208                                         g_print ("nullify block triggered %d\n", bbn->block_num);
11209
11210                                 bb->next_bb = bbn->next_bb;
11211
11212                                 for (i = 0; i < bbn->out_count; i++)
11213                                         replace_in_block (bbn->out_bb [i], bbn, NULL);
11214
11215                                 nullify_basic_block (bbn);                      
11216                                 changed = TRUE;
11217                         }
11218
11219                         last_ins = mono_inst_list_last (&bb->ins_list);
11220                         if (bb->out_count == 1) {
11221                                 bbn = bb->out_bb [0];
11222
11223                                 /* conditional branches where true and false targets are the same can be also replaced with OP_BR */
11224                                 if (last_ins && MONO_IS_COND_BRANCH_OP (last_ins)) {
11225                                         MonoInst *pop;
11226                                         MONO_INST_NEW (cfg, pop, CEE_POP);
11227                                         pop->inst_left = last_ins->inst_left->inst_left;
11228                                         mono_add_ins_to_end (bb, pop);
11229                                         MONO_INST_NEW (cfg, pop, CEE_POP);
11230                                         pop->inst_left = last_ins->inst_left->inst_right;
11231                                         mono_add_ins_to_end (bb, pop);
11232                                         last_ins->opcode = OP_BR;
11233                                         last_ins->inst_target_bb = last_ins->inst_true_bb;
11234                                         changed = TRUE;
11235                                         if (cfg->verbose_level > 2)
11236                                                 g_print ("cond branch removal triggered in %d %d\n", bb->block_num, bb->out_count);
11237                                 }
11238
11239                                 if (bb->region == bbn->region && bb->next_bb == bbn) {
11240                                         /* the block are in sequence anyway ... */
11241
11242                                         /* branches to the following block can be removed */
11243                                         if (last_ins && last_ins->opcode == OP_BR) {
11244                                                 last_ins->opcode = OP_NOP;
11245                                                 changed = TRUE;
11246                                                 if (cfg->verbose_level > 2)
11247                                                         g_print ("br removal triggered %d -> %d\n", bb->block_num, bbn->block_num);
11248                                         }
11249
11250                                         if (bbn->in_count == 1) {
11251
11252                                                 if (bbn != cfg->bb_exit) {
11253                                                         if (cfg->verbose_level > 2)
11254                                                                 g_print ("block merge triggered %d -> %d\n", bb->block_num, bbn->block_num);
11255                                                         merge_basic_blocks (bb, bbn);
11256                                                         changed = TRUE;
11257                                                         continue;
11258                                                 }
11259
11260                                                 //mono_print_bb_code (bb);
11261                                         }
11262                                 }
11263                         }
11264                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
11265                                 if (cfg->verbose_level > 2) {
11266                                         g_print ("nullify block triggered %d\n", bbn->block_num);
11267                                 }
11268                                 bb->next_bb = bbn->next_bb;
11269
11270                                 for (i = 0; i < bbn->out_count; i++)
11271                                         replace_in_block (bbn->out_bb [i], bbn, NULL);
11272
11273                                 nullify_basic_block (bbn);                      
11274                                 changed = TRUE;
11275                                 continue;
11276                         }
11277
11278                         if (bb->out_count == 1) {
11279                                 bbn = bb->out_bb [0];
11280
11281                                 if (last_ins && last_ins->opcode == OP_BR) {
11282                                         MonoInst *bbn_code;
11283
11284                                         bbn = last_ins->inst_target_bb;
11285                                         bbn_code = mono_inst_list_first (&bbn->ins_list);
11286                                         if (bb->region == bbn->region && bbn_code &&
11287                                                         bbn_code->opcode == OP_BR &&
11288                                                         bbn_code->inst_target_bb->region == bb->region) {
11289                                                 if (cfg->verbose_level > 2)
11290                                                         g_print ("in %s branch to branch triggered %d -> %d -> %d\n", cfg->method->name, 
11291                                                                  bb->block_num, bbn->block_num, bbn_code->inst_target_bb->block_num);
11292
11293                                                 replace_in_block (bbn, bb, NULL);
11294                                                 replace_out_block (bb, bbn, bbn_code->inst_target_bb);
11295                                                 link_bblock (cfg, bb, bbn_code->inst_target_bb);
11296                                                 last_ins->inst_target_bb = bbn_code->inst_target_bb;
11297                                                 changed = TRUE;
11298                                                 continue;
11299                                         }
11300                                 }
11301                         } else if (bb->out_count == 2) {
11302                                 if (last_ins && MONO_IS_COND_BRANCH_NOFP (last_ins)) {
11303                                         int branch_result = mono_eval_cond_branch (last_ins);
11304                                         MonoBasicBlock *taken_branch_target = NULL, *untaken_branch_target = NULL;
11305                                         MonoInst *bbn_code;
11306
11307                                         if (branch_result == BRANCH_TAKEN) {
11308                                                 taken_branch_target = last_ins->inst_true_bb;
11309                                                 untaken_branch_target = last_ins->inst_false_bb;
11310                                         } else if (branch_result == BRANCH_NOT_TAKEN) {
11311                                                 taken_branch_target = last_ins->inst_false_bb;
11312                                                 untaken_branch_target = last_ins->inst_true_bb;
11313                                         }
11314                                         if (taken_branch_target) {
11315                                                 /* if mono_eval_cond_branch () is ever taken to handle 
11316                                                  * non-constant values to compare, issue a pop here.
11317                                                  */
11318                                                 last_ins->opcode = OP_BR;
11319                                                 last_ins->inst_target_bb = taken_branch_target;
11320                                                 mono_unlink_bblock (cfg, bb, untaken_branch_target);
11321                                                 changed = TRUE;
11322                                                 continue;
11323                                         }
11324                                         bbn = last_ins->inst_true_bb;
11325                                         bbn_code = mono_inst_list_first (&bbn->ins_list);
11326                                         if (bb->region == bbn->region && bbn_code && bbn_code->opcode == OP_BR &&
11327                                                         bbn_code->inst_target_bb->region == bb->region) {
11328                                                 if (cfg->verbose_level > 2)             
11329                                                         g_print ("cbranch1 to branch triggered %d -> (%d) %d (0x%02x)\n", 
11330                                                                  bb->block_num, bbn->block_num, bbn_code->inst_target_bb->block_num, 
11331                                                                  bbn_code->opcode);
11332
11333                                                 /* 
11334                                                  * Unlink, then relink bblocks to avoid various
11335                                                  * tricky situations when the two targets of the branch
11336                                                  * are equal, or will become equal after the change.
11337                                                  */
11338                                                 mono_unlink_bblock (cfg, bb, last_ins->inst_true_bb);
11339                                                 mono_unlink_bblock (cfg, bb, last_ins->inst_false_bb);
11340
11341                                                 last_ins->inst_true_bb = bbn_code->inst_target_bb;
11342
11343                                                 link_bblock (cfg, bb, last_ins->inst_true_bb);
11344                                                 link_bblock (cfg, bb, last_ins->inst_false_bb);
11345
11346                                                 changed = TRUE;
11347                                                 continue;
11348                                         }
11349
11350                                         bbn = last_ins->inst_false_bb;
11351                                         bbn_code = mono_inst_list_first (&bbn->ins_list);
11352                                         if (bb->region == bbn->region && bbn_code && bbn_code->opcode == OP_BR &&
11353                                                         bbn_code->inst_target_bb->region == bb->region) {
11354                                                 if (cfg->verbose_level > 2)
11355                                                         g_print ("cbranch2 to branch triggered %d -> (%d) %d (0x%02x)\n", 
11356                                                                  bb->block_num, bbn->block_num, bbn_code->inst_target_bb->block_num, 
11357                                                                  bbn_code->opcode);
11358
11359                                                 mono_unlink_bblock (cfg, bb, last_ins->inst_true_bb);
11360                                                 mono_unlink_bblock (cfg, bb, last_ins->inst_false_bb);
11361
11362                                                 last_ins->inst_false_bb = bbn_code->inst_target_bb;
11363
11364                                                 link_bblock (cfg, bb, last_ins->inst_true_bb);
11365                                                 link_bblock (cfg, bb, last_ins->inst_false_bb);
11366
11367                                                 changed = TRUE;
11368                                                 continue;
11369                                         }
11370                                 }
11371
11372                                 /* detect and optimize to unsigned compares checks like: if (v < 0 || v > limit */
11373                                 if (last_ins && last_ins->opcode == CEE_BLT && last_ins->inst_left->inst_right->opcode == OP_ICONST) {
11374                                         if (try_unsigned_compare (cfg, bb, last_ins)) {
11375                                                 /*g_print ("applied in bb %d (->%d) %s\n", bb->block_num, last_ins->inst_target_bb->block_num, mono_method_full_name (cfg->method, TRUE));*/
11376                                                 changed = TRUE;
11377                                                 continue;
11378                                         }
11379                                 }
11380
11381                                 if (last_ins && MONO_IS_COND_BRANCH_NOFP (last_ins)) {
11382                                         if (last_ins->inst_false_bb->out_of_line && (bb->region == last_ins->inst_false_bb->region)) {
11383                                                 /* Reverse the branch */
11384                                                 last_ins->opcode = reverse_branch_op (last_ins->opcode);
11385                                                 bbn = last_ins->inst_false_bb;
11386                                                 last_ins->inst_false_bb = last_ins->inst_true_bb;
11387                                                 last_ins->inst_true_bb = bbn;
11388
11389                                                 move_basic_block_to_end (cfg, last_ins->inst_true_bb);
11390                                                 if (cfg->verbose_level > 2)
11391                                                         g_print ("cbranch to throw block triggered %d.\n", 
11392                                                                          bb->block_num);
11393                                         }
11394                                 }
11395                         }
11396                 }
11397         } while (changed && (niterations > 0));
11398
11399 }
11400
11401 static void
11402 mono_compile_create_vars (MonoCompile *cfg)
11403 {
11404         MonoMethodSignature *sig;
11405         MonoMethodHeader *header;
11406         int i;
11407
11408         header = mono_method_get_header (cfg->method);
11409
11410         sig = mono_method_signature (cfg->method);
11411         
11412         if (!MONO_TYPE_IS_VOID (sig->ret)) {
11413                 cfg->ret = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
11414                 cfg->ret->opcode = OP_RETARG;
11415                 cfg->ret->inst_vtype = sig->ret;
11416                 cfg->ret->klass = mono_class_from_mono_type (sig->ret);
11417         }
11418         if (cfg->verbose_level > 2)
11419                 g_print ("creating vars\n");
11420
11421         cfg->args = mono_mempool_alloc0 (cfg->mempool, (sig->param_count + sig->hasthis) * sizeof (MonoInst*));
11422
11423         if (sig->hasthis)
11424                 cfg->args [0] = mono_compile_create_var (cfg, &cfg->method->klass->this_arg, OP_ARG);
11425
11426         for (i = 0; i < sig->param_count; ++i) {
11427                 cfg->args [i + sig->hasthis] = mono_compile_create_var (cfg, sig->params [i], OP_ARG);
11428                 if (sig->params [i]->byref) {
11429                         cfg->disable_ssa = TRUE;
11430                 }
11431         }
11432
11433         cfg->locals_start = cfg->num_varinfo;
11434
11435         if (cfg->verbose_level > 2)
11436                 g_print ("creating locals\n");
11437
11438         for (i = 0; i < header->num_locals; ++i)
11439                 mono_compile_create_var (cfg, header->locals [i], OP_LOCAL);
11440         if (cfg->verbose_level > 2)
11441                 g_print ("locals done\n");
11442
11443         mono_arch_create_vars (cfg);
11444 }
11445
11446 void
11447 mono_print_code (MonoCompile *cfg)
11448 {
11449         MonoBasicBlock *bb;
11450         
11451         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11452                 MonoInst *tree;
11453
11454                 if (!MONO_INST_LIST_EMPTY (&bb->ins_list))
11455                         g_print ("CODE BLOCK %d (nesting %d):\n",
11456                                  bb->block_num, bb->nesting);
11457
11458                 MONO_BB_FOR_EACH_INS (bb, tree) {
11459                         mono_print_tree (tree);
11460                         g_print ("\n");
11461                 }
11462         }
11463 }
11464
11465 extern const char * const mono_burg_rule_string [];
11466
11467 static void
11468 emit_state (MonoCompile *cfg, MBState *state, int goal)
11469 {
11470         MBState *kids [10];
11471         int ern = mono_burg_rule (state, goal);
11472         const guint16 *nts = mono_burg_nts_data + mono_burg_nts [ern];
11473
11474         //g_print ("rule: %s\n", mono_burg_rule_string [ern]);
11475         switch (goal) {
11476         case MB_NTERM_reg:
11477                 //if (state->reg2)
11478                 //      state->reg1 = state->reg2; /* chain rule */
11479                 //else
11480 #ifdef MONO_ARCH_ENABLE_EMIT_STATE_OPT
11481                 if (!state->reg1)
11482 #endif
11483                         state->reg1 = mono_regstate_next_int (cfg->rs);
11484                 //g_print ("alloc symbolic R%d (reg2: R%d) in block %d\n", state->reg1, state->reg2, cfg->cbb->block_num);
11485                 break;
11486         case MB_NTERM_lreg:
11487                 state->reg1 = mono_regstate_next_int (cfg->rs);
11488                 state->reg2 = mono_regstate_next_int (cfg->rs);
11489                 break;
11490         case MB_NTERM_freg:
11491 #ifdef MONO_ARCH_SOFT_FLOAT
11492                 state->reg1 = mono_regstate_next_int (cfg->rs);
11493                 state->reg2 = mono_regstate_next_int (cfg->rs);
11494 #else
11495                 state->reg1 = mono_regstate_next_float (cfg->rs);
11496 #endif
11497                 break;
11498         default:
11499 #ifdef MONO_ARCH_ENABLE_EMIT_STATE_OPT
11500                 /*
11501                  * Enabling this might cause bugs to surface in the local register
11502                  * allocators on some architectures like x86.
11503                  */
11504                 if ((state->tree->ssa_op == MONO_SSA_STORE) && (state->left->tree->opcode == OP_REGVAR)) {
11505                         /* Do not optimize away reg-reg moves */
11506                         if (! ((state->right->tree->ssa_op == MONO_SSA_LOAD) && (state->right->left->tree->opcode == OP_REGVAR))) {
11507                                 state->right->reg1 = state->left->tree->dreg;
11508                         }
11509                 }
11510 #endif
11511
11512                 /* do nothing */
11513                 break;
11514         }
11515         if (nts [0]) {
11516                 mono_burg_kids (state, ern, kids);
11517
11518                 emit_state (cfg, kids [0], nts [0]);
11519                 if (nts [1]) {
11520                         emit_state (cfg, kids [1], nts [1]);
11521                         if (nts [2]) {
11522                                 emit_state (cfg, kids [2], nts [2]);
11523                                 if (nts [3]) {
11524                                         g_assert (!nts [4]);
11525                                         emit_state (cfg, kids [3], nts [3]);
11526                                 }
11527                         }
11528                 }
11529         }
11530
11531 //      g_print ("emit: %s (%p)\n", mono_burg_rule_string [ern], state);
11532         mono_burg_emit (ern, state, state->tree, cfg);
11533 }
11534
11535 #define DEBUG_SELECTION
11536
11537 static void 
11538 mini_select_instructions (MonoCompile *cfg)
11539 {
11540         MonoBasicBlock *bb;
11541         
11542         cfg->state_pool = mono_mempool_new ();
11543         cfg->rs = mono_regstate_new ();
11544
11545         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11546                 MonoInst *last_ins = mono_inst_list_last (&bb->ins_list);
11547
11548                 if (last_ins && MONO_IS_COND_BRANCH_OP (last_ins) &&
11549                                 bb->next_bb != last_ins->inst_false_bb) {
11550
11551                         /* we are careful when inverting, since bugs like #59580
11552                          * could show up when dealing with NaNs.
11553                          */
11554                         if (MONO_IS_COND_BRANCH_NOFP(last_ins) && bb->next_bb == last_ins->inst_true_bb) {
11555                                 MonoBasicBlock *tmp =  last_ins->inst_true_bb;
11556                                 last_ins->inst_true_bb = last_ins->inst_false_bb;
11557                                 last_ins->inst_false_bb = tmp;
11558
11559                                 last_ins->opcode = reverse_branch_op (last_ins->opcode);
11560                         } else {                        
11561                                 MonoInst *inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
11562                                 inst->opcode = OP_BR;
11563                                 inst->inst_target_bb = last_ins->inst_false_bb;
11564                                 mono_bblock_add_inst (bb, inst);
11565                         }
11566                 }
11567         }
11568
11569 #ifdef DEBUG_SELECTION
11570         if (cfg->verbose_level >= 4) {
11571         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11572                 MonoInst *tree; 
11573                 g_print ("DUMP BLOCK %d:\n", bb->block_num);
11574
11575                 MONO_BB_FOR_EACH_INS (bb, tree) {
11576                         mono_print_tree (tree);
11577                         g_print ("\n");
11578                 }
11579         }
11580         }
11581 #endif
11582
11583         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11584                 MonoInst *tree, *n;     
11585                 MonoInstList head;
11586                 MBState *mbstate;
11587
11588                 MONO_INST_LIST_INIT (&head);
11589                 if (MONO_INST_LIST_EMPTY (&bb->ins_list))
11590                         continue;
11591                 MONO_INST_LIST_SPLICE_INIT (&bb->ins_list, &head);
11592                 
11593                 cfg->cbb = bb;
11594                 mono_regstate_reset (cfg->rs);
11595
11596 #ifdef DEBUG_SELECTION
11597                 if (cfg->verbose_level >= 3)
11598                         g_print ("LABEL BLOCK %d:\n", bb->block_num);
11599 #endif
11600                 MONO_INST_LIST_FOR_EACH_ENTRY_SAFE (tree, n, &head, node) {
11601 #ifdef DEBUG_SELECTION
11602                         if (cfg->verbose_level >= 3) {
11603                                 mono_print_tree (tree);
11604                                 g_print ("\n");
11605                         }
11606 #endif
11607
11608                         cfg->ip = tree->cil_code;
11609                         if (!(mbstate = mono_burg_label (tree, cfg))) {
11610                                 g_warning ("unable to label tree %p", tree);
11611                                 mono_print_tree (tree);
11612                                 g_print ("\n");                         
11613                                 g_assert_not_reached ();
11614                         }
11615                         emit_state (cfg, mbstate, MB_NTERM_stmt);
11616                 }
11617                 bb->max_vreg = cfg->rs->next_vreg;
11618
11619                 mono_mempool_empty (cfg->state_pool); 
11620         }
11621         mono_mempool_destroy (cfg->state_pool); 
11622
11623         cfg->ip = NULL;
11624 }
11625
11626 /*
11627  * mono_normalize_opcodes:
11628  *
11629  *   Replace CEE_ and OP_ opcodes with the corresponding OP_I or OP_L opcodes.
11630  */
11631
11632 static gint16 *remap_table;
11633
11634 #if SIZEOF_VOID_P == 8
11635 #define REMAP_OPCODE(opcode) OP_L ## opcode
11636 #else
11637 #define REMAP_OPCODE(opcode) OP_I ## opcode
11638 #endif
11639
11640 static G_GNUC_UNUSED void
11641 mono_normalize_opcodes (MonoCompile *cfg, MonoBasicBlock *bb)
11642 {
11643         MonoInst *ins;
11644
11645         if (!remap_table) {
11646                 remap_table = g_new0 (gint16, OP_LAST);
11647
11648 #if SIZEOF_VOID_P == 8
11649                 remap_table [CEE_CONV_U8] = OP_ZEXT_I4;
11650                 remap_table [CEE_CONV_U] = OP_ZEXT_I4;
11651                 remap_table [CEE_CONV_I8] = OP_SEXT_I4;
11652                 remap_table [CEE_CONV_I] = OP_SEXT_I4;
11653                 remap_table [CEE_CONV_OVF_U4] = OP_LCONV_TO_OVF_U4;
11654                 remap_table [CEE_CONV_OVF_I4_UN] = OP_LCONV_TO_OVF_I4_UN;
11655 #else
11656 #endif
11657                 remap_table [CEE_CONV_R4] = OP_ICONV_TO_R4;
11658                 remap_table [CEE_CONV_R8] = OP_ICONV_TO_R8;
11659                 remap_table [CEE_CONV_I4] = OP_MOVE;
11660                 remap_table [CEE_CONV_U4] = OP_MOVE;
11661                 remap_table [CEE_CONV_I1] = REMAP_OPCODE (CONV_TO_I1);
11662                 remap_table [CEE_CONV_I2] = REMAP_OPCODE (CONV_TO_I2);
11663                 remap_table [CEE_CONV_U1] = REMAP_OPCODE (CONV_TO_U1);
11664                 remap_table [CEE_CONV_U2] = REMAP_OPCODE (CONV_TO_U2);
11665                 remap_table [CEE_CONV_R_UN] = REMAP_OPCODE (CONV_TO_R_UN);
11666                 remap_table [CEE_ADD] = REMAP_OPCODE (ADD);
11667                 remap_table [CEE_SUB] = REMAP_OPCODE (SUB);
11668                 remap_table [CEE_MUL] = REMAP_OPCODE (MUL);
11669                 remap_table [CEE_DIV] = REMAP_OPCODE (DIV);
11670                 remap_table [CEE_REM] = REMAP_OPCODE (REM);
11671                 remap_table [CEE_DIV_UN] = REMAP_OPCODE (DIV_UN);
11672                 remap_table [CEE_REM_UN] = REMAP_OPCODE (REM_UN);
11673                 remap_table [CEE_AND] = REMAP_OPCODE (AND);
11674                 remap_table [CEE_OR] = REMAP_OPCODE (OR);
11675                 remap_table [CEE_XOR] = REMAP_OPCODE (XOR);
11676                 remap_table [CEE_SHL] = REMAP_OPCODE (SHL);
11677                 remap_table [CEE_SHR] = REMAP_OPCODE (SHR);
11678                 remap_table [CEE_SHR_UN] = REMAP_OPCODE (SHR_UN);
11679                 remap_table [CEE_NOT] = REMAP_OPCODE (NOT);
11680                 remap_table [CEE_NEG] = REMAP_OPCODE (NEG);
11681                 remap_table [CEE_CALL] = OP_CALL;
11682                 remap_table [CEE_BEQ] = REMAP_OPCODE (BEQ);
11683                 remap_table [CEE_BNE_UN] = REMAP_OPCODE (BNE_UN);
11684                 remap_table [CEE_BLT] = REMAP_OPCODE (BLT);
11685                 remap_table [CEE_BLT_UN] = REMAP_OPCODE (BLT_UN);
11686                 remap_table [CEE_BGT] = REMAP_OPCODE (BGT);
11687                 remap_table [CEE_BGT_UN] = REMAP_OPCODE (BGT_UN);
11688                 remap_table [CEE_BGE] = REMAP_OPCODE (BGE);
11689                 remap_table [CEE_BGE_UN] = REMAP_OPCODE (BGE_UN);
11690                 remap_table [CEE_BLE] = REMAP_OPCODE (BLE);
11691                 remap_table [CEE_BLE_UN] = REMAP_OPCODE (BLE_UN);
11692                 remap_table [CEE_ADD_OVF] = REMAP_OPCODE (ADD_OVF);
11693                 remap_table [CEE_ADD_OVF_UN] = REMAP_OPCODE (ADD_OVF_UN);
11694                 remap_table [CEE_SUB_OVF] = REMAP_OPCODE (SUB_OVF);
11695                 remap_table [CEE_SUB_OVF_UN] = REMAP_OPCODE (SUB_OVF_UN);
11696                 remap_table [CEE_MUL_OVF] = REMAP_OPCODE (MUL_OVF);
11697                 remap_table [CEE_MUL_OVF_UN] = REMAP_OPCODE (MUL_OVF_UN);
11698         }
11699
11700         MONO_BB_FOR_EACH_INS (bb, ins) {
11701                 int remapped = remap_table [ins->opcode];
11702                 if (remapped)
11703                         ins->opcode = remapped;
11704         }
11705 }
11706
11707 void
11708 mono_codegen (MonoCompile *cfg)
11709 {
11710         MonoJumpInfo *patch_info;
11711         MonoBasicBlock *bb;
11712         int i, max_epilog_size;
11713         guint8 *code;
11714
11715         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11716                 cfg->spill_count = 0;
11717                 /* we reuse dfn here */
11718                 /* bb->dfn = bb_count++; */
11719 #ifdef MONO_ARCH_ENABLE_NORMALIZE_OPCODES
11720                 mono_normalize_opcodes (cfg, bb);
11721 #endif
11722
11723                 mono_arch_lowering_pass (cfg, bb);
11724
11725                 if (cfg->opt & MONO_OPT_PEEPHOLE)
11726                         mono_arch_peephole_pass_1 (cfg, bb);
11727
11728                 mono_local_regalloc (cfg, bb);
11729
11730                 if (cfg->opt & MONO_OPT_PEEPHOLE)
11731                         mono_arch_peephole_pass_2 (cfg, bb);
11732         }
11733
11734         if (cfg->prof_options & MONO_PROFILE_COVERAGE)
11735                 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, cfg->num_bblocks);
11736
11737         code = mono_arch_emit_prolog (cfg);
11738
11739         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
11740                 code = mono_arch_instrument_prolog (cfg, mono_profiler_method_enter, code, FALSE);
11741
11742         cfg->code_len = code - cfg->native_code;
11743         cfg->prolog_end = cfg->code_len;
11744
11745         mono_debug_open_method (cfg);
11746
11747         /* emit code all basic blocks */
11748         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11749                 bb->native_offset = cfg->code_len;
11750                 mono_arch_output_basic_block (cfg, bb);
11751
11752                 if (bb == cfg->bb_exit) {
11753                         cfg->epilog_begin = cfg->code_len;
11754
11755                         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE) {
11756                                 code = cfg->native_code + cfg->code_len;
11757                                 code = mono_arch_instrument_epilog (cfg, mono_profiler_method_leave, code, FALSE);
11758                                 cfg->code_len = code - cfg->native_code;
11759                                 g_assert (cfg->code_len < cfg->code_size);
11760                         }
11761
11762                         mono_arch_emit_epilog (cfg);
11763                 }
11764         }
11765
11766         mono_arch_emit_exceptions (cfg);
11767
11768         max_epilog_size = 0;
11769
11770         code = cfg->native_code + cfg->code_len;
11771
11772         /* we always allocate code in cfg->domain->code_mp to increase locality */
11773         cfg->code_size = cfg->code_len + max_epilog_size;
11774         /* fixme: align to MONO_ARCH_CODE_ALIGNMENT */
11775
11776         if (cfg->method->dynamic) {
11777                 /* Allocate the code into a separate memory pool so it can be freed */
11778                 cfg->dynamic_info = g_new0 (MonoJitDynamicMethodInfo, 1);
11779                 cfg->dynamic_info->code_mp = mono_code_manager_new_dynamic ();
11780                 mono_domain_lock (cfg->domain);
11781                 mono_dynamic_code_hash_insert (cfg->domain, cfg->method, cfg->dynamic_info);
11782                 mono_domain_unlock (cfg->domain);
11783
11784                 code = mono_code_manager_reserve (cfg->dynamic_info->code_mp, cfg->code_size);
11785         } else {
11786                 mono_domain_lock (cfg->domain);
11787                 code = mono_code_manager_reserve (cfg->domain->code_mp, cfg->code_size);
11788                 mono_domain_unlock (cfg->domain);
11789         }
11790
11791         memcpy (code, cfg->native_code, cfg->code_len);
11792         g_free (cfg->native_code);
11793         cfg->native_code = code;
11794         code = cfg->native_code + cfg->code_len;
11795   
11796         /* g_assert (((int)cfg->native_code & (MONO_ARCH_CODE_ALIGNMENT - 1)) == 0); */
11797         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
11798                 switch (patch_info->type) {
11799                 case MONO_PATCH_INFO_ABS: {
11800                         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (patch_info->data.target);
11801                         if (info) {
11802                                 //printf ("TEST %s %p\n", info->name, patch_info->data.target);
11803                                 if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && 
11804                                         strstr (cfg->method->name, info->name)) {
11805                                         /*
11806                                          * This is an icall wrapper, and this is a call to the
11807                                          * wrapped function.
11808                                          */
11809                                         if (cfg->compile_aot) {
11810                                                 patch_info->type = MONO_PATCH_INFO_JIT_ICALL_ADDR;
11811                                                 patch_info->data.name = info->name;
11812                                         }
11813                                 } else {
11814                                         /* for these array methods we currently register the same function pointer
11815                                          * since it's a vararg function. But this means that mono_find_jit_icall_by_addr ()
11816                                          * will return the incorrect one depending on the order they are registered.
11817                                          * See tests/test-arr.cs
11818                                          */
11819                                         if (strstr (info->name, "ves_array_new_va_") == NULL && strstr (info->name, "ves_array_element_address_") == NULL) {
11820                                                 patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
11821                                                 patch_info->data.name = info->name;
11822                                         }
11823                                 }
11824                         }
11825                         else {
11826                                 MonoVTable *vtable = mono_find_class_init_trampoline_by_addr (patch_info->data.target);
11827                                 if (vtable) {
11828                                         patch_info->type = MONO_PATCH_INFO_CLASS_INIT;
11829                                         patch_info->data.klass = vtable->klass;
11830                                 } else {
11831                                         MonoClass *klass = mono_find_delegate_trampoline_by_addr (patch_info->data.target);
11832                                         if (klass) {
11833                                                 patch_info->type = MONO_PATCH_INFO_DELEGATE_TRAMPOLINE;
11834                                                 patch_info->data.klass = klass;
11835                                         }
11836                                 }
11837                         }
11838                         break;
11839                 }
11840                 case MONO_PATCH_INFO_SWITCH: {
11841                         gpointer *table;
11842                         if (cfg->method->dynamic) {
11843                                 table = mono_code_manager_reserve (cfg->dynamic_info->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
11844                         } else {
11845                                 mono_domain_lock (cfg->domain);
11846                                 table = mono_code_manager_reserve (cfg->domain->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
11847                                 mono_domain_unlock (cfg->domain);
11848                         }
11849
11850                         if (!cfg->compile_aot)
11851                                 /* In the aot case, the patch already points to the correct location */
11852                                 patch_info->ip.i = patch_info->ip.label->inst_c0;
11853                         for (i = 0; i < patch_info->data.table->table_size; i++) {
11854                                 table [i] = GINT_TO_POINTER (patch_info->data.table->table [i]->native_offset);
11855                         }
11856                         patch_info->data.table->table = (MonoBasicBlock**)table;
11857                         break;
11858                 }
11859                 default:
11860                         /* do nothing */
11861                         break;
11862                 }
11863         }
11864
11865 #ifdef VALGRIND_JIT_REGISTER_MAP
11866 if (valgrind_register){
11867                 char* nm = mono_method_full_name (cfg->method, TRUE);
11868                 VALGRIND_JIT_REGISTER_MAP (nm, cfg->native_code, cfg->native_code + cfg->code_len);
11869                 g_free (nm);
11870         }
11871 #endif
11872  
11873         if (cfg->verbose_level > 0) {
11874                 char* nm = mono_method_full_name (cfg->method, TRUE);
11875                 g_print ("Method %s emitted at %p to %p (code length %d) [%s]\n", 
11876                                  nm, 
11877                                  cfg->native_code, cfg->native_code + cfg->code_len, cfg->code_len, cfg->domain->friendly_name);
11878                 g_free (nm);
11879         }
11880
11881         {
11882                 gboolean is_generic = FALSE;
11883
11884                 if (cfg->method->is_inflated || mono_method_get_generic_container (cfg->method) ||
11885                                 cfg->method->klass->generic_container || cfg->method->klass->generic_class) {
11886                         is_generic = TRUE;
11887                 }
11888
11889                 if (cfg->generic_sharing_context)
11890                         g_assert (is_generic);
11891         }
11892
11893 #ifdef MONO_ARCH_HAVE_SAVE_UNWIND_INFO
11894         mono_arch_save_unwind_info (cfg);
11895 #endif
11896         
11897         mono_arch_patch_code (cfg->method, cfg->domain, cfg->native_code, cfg->patch_info, cfg->run_cctors);
11898
11899         if (cfg->method->dynamic) {
11900                 mono_code_manager_commit (cfg->dynamic_info->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
11901         } else {
11902                 mono_domain_lock (cfg->domain);
11903                 mono_code_manager_commit (cfg->domain->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
11904                 mono_domain_unlock (cfg->domain);
11905         }
11906         
11907         mono_arch_flush_icache (cfg->native_code, cfg->code_len);
11908
11909         mono_debug_close_method (cfg);
11910 }
11911
11912
11913
11914 static void
11915 remove_critical_edges (MonoCompile *cfg) {
11916         MonoBasicBlock *bb;
11917         MonoBasicBlock *previous_bb;
11918         
11919         if (cfg->verbose_level > 3) {
11920                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11921                         MonoInst *last_ins;
11922                         int i;
11923                         printf ("remove_critical_edges %s, BEFORE BB%d (in:", mono_method_full_name (cfg->method, TRUE), bb->block_num);
11924                         for (i = 0; i < bb->in_count; i++) {
11925                                 printf (" %d", bb->in_bb [i]->block_num);
11926                         }
11927                         printf (") (out:");
11928                         for (i = 0; i < bb->out_count; i++) {
11929                                 printf (" %d", bb->out_bb [i]->block_num);
11930                         }
11931                         printf (")");
11932                         last_ins = mono_inst_list_last (&bb->ins_list);
11933                         if (last_ins) {
11934                                 printf (" ");
11935                                 mono_print_tree (last_ins);
11936                         }
11937                         printf ("\n");
11938                 }
11939         }
11940         
11941         for (previous_bb = cfg->bb_entry, bb = previous_bb->next_bb; bb != NULL; previous_bb = previous_bb->next_bb, bb = bb->next_bb) {
11942                 if (bb->in_count > 1) {
11943                         int in_bb_index;
11944                         for (in_bb_index = 0; in_bb_index < bb->in_count; in_bb_index++) {
11945                                 MonoBasicBlock *in_bb = bb->in_bb [in_bb_index];
11946                                 if (in_bb->out_count > 1) {
11947                                         MonoBasicBlock *new_bb = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock));
11948                                         MONO_INST_LIST_INIT (&new_bb->ins_list);
11949                                         new_bb->block_num = cfg->num_bblocks++;
11950 //                                      new_bb->real_offset = bb->real_offset;
11951                                         new_bb->region = bb->region;
11952                                         
11953                                         /* Do not alter the CFG while altering the BB list */
11954                                         if (previous_bb->region == bb->region) {
11955                                                 if (previous_bb != cfg->bb_entry) {
11956                                                         MonoInst *last_ins;
11957                                                         /* If previous_bb "followed through" to bb, */
11958                                                         /* keep it linked with a OP_BR */
11959                                                         last_ins = mono_inst_list_last (&previous_bb->ins_list);
11960                                                         if ((last_ins == NULL) ||
11961                                                                         ((last_ins->opcode != OP_BR) &&
11962                                                                         (!(MONO_IS_COND_BRANCH_OP (last_ins))) &&
11963                                                                         (last_ins->opcode != OP_SWITCH))) {
11964                                                                 int i;
11965                                                                 /* Make sure previous_bb really falls through bb */
11966                                                                 for (i = 0; i < previous_bb->out_count; i++) {
11967                                                                         if (previous_bb->out_bb [i] == bb) {
11968                                                                                 MonoInst *jump;
11969                                                                                 MONO_INST_NEW (cfg, jump, OP_BR);
11970                                                                                 MONO_ADD_INS (previous_bb, jump);
11971                                                                                 jump->cil_code = previous_bb->cil_code;
11972                                                                                 jump->inst_target_bb = bb;
11973                                                                                 break;
11974                                                                         }
11975                                                                 }
11976                                                         }
11977                                                 } else {
11978                                                         /* We cannot add any inst to the entry BB, so we must */
11979                                                         /* put a new BB in the middle to hold the OP_BR */
11980                                                         MonoInst *jump;
11981                                                         MonoBasicBlock *new_bb_after_entry = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock));
11982                                                         MONO_INST_LIST_INIT (&new_bb_after_entry->ins_list);
11983                                                         new_bb_after_entry->block_num = cfg->num_bblocks++;
11984 //                                                      new_bb_after_entry->real_offset = bb->real_offset;
11985                                                         new_bb_after_entry->region = bb->region;
11986                                                         
11987                                                         MONO_INST_NEW (cfg, jump, OP_BR);
11988                                                         MONO_ADD_INS (new_bb_after_entry, jump);
11989                                                         jump->cil_code = bb->cil_code;
11990                                                         jump->inst_target_bb = bb;
11991                                                         
11992                                                         previous_bb->next_bb = new_bb_after_entry;
11993                                                         previous_bb = new_bb_after_entry;
11994                                                         
11995                                                         if (cfg->verbose_level > 2) {
11996                                                                 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);
11997                                                         }
11998                                                 }
11999                                         }
12000                                         
12001                                         /* Insert new_bb in the BB list */
12002                                         previous_bb->next_bb = new_bb;
12003                                         new_bb->next_bb = bb;
12004                                         previous_bb = new_bb;
12005                                         
12006                                         /* Setup in_bb and out_bb */
12007                                         new_bb->in_bb = mono_mempool_alloc ((cfg)->mempool, sizeof (MonoBasicBlock*));
12008                                         new_bb->in_bb [0] = in_bb;
12009                                         new_bb->in_count = 1;
12010                                         new_bb->out_bb = mono_mempool_alloc ((cfg)->mempool, sizeof (MonoBasicBlock*));
12011                                         new_bb->out_bb [0] = bb;
12012                                         new_bb->out_count = 1;
12013                                         
12014                                         /* Relink in_bb and bb to (from) new_bb */
12015                                         replace_out_block (in_bb, bb, new_bb);
12016                                         replace_out_block_in_code (in_bb, bb, new_bb);
12017                                         replace_in_block (bb, in_bb, new_bb);
12018                                         
12019                                         if (cfg->verbose_level > 2) {
12020                                                 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);
12021                                         }
12022                                 }
12023                         }
12024                 }
12025         }
12026         
12027         if (cfg->verbose_level > 3) {
12028                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
12029                         MonoInst *last_ins;
12030                         int i;
12031                         printf ("remove_critical_edges %s, AFTER BB%d (in:", mono_method_full_name (cfg->method, TRUE), bb->block_num);
12032                         for (i = 0; i < bb->in_count; i++) {
12033                                 printf (" %d", bb->in_bb [i]->block_num);
12034                         }
12035                         printf (") (out:");
12036                         for (i = 0; i < bb->out_count; i++) {
12037                                 printf (" %d", bb->out_bb [i]->block_num);
12038                         }
12039                         printf (")");
12040                         last_ins = mono_inst_list_last (&bb->ins_list);
12041                         if (last_ins) {
12042                                 printf (" ");
12043                                 mono_print_tree (last_ins);
12044                         }
12045                         printf ("\n");
12046                 }
12047         }
12048 }
12049
12050 static MonoGenericInst*
12051 get_object_generic_inst (int type_argc)
12052 {
12053         MonoType **type_argv;
12054         int i;
12055
12056         type_argv = alloca (sizeof (MonoType*) * type_argc);
12057
12058         for (i = 0; i < type_argc; ++i)
12059                 type_argv [i] = &mono_defaults.object_class->byval_arg;
12060
12061         return mono_metadata_get_generic_inst (type_argc, type_argv);
12062 }
12063
12064 /*
12065  * mini_method_compile:
12066  * @method: the method to compile
12067  * @opts: the optimization flags to use
12068  * @domain: the domain where the method will be compiled in
12069  * @run_cctors: whether we should run type ctors if possible
12070  * @compile_aot: whether this is an AOT compilation
12071  * @parts: debug flag
12072  *
12073  * Returns: a MonoCompile* pointer. Caller must check the exception_type
12074  * field in the returned struct to see if compilation succeded.
12075  */
12076 MonoCompile*
12077 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gboolean run_cctors, gboolean compile_aot, int parts)
12078 {
12079         MonoMethodHeader *header;
12080         guint8 *ip;
12081         MonoCompile *cfg;
12082         MonoJitInfo *jinfo;
12083         int dfn = 0, i, code_size_ratio;
12084         gboolean deadce_has_run = FALSE;
12085         gboolean try_generic_shared;
12086         MonoMethod *method_to_compile, *method_to_register;
12087         int generic_info_size;
12088
12089         mono_jit_stats.methods_compiled++;
12090         if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)
12091                 mono_profiler_method_jit (method);
12092         if (MONO_PROBE_METHOD_COMPILE_BEGIN_ENABLED ())
12093                 MONO_PROBE_METHOD_COMPILE_BEGIN (method);
12094  
12095         if (compile_aot)
12096                 /* We are passed the original generic method definition */
12097                 try_generic_shared = mono_class_generic_sharing_enabled (method->klass) &&
12098                         (opts & MONO_OPT_GSHARED) && (method->is_generic || method->klass->generic_container);
12099         else
12100                 try_generic_shared = mono_class_generic_sharing_enabled (method->klass) &&
12101                         (opts & MONO_OPT_GSHARED) && mono_method_is_generic_sharable_impl (method, FALSE);
12102
12103         if (opts & MONO_OPT_GSHARED) {
12104                 if (try_generic_shared)
12105                         mono_stats.generics_sharable_methods++;
12106                 else if (mono_method_is_generic_impl (method))
12107                         mono_stats.generics_unsharable_methods++;
12108         }
12109
12110  restart_compile:
12111         if (try_generic_shared) {
12112                 MonoMethod *declaring_method;
12113                 MonoGenericContext *shared_context;
12114
12115                 if (compile_aot) {
12116                         declaring_method = method;
12117                 } else {
12118                         declaring_method = mono_method_get_declaring_generic_method (method);
12119                         if (method->klass->generic_class)
12120                                 g_assert (method->klass->generic_class->container_class == declaring_method->klass);
12121                         else
12122                                 g_assert (method->klass == declaring_method->klass);
12123                 }
12124
12125                 if (declaring_method->is_generic)
12126                         shared_context = &(mono_method_get_generic_container (declaring_method)->context);
12127                 else
12128                         shared_context = &declaring_method->klass->generic_container->context;
12129
12130                 method_to_compile = mono_class_inflate_generic_method (declaring_method, shared_context);
12131                 g_assert (method_to_compile);
12132         } else {
12133                 method_to_compile = method;
12134         }
12135
12136         cfg = g_new0 (MonoCompile, 1);
12137         cfg->method = method_to_compile;
12138         cfg->mempool = mono_mempool_new ();
12139         cfg->opt = opts;
12140         cfg->prof_options = mono_profiler_get_events ();
12141         cfg->run_cctors = run_cctors;
12142         cfg->domain = domain;
12143         cfg->verbose_level = mini_verbose;
12144         cfg->compile_aot = compile_aot;
12145         cfg->skip_visibility = method->skip_visibility;
12146         if (try_generic_shared)
12147                 cfg->generic_sharing_context = (MonoGenericSharingContext*)&cfg->generic_sharing_context;
12148         cfg->token_info_hash = g_hash_table_new (NULL, NULL);
12149
12150         /* The debugger has no liveness information, so avoid sharing registers/stack slots */
12151         if (mono_debug_using_mono_debugger () || debug_options.mdb_optimizations) {
12152                 cfg->disable_reuse_registers = TRUE;
12153                 cfg->disable_reuse_stack_slots = TRUE;
12154                 /* 
12155                  * This decreases the change the debugger will read registers/stack slots which are
12156                  * not yet initialized.
12157                  */
12158                 cfg->disable_initlocals_opt = TRUE;
12159
12160                 /* Temporarily disable this when running in the debugger until we have support
12161                  * for this in the debugger. */
12162                 cfg->disable_omit_fp = TRUE;
12163
12164                 // cfg->opt |= MONO_OPT_SHARED;
12165                 cfg->opt &= ~MONO_OPT_INLINE;
12166                 cfg->opt &= ~MONO_OPT_COPYPROP;
12167                 cfg->opt &= ~MONO_OPT_CONSPROP;
12168         }
12169
12170         header = mono_method_get_header (method_to_compile);
12171         if (!header) {
12172                 cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
12173                 cfg->exception_message = g_strdup_printf ("Missing or incorrect header for method %s", cfg->method->name);
12174                 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
12175                         MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
12176                 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
12177                         mono_profiler_method_end_jit (method, NULL, MONO_PROFILE_FAILED);
12178                 return cfg;
12179         }
12180
12181         ip = (guint8 *)header->code;
12182
12183         if (cfg->verbose_level > 2) {
12184                 if (cfg->generic_sharing_context)
12185                         g_print ("converting shared method %s\n", mono_method_full_name (method, TRUE));
12186                 else
12187                         g_print ("converting method %s\n", mono_method_full_name (method, TRUE));
12188         }
12189
12190         /*
12191          * create MonoInst* which represents arguments and local variables
12192          */
12193         mono_compile_create_vars (cfg);
12194
12195         if ((i = mono_method_to_ir (cfg, method_to_compile, NULL, NULL, cfg->locals_start, NULL, NULL, NULL, 0, FALSE)) < 0) {
12196                 if (try_generic_shared && cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
12197                         if (compile_aot) {
12198                                 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
12199                                         MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
12200                                 return cfg;
12201                         }
12202                         mono_destroy_compile (cfg);
12203                         try_generic_shared = FALSE;
12204                         goto restart_compile;
12205                 }
12206                 g_assert (cfg->exception_type != MONO_EXCEPTION_GENERIC_SHARING_FAILED);
12207
12208                 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
12209                         MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
12210                 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
12211                         mono_profiler_method_end_jit (method, NULL, MONO_PROFILE_FAILED);
12212                 /* cfg contains the details of the failure, so let the caller cleanup */
12213                 return cfg;
12214         }
12215
12216         mono_jit_stats.basic_blocks += cfg->num_bblocks;
12217         mono_jit_stats.max_basic_blocks = MAX (cfg->num_bblocks, mono_jit_stats.max_basic_blocks);
12218
12219         if ((cfg->num_varinfo > 2000) && !cfg->compile_aot) {
12220                 /* 
12221                  * we disable some optimizations if there are too many variables
12222                  * because JIT time may become too expensive. The actual number needs 
12223                  * to be tweaked and eventually the non-linear algorithms should be fixed.
12224                  */
12225                 cfg->opt &= ~ (MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP);
12226                 cfg->disable_ssa = TRUE;
12227         }
12228
12229         /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/
12230
12231         if (cfg->opt & MONO_OPT_BRANCH)
12232                 optimize_branches (cfg);
12233
12234         if (cfg->opt & MONO_OPT_SSAPRE) {
12235                 remove_critical_edges (cfg);
12236         }
12237
12238         /* Depth-first ordering on basic blocks */
12239         cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
12240
12241         df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
12242         if (cfg->num_bblocks != dfn + 1) {
12243                 MonoBasicBlock *bb;
12244
12245                 cfg->num_bblocks = dfn + 1;
12246
12247                 if (!header->clauses) {
12248                         /* remove unreachable code, because the code in them may be 
12249                          * inconsistent  (access to dead variables for example) */
12250                         for (bb = cfg->bb_entry; bb;) {
12251                                 MonoBasicBlock *bbn = bb->next_bb;
12252
12253                                 if (bbn && bbn->region == -1 && !bbn->dfn) {
12254                                         if (cfg->verbose_level > 1)
12255                                                 g_print ("found unreachable code in BB%d\n", bbn->block_num);
12256                                         bb->next_bb = bbn->next_bb;
12257                                         nullify_basic_block (bbn);                      
12258                                 } else {
12259                                         bb = bb->next_bb;
12260                                 }
12261                         }
12262                 }
12263         }
12264
12265         if (cfg->opt & MONO_OPT_LOOP) {
12266                 mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM);
12267                 mono_compute_natural_loops (cfg);
12268         }
12269
12270         /* after method_to_ir */
12271         if (parts == 1) {
12272                 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
12273                         MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
12274                 return cfg;
12275         }
12276
12277 //#define DEBUGSSA "logic_run"
12278 #define DEBUGSSA_CLASS "Tests"
12279 #ifdef DEBUGSSA
12280
12281         if (!header->num_clauses && !cfg->disable_ssa) {
12282                 mono_local_cprop (cfg);
12283 #ifndef DISABLE_SSA
12284                 mono_ssa_compute (cfg);
12285 #endif
12286         }
12287 #else 
12288
12289         /* fixme: add all optimizations which requires SSA */
12290         if (cfg->opt & (MONO_OPT_SSA | MONO_OPT_ABCREM | MONO_OPT_SSAPRE)) {
12291                 if (!(cfg->comp_done & MONO_COMP_SSA) && !header->num_clauses && !cfg->disable_ssa) {
12292                         mono_local_cprop (cfg);
12293 #ifndef DISABLE_SSA
12294                         mono_ssa_compute (cfg);
12295 #endif
12296
12297                         if (cfg->verbose_level >= 2) {
12298                                 print_dfn (cfg);
12299                         }
12300                 }
12301         }
12302 #endif
12303
12304         /* after SSA translation */
12305         if (parts == 2) {
12306                 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
12307                         MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
12308                 return cfg;
12309         }
12310
12311         if ((cfg->opt & MONO_OPT_CONSPROP) || (cfg->opt & MONO_OPT_COPYPROP)) {
12312                 if (cfg->comp_done & MONO_COMP_SSA) {
12313 #ifndef DISABLE_SSA
12314                         mono_ssa_cprop (cfg);
12315 #endif
12316                 } else {
12317                         mono_local_cprop (cfg);
12318                 }
12319         }
12320
12321 #ifndef DISABLE_SSA
12322         if (cfg->comp_done & MONO_COMP_SSA) {                   
12323                 //mono_ssa_deadce (cfg);
12324
12325                 //mono_ssa_strength_reduction (cfg);
12326
12327                 if (cfg->opt & MONO_OPT_SSAPRE) {
12328                         mono_perform_ssapre (cfg);
12329                         //mono_local_cprop (cfg);
12330                 }
12331                 
12332                 if (cfg->opt & MONO_OPT_DEADCE) {
12333                         mono_ssa_deadce (cfg);
12334                         deadce_has_run = TRUE;
12335                 }
12336                 
12337                 if ((cfg->flags & MONO_CFG_HAS_LDELEMA) && (cfg->opt & MONO_OPT_ABCREM))
12338                         mono_perform_abc_removal (cfg);
12339                 
12340                 mono_ssa_remove (cfg);
12341
12342                 if (cfg->opt & MONO_OPT_BRANCH)
12343                         optimize_branches (cfg);
12344         }
12345 #endif
12346
12347         /* after SSA removal */
12348         if (parts == 3) {
12349                 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
12350                         MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
12351                 return cfg;
12352         }
12353
12354         if (cfg->verbose_level > 4) {
12355                 printf ("BEFORE DECOMPSE START\n");
12356                 mono_print_code (cfg);
12357                 printf ("BEFORE DECOMPSE END\n");
12358         }
12359         
12360         decompose_pass (cfg);
12361
12362         if (cfg->got_var) {
12363                 GList *regs;
12364
12365                 g_assert (cfg->got_var_allocated);
12366
12367                 /* 
12368                  * Allways allocate the GOT var to a register, because keeping it
12369                  * in memory will increase the number of live temporaries in some
12370                  * code created by inssel.brg, leading to the well known spills+
12371                  * branches problem. Testcase: mcs crash in 
12372                  * System.MonoCustomAttrs:GetCustomAttributes.
12373                  */
12374                 regs = mono_arch_get_global_int_regs (cfg);
12375                 g_assert (regs);
12376                 cfg->got_var->opcode = OP_REGVAR;
12377                 cfg->got_var->dreg = GPOINTER_TO_INT (regs->data);
12378                 cfg->used_int_regs |= 1LL << cfg->got_var->dreg;
12379                 
12380                 g_list_free (regs);
12381         }
12382
12383         /* todo: remove code when we have verified that the liveness for try/catch blocks
12384          * works perfectly 
12385          */
12386         /* 
12387          * Currently, this can't be commented out since exception blocks are not
12388          * processed during liveness analysis.
12389          */
12390         mono_liveness_handle_exception_clauses (cfg);
12391
12392         if (cfg->opt & MONO_OPT_LINEARS) {
12393                 GList *vars, *regs;
12394                 
12395                 /* For now, compute aliasing info only if needed for deadce... */
12396                 if ((cfg->opt & MONO_OPT_DEADCE) && (! deadce_has_run) && (header->num_clauses == 0)) {
12397                         cfg->aliasing_info = mono_build_aliasing_information (cfg);
12398                 }
12399
12400                 /* fixme: maybe we can avoid to compute livenesss here if already computed ? */
12401                 cfg->comp_done &= ~MONO_COMP_LIVENESS;
12402                 if (!(cfg->comp_done & MONO_COMP_LIVENESS))
12403                         mono_analyze_liveness (cfg);
12404
12405                 if (cfg->aliasing_info != NULL) {
12406                         mono_aliasing_deadce (cfg->aliasing_info);
12407                         deadce_has_run = TRUE;
12408                 }
12409                 
12410                 if ((vars = mono_arch_get_allocatable_int_vars (cfg))) {
12411                         regs = mono_arch_get_global_int_regs (cfg);
12412                         if (cfg->got_var)
12413                                 regs = g_list_delete_link (regs, regs);
12414                         mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs);
12415                 }
12416                 
12417                 if (cfg->aliasing_info != NULL) {
12418                         mono_destroy_aliasing_information (cfg->aliasing_info);
12419                         cfg->aliasing_info = NULL;
12420                 }
12421         }
12422
12423         //mono_print_code (cfg);
12424
12425     //print_dfn (cfg);
12426         
12427         /* variables are allocated after decompose, since decompose could create temps */
12428         mono_arch_allocate_vars (cfg);
12429
12430         if (cfg->opt & MONO_OPT_CFOLD)
12431                 mono_constant_fold (cfg);
12432
12433         mini_select_instructions (cfg);
12434
12435         mono_codegen (cfg);
12436         if (cfg->verbose_level >= 2) {
12437                 char *id =  mono_method_full_name (cfg->method, FALSE);
12438                 mono_disassemble_code (cfg, cfg->native_code, cfg->code_len, id + 3);
12439                 g_free (id);
12440         }
12441
12442         if (cfg->generic_sharing_context)
12443                 generic_info_size = sizeof (MonoGenericJitInfo);
12444         else
12445                 generic_info_size = 0;
12446
12447         if (cfg->method->dynamic) {
12448                 jinfo = g_malloc0 (sizeof (MonoJitInfo) + (header->num_clauses * sizeof (MonoJitExceptionInfo)) +
12449                                 generic_info_size);
12450         } else {
12451                 /* we access cfg->domain->mp */
12452                 mono_domain_lock (cfg->domain);
12453                 jinfo = mono_mempool_alloc0 (cfg->domain->mp, sizeof (MonoJitInfo) +
12454                                 (header->num_clauses * sizeof (MonoJitExceptionInfo)) +
12455                                 generic_info_size);
12456                 mono_domain_unlock (cfg->domain);
12457         }
12458
12459         if (cfg->generic_sharing_context) {
12460                 MonoGenericContext object_context;
12461
12462                 g_assert (!method_to_compile->klass->generic_class);
12463                 if (method_to_compile->klass->generic_container) {
12464                         int type_argc = method_to_compile->klass->generic_container->type_argc;
12465
12466                         object_context.class_inst = get_object_generic_inst (type_argc);
12467                 } else {
12468                         object_context.class_inst = NULL;
12469                 }
12470
12471                 if (mini_method_get_context (method_to_compile)->method_inst) {
12472                         int type_argc = mini_method_get_context (method_to_compile)->method_inst->type_argc;
12473
12474                         object_context.method_inst = get_object_generic_inst (type_argc);
12475                 } else {
12476                         object_context.method_inst = NULL;
12477                 }
12478
12479                 g_assert (object_context.class_inst || object_context.method_inst);
12480
12481                 method_to_register = mono_class_inflate_generic_method (method_to_compile, &object_context);
12482         } else {
12483                 g_assert (method == method_to_compile);
12484                 method_to_register = method;
12485         }
12486
12487         jinfo->method = method_to_register;
12488         jinfo->code_start = cfg->native_code;
12489         jinfo->code_size = cfg->code_len;
12490         jinfo->used_regs = cfg->used_int_regs;
12491         jinfo->domain_neutral = (cfg->opt & MONO_OPT_SHARED) != 0;
12492         jinfo->cas_inited = FALSE; /* initialization delayed at the first stalk walk using this method */
12493         jinfo->num_clauses = header->num_clauses;
12494
12495         if (cfg->generic_sharing_context) {
12496                 MonoInst *inst;
12497                 MonoGenericJitInfo *gi;
12498
12499                 jinfo->has_generic_jit_info = 1;
12500
12501                 gi = mono_jit_info_get_generic_jit_info (jinfo);
12502                 g_assert (gi);
12503
12504                 gi->generic_sharing_context = cfg->generic_sharing_context;
12505
12506                 /*
12507                  * Non-generic static methods only get a "this" info
12508                  * if they use the rgctx variable (which they are
12509                  * forced to if they have any open catch clauses).
12510                  */
12511                 if (cfg->rgctx_var ||
12512                                 (!(method_to_compile->flags & METHOD_ATTRIBUTE_STATIC) &&
12513                                 !mini_method_get_context (method_to_compile)->method_inst)) {
12514                         gi->has_this = 1;
12515
12516                         if ((method_to_compile->flags & METHOD_ATTRIBUTE_STATIC) ||
12517                                         mini_method_get_context (method_to_compile)->method_inst) {
12518                                 inst = cfg->rgctx_var;
12519                                 g_assert (inst->opcode == OP_REGOFFSET);
12520                         } else {
12521                                 inst = cfg->args [0];
12522                         }
12523
12524                         if (inst->opcode == OP_REGVAR) {
12525                                 gi->this_in_reg = 1;
12526                                 gi->this_reg = inst->dreg;
12527
12528                                 //g_print ("this in reg %d\n", inst->dreg);
12529                         } else {
12530                                 g_assert (inst->opcode == OP_REGOFFSET);
12531 #ifdef __i386__
12532                                 g_assert (inst->inst_basereg == X86_EBP);
12533 #elif defined(__x86_64__)
12534                                 g_assert (inst->inst_basereg == X86_EBP || inst->inst_basereg == X86_ESP);
12535 #endif
12536                                 g_assert (inst->inst_offset >= G_MININT32 && inst->inst_offset <= G_MAXINT32);
12537
12538                                 gi->this_in_reg = 0;
12539                                 gi->this_reg = inst->inst_basereg;
12540                                 gi->this_offset = inst->inst_offset;
12541
12542                                 //g_print ("this at offset %d from reg %d\n", gi->this_offset, gi->this_reg);
12543                         }
12544                 } else {
12545                         gi->has_this = 0;
12546                 }
12547         }
12548
12549         if (header->num_clauses) {
12550                 int i;
12551
12552                 for (i = 0; i < header->num_clauses; i++) {
12553                         MonoExceptionClause *ec = &header->clauses [i];
12554                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
12555                         MonoBasicBlock *tblock;
12556                         MonoInst *exvar;
12557
12558                         ei->flags = ec->flags;
12559
12560                         exvar = mono_find_exvar_for_offset (cfg, ec->handler_offset);
12561                         ei->exvar_offset = exvar ? exvar->inst_offset : 0;
12562
12563                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
12564                                 tblock = cfg->cil_offset_to_bb [ec->data.filter_offset];
12565                                 g_assert (tblock);
12566                                 ei->data.filter = cfg->native_code + tblock->native_offset;
12567                         } else {
12568                                 ei->data.catch_class = ec->data.catch_class;
12569                         }
12570
12571                         tblock = cfg->cil_offset_to_bb [ec->try_offset];
12572                         g_assert (tblock);
12573                         ei->try_start = cfg->native_code + tblock->native_offset;
12574                         g_assert (tblock->native_offset);
12575                         tblock = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
12576                         g_assert (tblock);
12577                         ei->try_end = cfg->native_code + tblock->native_offset;
12578                         g_assert (tblock->native_offset);
12579                         tblock = cfg->cil_offset_to_bb [ec->handler_offset];
12580                         g_assert (tblock);
12581                         ei->handler_start = cfg->native_code + tblock->native_offset;
12582                 }
12583         }
12584
12585         cfg->jit_info = jinfo;
12586 #if defined(__arm__)
12587         mono_arch_fixup_jinfo (cfg);
12588 #endif
12589
12590         mono_domain_lock (cfg->domain);
12591         mono_jit_info_table_add (cfg->domain, jinfo);
12592
12593         if (cfg->method->dynamic)
12594                 mono_dynamic_code_hash_lookup (cfg->domain, cfg->method)->ji = jinfo;
12595         mono_domain_unlock (cfg->domain);
12596
12597         /* collect statistics */
12598         mono_jit_stats.allocated_code_size += cfg->code_len;
12599         code_size_ratio = cfg->code_len;
12600         if (code_size_ratio > mono_jit_stats.biggest_method_size && mono_jit_stats.enabled) {
12601                 mono_jit_stats.biggest_method_size = code_size_ratio;
12602                 g_free (mono_jit_stats.biggest_method);
12603                 mono_jit_stats.biggest_method = g_strdup_printf ("%s::%s)", method->klass->name, method->name);
12604         }
12605         code_size_ratio = (code_size_ratio * 100) / mono_method_get_header (method)->code_size;
12606         if (code_size_ratio > mono_jit_stats.max_code_size_ratio && mono_jit_stats.enabled) {
12607                 mono_jit_stats.max_code_size_ratio = code_size_ratio;
12608                 g_free (mono_jit_stats.max_ratio_method);
12609                 mono_jit_stats.max_ratio_method = g_strdup_printf ("%s::%s)", method->klass->name, method->name);
12610         }
12611         mono_jit_stats.native_code_size += cfg->code_len;
12612
12613         if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
12614                 MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
12615         if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
12616                 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
12617
12618         return cfg;
12619 }
12620
12621 static MonoJitInfo*
12622 lookup_generic_method (MonoDomain *domain, MonoMethod *method)
12623 {
12624         MonoMethod *open_method;
12625
12626         if (!mono_method_is_generic_sharable_impl (method, FALSE))
12627                 return NULL;
12628
12629         open_method = mono_method_get_declaring_generic_method (method);
12630
12631         return mono_domain_lookup_shared_generic (domain, open_method);
12632 }
12633
12634 /*
12635  * LOCKING: Assumes domain->jit_code_hash_lock is held.
12636  */
12637 static MonoJitInfo*
12638 lookup_method_inner (MonoDomain *domain, MonoMethod *method)
12639 {
12640         MonoJitInfo *ji = mono_internal_hash_table_lookup (&domain->jit_code_hash, method);
12641
12642         if (ji)
12643                 return ji;
12644
12645         return lookup_generic_method (domain, method);
12646 }
12647
12648 static MonoJitInfo*
12649 lookup_method (MonoDomain *domain, MonoMethod *method)
12650 {
12651         MonoJitInfo *info;
12652
12653         mono_domain_jit_code_hash_lock (domain);
12654         info = lookup_method_inner (domain, method);
12655         mono_domain_jit_code_hash_unlock (domain);
12656
12657         return info;
12658 }
12659
12660 static gpointer
12661 mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain, int opt)
12662 {
12663         MonoCompile *cfg;
12664         gpointer code = NULL;
12665         MonoJitInfo *info;
12666         MonoVTable *vtable;
12667
12668 #ifdef MONO_USE_AOT_COMPILER
12669         if ((opt & MONO_OPT_AOT) && !(mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)) {
12670                 MonoDomain *domain = mono_domain_get ();
12671
12672                 mono_class_init (method->klass);
12673
12674                 mono_domain_lock (domain);
12675                 if ((code = mono_aot_get_method (domain, method))) {
12676                         mono_domain_unlock (domain);
12677                         vtable = mono_class_vtable (domain, method->klass);
12678                         g_assert (vtable);
12679                         mono_runtime_class_init (vtable);
12680                         return code;
12681                 }
12682
12683                 mono_domain_unlock (domain);
12684         }
12685 #endif
12686
12687         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
12688             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
12689                 MonoMethod *nm;
12690                 MonoMethodPInvoke* piinfo = (MonoMethodPInvoke *) method;
12691
12692                 if (!piinfo->addr) {
12693                         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
12694                                 piinfo->addr = mono_lookup_internal_call (method);
12695                         else if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)
12696 #ifdef PLATFORM_WIN32
12697                                 g_warning ("Method '%s' in assembly '%s' contains native code that cannot be executed by Mono in modules loaded from byte arrays. The assembly was probably created using C++/CLI.\n", mono_method_full_name (method, TRUE), method->klass->image->name);
12698 #else
12699                                 g_warning ("Method '%s' in assembly '%s' contains native code that cannot be executed by Mono on this platform. The assembly was probably created using C++/CLI.\n", mono_method_full_name (method, TRUE), method->klass->image->name);
12700 #endif
12701                         else
12702                                 mono_lookup_pinvoke_call (method, NULL, NULL);
12703                 }
12704                         nm = mono_marshal_get_native_wrapper (method, check_for_pending_exc);
12705                         return mono_get_addr_from_ftnptr (mono_compile_method (nm));
12706
12707                         //if (mono_debug_format != MONO_DEBUG_FORMAT_NONE) 
12708                         //mono_debug_add_wrapper (method, nm);
12709         } else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
12710                 const char *name = method->name;
12711                 MonoMethod *nm;
12712
12713                 if (method->klass->parent == mono_defaults.multicastdelegate_class) {
12714                         if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
12715                                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name ("mono_delegate_ctor");
12716                                 g_assert (mi);
12717                                 return mono_get_addr_from_ftnptr ((gpointer)mono_icall_get_wrapper (mi));
12718                         } else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
12719 #ifdef MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE
12720                                 return mono_create_delegate_trampoline (method->klass);
12721 #else
12722                                 nm = mono_marshal_get_delegate_invoke (method, NULL);
12723                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
12724 #endif
12725                         } else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
12726                                 nm = mono_marshal_get_delegate_begin_invoke (method);
12727                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
12728                         } else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
12729                                 nm = mono_marshal_get_delegate_end_invoke (method);
12730                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
12731                         }
12732                 }
12733                 return NULL;
12734         }
12735
12736         if (mono_aot_only)
12737                 g_error ("Attempting to JIT compile method '%s' while running with --aot-only.\n", mono_method_full_name (method, TRUE));
12738
12739         cfg = mini_method_compile (method, opt, target_domain, TRUE, FALSE, 0);
12740
12741         switch (cfg->exception_type) {
12742         case MONO_EXCEPTION_NONE: break;
12743         case MONO_EXCEPTION_TYPE_LOAD:
12744         case MONO_EXCEPTION_MISSING_FIELD:
12745         case MONO_EXCEPTION_MISSING_METHOD:
12746         case MONO_EXCEPTION_FILE_NOT_FOUND: {
12747                 /* Throw a type load exception if needed */
12748                 MonoLoaderError *error = mono_loader_get_last_error ();
12749                 MonoException *ex;
12750
12751                 if (error) {
12752                         ex = mono_loader_error_prepare_exception (error);
12753                 } else {
12754                         if (cfg->exception_ptr) {
12755                                 ex = mono_class_get_exception_for_failure (cfg->exception_ptr);
12756                         } else {
12757                                 if (cfg->exception_type == MONO_EXCEPTION_MISSING_FIELD)
12758                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingFieldException", cfg->exception_message);
12759                                 else if (cfg->exception_type == MONO_EXCEPTION_MISSING_METHOD)
12760                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingMethodException", cfg->exception_message);
12761                                 else if (cfg->exception_type == MONO_EXCEPTION_TYPE_LOAD)
12762                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "TypeLoadException", cfg->exception_message);
12763                                 else if (cfg->exception_type == MONO_EXCEPTION_FILE_NOT_FOUND)
12764                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "FileNotFoundException", cfg->exception_message);
12765                                 else
12766                                         g_assert_not_reached ();
12767                         }
12768                 }
12769                 mono_destroy_compile (cfg);
12770                 mono_raise_exception (ex);
12771                 break;
12772         }
12773         case MONO_EXCEPTION_INVALID_PROGRAM: {
12774                 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "InvalidProgramException", cfg->exception_message);
12775                 mono_destroy_compile (cfg);
12776                 mono_raise_exception (ex);
12777                 break;
12778         }
12779         case MONO_EXCEPTION_UNVERIFIABLE_IL: {
12780                 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System.Security", "VerificationException", cfg->exception_message);
12781                 mono_destroy_compile (cfg);
12782                 mono_raise_exception (ex);
12783                 break;
12784         }
12785         case MONO_EXCEPTION_METHOD_ACCESS: {
12786                 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MethodAccessException", cfg->exception_message);
12787                 mono_destroy_compile (cfg);
12788                 mono_raise_exception (ex);
12789                 break;
12790         }
12791         case MONO_EXCEPTION_FIELD_ACCESS: {
12792                 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "FieldAccessException", cfg->exception_message);
12793                 mono_destroy_compile (cfg);
12794                 mono_raise_exception (ex);
12795                 break;
12796         }
12797         /* this can only be set if the security manager is active */
12798         case MONO_EXCEPTION_SECURITY_LINKDEMAND: {
12799                 MonoSecurityManager* secman = mono_security_manager_get_methods ();
12800                 MonoObject *exc = NULL;
12801                 gpointer args [2];
12802
12803                 args [0] = &cfg->exception_data;
12804                 args [1] = &method;
12805                 mono_runtime_invoke (secman->linkdemandsecurityexception, NULL, args, &exc);
12806
12807                 mono_destroy_compile (cfg);
12808                 cfg = NULL;
12809
12810                 mono_raise_exception ((MonoException*)exc);
12811         }
12812         default:
12813                 g_assert_not_reached ();
12814         }
12815
12816         mono_domain_lock (target_domain);
12817
12818         /* Check if some other thread already did the job. In this case, we can
12819        discard the code this thread generated. */
12820
12821         mono_domain_jit_code_hash_lock (target_domain);
12822
12823         info = lookup_method_inner (target_domain, method);
12824         if (info) {
12825                 /* We can't use a domain specific method in another domain */
12826                 if ((target_domain == mono_domain_get ()) || info->domain_neutral) {
12827                         code = info->code_start;
12828 //                      printf("Discarding code for method %s\n", method->name);
12829                 }
12830         }
12831         
12832         if (code == NULL) {
12833                 mono_internal_hash_table_insert (&target_domain->jit_code_hash, cfg->jit_info->method, cfg->jit_info);
12834                 mono_domain_jit_code_hash_unlock (target_domain);
12835                 code = cfg->native_code;
12836
12837                 if (cfg->generic_sharing_context && mono_method_is_generic_sharable_impl (method, FALSE)) {
12838                         /* g_print ("inserting method %s.%s.%s\n", method->klass->name_space, method->klass->name, method->name); */
12839                         mono_domain_register_shared_generic (target_domain, 
12840                                 mono_method_get_declaring_generic_method (method), cfg->jit_info);
12841                         mono_stats.generics_shared_methods++;
12842                 }
12843         } else {
12844                 mono_domain_jit_code_hash_unlock (target_domain);
12845         }
12846
12847         mono_destroy_compile (cfg);
12848
12849         if (target_domain->jump_target_hash) {
12850                 MonoJumpInfo patch_info;
12851                 GSList *list, *tmp;
12852                 list = g_hash_table_lookup (target_domain->jump_target_hash, method);
12853                 if (list) {
12854                         patch_info.next = NULL;
12855                         patch_info.ip.i = 0;
12856                         patch_info.type = MONO_PATCH_INFO_METHOD_JUMP;
12857                         patch_info.data.method = method;
12858                         g_hash_table_remove (target_domain->jump_target_hash, method);
12859                 }
12860                 for (tmp = list; tmp; tmp = tmp->next)
12861                         mono_arch_patch_code (NULL, target_domain, tmp->data, &patch_info, TRUE);
12862                 g_slist_free (list);
12863         }
12864
12865         mono_domain_unlock (target_domain);
12866
12867         vtable = mono_class_vtable (target_domain, method->klass);
12868         if (!vtable) {
12869                 MonoException *exc;
12870                 exc = mono_class_get_exception_for_failure (method->klass);
12871                 g_assert (exc);
12872                 mono_raise_exception (exc);
12873         }
12874         mono_runtime_class_init (vtable);
12875         return code;
12876 }
12877
12878 static gpointer
12879 mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt)
12880 {
12881         MonoDomain *target_domain, *domain = mono_domain_get ();
12882         MonoJitInfo *info;
12883         gpointer p;
12884         MonoJitICallInfo *callinfo = NULL;
12885
12886         /*
12887          * ICALL wrappers are handled specially, since there is only one copy of them
12888          * shared by all appdomains.
12889          */
12890         if ((method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && (strstr (method->name, "__icall_wrapper_") == method->name)) {
12891                 const char *icall_name;
12892
12893                 icall_name = method->name + strlen ("__icall_wrapper_");
12894                 g_assert (icall_name);
12895                 callinfo = mono_find_jit_icall_by_name (icall_name);
12896                 g_assert (callinfo);
12897
12898                 /* Must be domain neutral since there is only one copy */
12899                 opt |= MONO_OPT_SHARED;
12900         }
12901
12902         if (opt & MONO_OPT_SHARED)
12903                 target_domain = mono_get_root_domain ();
12904         else 
12905                 target_domain = domain;
12906
12907         info = lookup_method (target_domain, method);
12908         if (info) {
12909                 /* We can't use a domain specific method in another domain */
12910                 if (! ((domain != target_domain) && !info->domain_neutral)) {
12911                         MonoVTable *vtable;
12912
12913                         mono_jit_stats.methods_lookups++;
12914                         vtable = mono_class_vtable (domain, method->klass);
12915                         mono_runtime_class_init (vtable);
12916                         return mono_create_ftnptr (target_domain, info->code_start);
12917                 }
12918         }
12919
12920         p = mono_create_ftnptr (target_domain, mono_jit_compile_method_inner (method, target_domain, opt));
12921
12922         if (callinfo) {
12923                 mono_jit_lock ();
12924                 if (!callinfo->wrapper) {
12925                         callinfo->wrapper = p;
12926                         mono_register_jit_icall_wrapper (callinfo, p);
12927                         mono_debug_add_icall_wrapper (method, callinfo);
12928                 }
12929                 mono_jit_unlock ();
12930         }
12931
12932         return p;
12933 }
12934
12935 static gpointer
12936 mono_jit_compile_method (MonoMethod *method)
12937 {
12938         return mono_jit_compile_method_with_opt (method, default_opt);
12939 }
12940
12941 static void
12942 invalidated_delegate_trampoline (char *desc)
12943 {
12944         g_error ("Unmanaged code called delegate of type %s which was already garbage collected.\n"
12945                  "See http://www.go-mono.com/delegate.html for an explanation and ways to fix this.",
12946                  desc);
12947 }
12948
12949 /*
12950  * mono_jit_free_method:
12951  *
12952  *  Free all memory allocated by the JIT for METHOD.
12953  */
12954 static void
12955 mono_jit_free_method (MonoDomain *domain, MonoMethod *method)
12956 {
12957         MonoJitDynamicMethodInfo *ji;
12958         gboolean destroy = TRUE;
12959
12960         g_assert (method->dynamic);
12961
12962         mono_domain_lock (domain);
12963         ji = mono_dynamic_code_hash_lookup (domain, method);
12964         mono_domain_unlock (domain);
12965
12966         if (!ji)
12967                 return;
12968         mono_domain_lock (domain);
12969         g_hash_table_remove (domain->dynamic_code_hash, method);
12970         mono_internal_hash_table_remove (&domain->jit_code_hash, method);
12971         g_hash_table_remove (domain->jump_trampoline_hash, method);
12972         mono_domain_unlock (domain);
12973
12974 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
12975         if (debug_options.keep_delegates && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
12976                 /*
12977                  * Instead of freeing the code, change it to call an error routine
12978                  * so people can fix their code.
12979                  */
12980                 char *type = mono_type_full_name (&method->klass->byval_arg);
12981                 char *type_and_method = g_strdup_printf ("%s.%s", type, method->name);
12982
12983                 g_free (type);
12984                 mono_arch_invalidate_method (ji->ji, invalidated_delegate_trampoline, type_and_method);
12985                 destroy = FALSE;
12986         }
12987 #endif
12988
12989         /* 
12990          * This needs to be done before freeing code_mp, since the code address is the
12991          * key in the table, so if we free the code_mp first, another thread can grab the
12992          * same code address and replace our entry in the table.
12993          */
12994         mono_jit_info_table_remove (domain, ji->ji);
12995
12996         if (destroy)
12997                 mono_code_manager_destroy (ji->code_mp);
12998         g_free (ji);
12999 }
13000
13001 gpointer
13002 mono_jit_find_compiled_method (MonoDomain *domain, MonoMethod *method)
13003 {
13004         MonoDomain *target_domain;
13005         MonoJitInfo *info;
13006
13007         if (default_opt & MONO_OPT_SHARED)
13008                 target_domain = mono_get_root_domain ();
13009         else 
13010                 target_domain = domain;
13011
13012         info = lookup_method (target_domain, method);
13013         if (info) {
13014                 /* We can't use a domain specific method in another domain */
13015                 if (! ((domain != target_domain) && !info->domain_neutral)) {
13016                         mono_jit_stats.methods_lookups++;
13017                         return info->code_start;
13018                 }
13019         }
13020
13021         return NULL;
13022 }
13023
13024 /**
13025  * mono_jit_runtime_invoke:
13026  * @method: the method to invoke
13027  * @obj: this pointer
13028  * @params: array of parameter values.
13029  * @exc: used to catch exceptions objects
13030  */
13031 static MonoObject*
13032 mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
13033 {
13034         MonoMethod *to_compile;
13035         MonoMethod *invoke;
13036         MonoObject *(*runtime_invoke) (MonoObject *this, void **params, MonoObject **exc, void* compiled_method);
13037         void* compiled_method;
13038         MonoVTable *vtable;
13039
13040         if (obj == NULL && !(method->flags & METHOD_ATTRIBUTE_STATIC) && !method->string_ctor && (method->wrapper_type == 0)) {
13041                 g_warning ("Ignoring invocation of an instance method on a NULL instance.\n");
13042                 return NULL;
13043         }
13044
13045         if (((method->flags & METHOD_ATTRIBUTE_STATIC) ||
13046                                 (method->is_inflated && mono_method_get_context (method)->method_inst)) &&
13047                         mono_class_generic_sharing_enabled (method->klass) &&
13048                         mono_method_is_generic_sharable_impl (method, FALSE)) {
13049                 to_compile = mono_marshal_get_static_rgctx_invoke (method);
13050         } else {
13051                 to_compile = method;
13052         }
13053
13054         invoke = mono_marshal_get_runtime_invoke (method);
13055         runtime_invoke = mono_jit_compile_method (invoke);
13056         
13057         /* We need this here becuase mono_marshal_get_runtime_invoke can be place 
13058          * the helper method in System.Object and not the target class
13059          */
13060         vtable = mono_class_vtable (mono_domain_get (), method->klass);
13061         g_assert (vtable);
13062         mono_runtime_class_init (vtable);
13063
13064         if (method->klass->rank && (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
13065                 (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
13066                 /* 
13067                  * Array Get/Set/Address methods. The JIT implements them using inline code 
13068                  * inside the runtime invoke wrappers, so no need to compile them.
13069                  */
13070                 compiled_method = NULL;
13071         } else {
13072                 compiled_method = mono_jit_compile_method (to_compile);
13073         }
13074         return runtime_invoke (obj, params, exc, compiled_method);
13075 }
13076
13077 #ifdef MONO_GET_CONTEXT
13078 #define GET_CONTEXT MONO_GET_CONTEXT
13079 #endif
13080
13081 #ifndef GET_CONTEXT
13082 #ifdef PLATFORM_WIN32
13083 #define GET_CONTEXT \
13084         struct sigcontext *ctx = (struct sigcontext*)_dummy;
13085 #else
13086 #ifdef MONO_ARCH_USE_SIGACTION
13087 #define GET_CONTEXT \
13088     void *ctx = context;
13089 #elif defined(__sparc__)
13090 #define GET_CONTEXT \
13091     void *ctx = sigctx;
13092 #else
13093 #define GET_CONTEXT \
13094         void **_p = (void **)&_dummy; \
13095         struct sigcontext *ctx = (struct sigcontext *)++_p;
13096 #endif
13097 #endif
13098 #endif
13099
13100 #ifdef MONO_ARCH_USE_SIGACTION
13101 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy, siginfo_t *info, void *context)
13102 #elif defined(__sparc__)
13103 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy, void *sigctx)
13104 #else
13105 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy)
13106 #endif
13107
13108 static void
13109 SIG_HANDLER_SIGNATURE (sigfpe_signal_handler)
13110 {
13111         MonoException *exc = NULL;
13112 #ifndef MONO_ARCH_USE_SIGACTION
13113         void *info = NULL;
13114 #endif
13115         GET_CONTEXT;
13116
13117 #if defined(MONO_ARCH_HAVE_IS_INT_OVERFLOW)
13118         if (mono_arch_is_int_overflow (ctx, info))
13119                 exc = mono_get_exception_arithmetic ();
13120         else
13121                 exc = mono_get_exception_divide_by_zero ();
13122 #else
13123         exc = mono_get_exception_divide_by_zero ();
13124 #endif
13125         
13126         mono_arch_handle_exception (ctx, exc, FALSE);
13127 }
13128
13129 static void
13130 SIG_HANDLER_SIGNATURE (sigill_signal_handler)
13131 {
13132         MonoException *exc;
13133         GET_CONTEXT;
13134
13135         exc = mono_get_exception_execution_engine ("SIGILL");
13136         
13137         mono_arch_handle_exception (ctx, exc, FALSE);
13138 }
13139
13140 static void
13141 SIG_HANDLER_SIGNATURE (sigsegv_signal_handler)
13142 {
13143 #ifndef MONO_ARCH_SIGSEGV_ON_ALTSTACK
13144         MonoException *exc = NULL;
13145 #endif
13146         MonoJitInfo *ji;
13147
13148 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
13149         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
13150 #endif
13151         GET_CONTEXT;
13152
13153 #ifdef MONO_ARCH_USE_SIGACTION
13154         if (debug_options.collect_pagefault_stats) {
13155                 if (mono_raw_buffer_is_pagefault (info->si_addr)) {
13156                         mono_raw_buffer_handle_pagefault (info->si_addr);
13157                         return;
13158                 }
13159                 if (mono_aot_is_pagefault (info->si_addr)) {
13160                         mono_aot_handle_pagefault (info->si_addr);
13161                         return;
13162                 }
13163         }
13164 #endif
13165
13166         ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context (ctx));
13167
13168 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
13169         /* we got a stack overflow in the soft-guard pages
13170          * There are two cases:
13171          * 1) managed code caused the overflow: we unprotect the soft-guard page
13172          * and let the arch-specific code trigger the exception handling mechanism
13173          * in the thread stack. The soft-guard pages will be protected again as the stack is unwound.
13174          * 2) unmanaged code caused the overflow: we unprotect the soft-guard page
13175          * and hope we can continue with those enabled, at least until the hard-guard page
13176          * is hit. The alternative to continuing here is to just print a message and abort.
13177          * We may add in the future the code to protect the pages again in the codepath
13178          * when we return from unmanaged to managed code.
13179          */
13180         if (jit_tls->stack_ovf_guard_size && (guint8*)info->si_addr >= (guint8*)jit_tls->stack_ovf_guard_base &&
13181                         (guint8*)info->si_addr < (guint8*)jit_tls->stack_ovf_guard_base + jit_tls->stack_ovf_guard_size) {
13182                 mono_mprotect (jit_tls->stack_ovf_guard_base, jit_tls->stack_ovf_guard_size, MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
13183                 if (ji) {
13184                         mono_arch_handle_altstack_exception (ctx, info->si_addr, TRUE);
13185                 } else {
13186                         /* We print a message: after this even managed stack overflows
13187                          * may crash the runtime
13188                          */
13189                         fprintf (stderr, "Stack overflow in unmanaged: IP: %p, fault addr: %p\n", mono_arch_ip_from_context (ctx), (gpointer)info->si_addr);
13190                 }
13191                 return;
13192         }
13193         /* The hard-guard page has been hit: there is not much we can do anymore
13194          * Print a hopefully clear message and abort.
13195          */
13196         if (jit_tls->stack_size && 
13197                         ABS ((guint8*)info->si_addr - ((guint8*)jit_tls->end_of_stack - jit_tls->stack_size)) < 32768) {
13198                 const char *method;
13199                 /* we don't do much now, but we can warn the user with a useful message */
13200                 fprintf (stderr, "Stack overflow: IP: %p, fault addr: %p\n", mono_arch_ip_from_context (ctx), (gpointer)info->si_addr);
13201                 if (ji && ji->method)
13202                         method = mono_method_full_name (ji->method, TRUE);
13203                 else
13204                         method = "Unmanaged";
13205                 fprintf (stderr, "At %s\n", method);
13206                 abort ();
13207         } else {
13208                 mono_arch_handle_altstack_exception (ctx, info->si_addr, FALSE);
13209         }
13210 #else
13211
13212         if (!ji) {
13213                 mono_handle_native_sigsegv (SIGSEGV, ctx);
13214         }
13215                         
13216         mono_arch_handle_exception (ctx, exc, FALSE);
13217 #endif
13218 }
13219
13220 #ifndef PLATFORM_WIN32
13221
13222 static void
13223 SIG_HANDLER_SIGNATURE (sigabrt_signal_handler)
13224 {
13225         MonoJitInfo *ji;
13226         GET_CONTEXT;
13227
13228         ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
13229         if (!ji) {
13230                 mono_handle_native_sigsegv (SIGABRT, ctx);
13231         }
13232 }
13233
13234 static void
13235 SIG_HANDLER_SIGNATURE (sigusr1_signal_handler)
13236 {
13237         gboolean running_managed;
13238         MonoException *exc;
13239         MonoThread *thread = mono_thread_current ();
13240         void *ji;
13241         
13242         GET_CONTEXT;
13243
13244         if (thread->thread_dump_requested) {
13245                 thread->thread_dump_requested = FALSE;
13246
13247                 mono_print_thread_dump (ctx);
13248         }
13249
13250         /*
13251          * FIXME:
13252          * This is an async signal, so the code below must not call anything which
13253          * is not async safe. That includes the pthread locking functions. If we
13254          * know that we interrupted managed code, then locking is safe.
13255          */
13256         ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
13257         running_managed = ji != NULL;
13258         
13259         exc = mono_thread_request_interruption (running_managed); 
13260         if (!exc) return;
13261
13262         mono_arch_handle_exception (ctx, exc, FALSE);
13263 }
13264
13265 #if defined(__i386__) || defined(__x86_64__)
13266 #define FULL_STAT_PROFILER_BACKTRACE 1
13267 #define CURRENT_FRAME_GET_BASE_POINTER(f) (* (gpointer*)(f))
13268 #define CURRENT_FRAME_GET_RETURN_ADDRESS(f) (* (((gpointer*)(f)) + 1))
13269 #if MONO_ARCH_STACK_GROWS_UP
13270 #define IS_BEFORE_ON_STACK <
13271 #define IS_AFTER_ON_STACK >
13272 #else
13273 #define IS_BEFORE_ON_STACK >
13274 #define IS_AFTER_ON_STACK <
13275 #endif
13276 #else
13277 #define FULL_STAT_PROFILER_BACKTRACE 0
13278 #endif
13279
13280 #if defined(__ia64__) || defined(__sparc__) || defined(sparc) || defined(__s390__) || defined(s390)
13281
13282 static void
13283 SIG_HANDLER_SIGNATURE (sigprof_signal_handler)
13284 {
13285         NOT_IMPLEMENTED;
13286 }
13287
13288 #else
13289
13290 static void
13291 SIG_HANDLER_SIGNATURE (sigprof_signal_handler)
13292 {
13293         int call_chain_depth = mono_profiler_stat_get_call_chain_depth ();
13294         GET_CONTEXT;
13295         
13296         if (call_chain_depth == 0) {
13297                 mono_profiler_stat_hit (mono_arch_ip_from_context (ctx), ctx);
13298         } else {
13299                 MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
13300                 int current_frame_index = 1;
13301                 MonoContext mono_context;
13302 #if FULL_STAT_PROFILER_BACKTRACE
13303                 guchar *current_frame;
13304                 guchar *stack_bottom;
13305                 guchar *stack_top;
13306 #else
13307                 MonoDomain *domain;
13308 #endif
13309                 guchar *ips [call_chain_depth + 1];
13310
13311                 mono_arch_sigctx_to_monoctx (ctx, &mono_context);
13312                 ips [0] = MONO_CONTEXT_GET_IP (&mono_context);
13313                 
13314                 if (jit_tls != NULL) {
13315 #if FULL_STAT_PROFILER_BACKTRACE
13316                         stack_bottom = jit_tls->end_of_stack;
13317                         stack_top = MONO_CONTEXT_GET_SP (&mono_context);
13318                         current_frame = MONO_CONTEXT_GET_BP (&mono_context);
13319                         
13320                         while ((current_frame_index <= call_chain_depth) &&
13321                                         (stack_bottom IS_BEFORE_ON_STACK (guchar*) current_frame) &&
13322                                         ((guchar*) current_frame IS_BEFORE_ON_STACK stack_top)) {
13323                                 ips [current_frame_index] = CURRENT_FRAME_GET_RETURN_ADDRESS (current_frame);
13324                                 current_frame_index ++;
13325                                 stack_top = current_frame;
13326                                 current_frame = CURRENT_FRAME_GET_BASE_POINTER (current_frame);
13327                         }
13328 #else
13329                         domain = mono_domain_get ();
13330                         if (domain != NULL) {
13331                                 MonoLMF *lmf = NULL;
13332                                 MonoJitInfo *ji;
13333                                 MonoJitInfo res;
13334                                 MonoContext new_mono_context;
13335                                 int native_offset;
13336                                 ji = mono_arch_find_jit_info (domain, jit_tls, &res, NULL, &mono_context,
13337                                                 &new_mono_context, NULL, &lmf, &native_offset, NULL);
13338                                 while ((ji != NULL) && (current_frame_index <= call_chain_depth)) {
13339                                         ips [current_frame_index] = MONO_CONTEXT_GET_IP (&new_mono_context);
13340                                         current_frame_index ++;
13341                                         mono_context = new_mono_context;
13342                                         ji = mono_arch_find_jit_info (domain, jit_tls, &res, NULL, &mono_context,
13343                                                         &new_mono_context, NULL, &lmf, &native_offset, NULL);
13344                                 }
13345                         }
13346 #endif
13347                 }
13348                 
13349                 
13350                 mono_profiler_stat_call_chain (current_frame_index, & ips [0], ctx);
13351         }
13352 }
13353
13354 #endif
13355
13356 static void
13357 SIG_HANDLER_SIGNATURE (sigquit_signal_handler)
13358 {
13359         GET_CONTEXT;
13360
13361         printf ("Full thread dump:\n");
13362
13363         mono_threads_request_thread_dump ();
13364
13365         /*
13366          * print_thread_dump () skips the current thread, since sending a signal
13367          * to it would invoke the signal handler below the sigquit signal handler,
13368          * and signal handlers don't create an lmf, so the stack walk could not
13369          * be performed.
13370          */
13371         mono_print_thread_dump (ctx);
13372 }
13373
13374 static void
13375 SIG_HANDLER_SIGNATURE (sigusr2_signal_handler)
13376 {
13377         gboolean enabled = mono_trace_is_enabled ();
13378
13379         mono_trace_enable (!enabled);
13380 }
13381
13382 #endif
13383
13384 static void
13385 SIG_HANDLER_SIGNATURE (sigint_signal_handler)
13386 {
13387         MonoException *exc;
13388         GET_CONTEXT;
13389
13390         exc = mono_get_exception_execution_engine ("Interrupted (SIGINT).");
13391         
13392         mono_arch_handle_exception (ctx, exc, FALSE);
13393 }
13394
13395 #ifdef PLATFORM_MACOSX
13396
13397 /*
13398  * This code disables the CrashReporter of MacOS X by installing
13399  * a dummy Mach exception handler.
13400  */
13401
13402 /*
13403  * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/exc_server.html
13404  */
13405 extern
13406 boolean_t
13407 exc_server (mach_msg_header_t *request_msg,
13408             mach_msg_header_t *reply_msg);
13409
13410 /*
13411  * The exception message
13412  */
13413 typedef struct {
13414         mach_msg_base_t msg;  /* common mach message header */
13415         char payload [1024];  /* opaque */
13416 } mach_exception_msg_t;
13417
13418 /* The exception port */
13419 static mach_port_t mach_exception_port = VM_MAP_NULL;
13420
13421 /*
13422  * Implicitly called by exc_server. Must be public.
13423  *
13424  * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/catch_exception_raise.html
13425  */
13426 kern_return_t
13427 catch_exception_raise (
13428         mach_port_t exception_port,
13429         mach_port_t thread,
13430         mach_port_t task,
13431         exception_type_t exception,
13432         exception_data_t code,
13433         mach_msg_type_number_t code_count)
13434 {
13435         /* consume the exception */
13436         return KERN_FAILURE;
13437 }
13438
13439 /*
13440  * Exception thread handler.
13441  */
13442 static
13443 void *
13444 mach_exception_thread (void *arg)
13445 {
13446         for (;;) {
13447                 mach_exception_msg_t request;
13448                 mach_exception_msg_t reply;
13449                 mach_msg_return_t result;
13450
13451                 /* receive from "mach_exception_port" */
13452                 result = mach_msg (&request.msg.header,
13453                                    MACH_RCV_MSG | MACH_RCV_LARGE,
13454                                    0,
13455                                    sizeof (request),
13456                                    mach_exception_port,
13457                                    MACH_MSG_TIMEOUT_NONE,
13458                                    MACH_PORT_NULL);
13459
13460                 g_assert (result == MACH_MSG_SUCCESS);
13461
13462                 /* dispatch to catch_exception_raise () */
13463                 exc_server (&request.msg.header, &reply.msg.header);
13464
13465                 /* send back to sender */
13466                 result = mach_msg (&reply.msg.header,
13467                                    MACH_SEND_MSG,
13468                                    reply.msg.header.msgh_size,
13469                                    0,
13470                                    MACH_PORT_NULL,
13471                                    MACH_MSG_TIMEOUT_NONE,
13472                                    MACH_PORT_NULL);
13473
13474                 g_assert (result == MACH_MSG_SUCCESS);
13475         }
13476         return NULL;
13477 }
13478
13479 static void
13480 macosx_register_exception_handler ()
13481 {
13482         mach_port_t task;
13483         pthread_attr_t attr;
13484         pthread_t thread;
13485
13486         if (mach_exception_port != VM_MAP_NULL)
13487                 return;
13488
13489         task = mach_task_self ();
13490
13491         /* create the "mach_exception_port" with send & receive rights */
13492         g_assert (mach_port_allocate (task, MACH_PORT_RIGHT_RECEIVE,
13493                                       &mach_exception_port) == KERN_SUCCESS);
13494         g_assert (mach_port_insert_right (task, mach_exception_port, mach_exception_port,
13495                                           MACH_MSG_TYPE_MAKE_SEND) == KERN_SUCCESS);
13496
13497         /* create the exception handler thread */
13498         g_assert (!pthread_attr_init (&attr));
13499         g_assert (!pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED));
13500         g_assert (!pthread_create (&thread, &attr, mach_exception_thread, NULL));
13501         pthread_attr_destroy (&attr);
13502
13503         /*
13504          * register "mach_exception_port" as a receiver for the
13505          * EXC_BAD_ACCESS exception
13506          *
13507          * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/task_set_exception_ports.html
13508          */
13509         g_assert (task_set_exception_ports (task, EXC_MASK_BAD_ACCESS,
13510                                             mach_exception_port,
13511                                             EXCEPTION_DEFAULT,
13512                                             MACHINE_THREAD_STATE) == KERN_SUCCESS);
13513 }
13514 #endif
13515
13516 #ifndef PLATFORM_WIN32
13517 static void
13518 add_signal_handler (int signo, gpointer handler)
13519 {
13520         struct sigaction sa;
13521
13522 #ifdef MONO_ARCH_USE_SIGACTION
13523         sa.sa_sigaction = handler;
13524         sigemptyset (&sa.sa_mask);
13525         sa.sa_flags = SA_SIGINFO;
13526 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
13527         if (signo == SIGSEGV)
13528                 sa.sa_flags |= SA_ONSTACK;
13529 #endif
13530 #else
13531         sa.sa_handler = handler;
13532         sigemptyset (&sa.sa_mask);
13533         sa.sa_flags = 0;
13534 #endif
13535         g_assert (sigaction (signo, &sa, NULL) != -1);
13536 }
13537
13538 static void
13539 remove_signal_handler (int signo)
13540 {
13541         struct sigaction sa;
13542
13543         sa.sa_handler = SIG_DFL;
13544         sigemptyset (&sa.sa_mask);
13545         sa.sa_flags = 0;
13546
13547         g_assert (sigaction (signo, &sa, NULL) != -1);
13548 }
13549 #endif
13550
13551 static void
13552 mono_runtime_install_handlers (void)
13553 {
13554 #ifdef PLATFORM_WIN32
13555         win32_seh_init();
13556         win32_seh_set_handler(SIGFPE, sigfpe_signal_handler);
13557         win32_seh_set_handler(SIGILL, sigill_signal_handler);
13558         win32_seh_set_handler(SIGSEGV, sigsegv_signal_handler);
13559         if (debug_options.handle_sigint)
13560                 win32_seh_set_handler(SIGINT, sigint_signal_handler);
13561
13562 #else /* !PLATFORM_WIN32 */
13563
13564
13565 #ifdef PLATFORM_MACOSX
13566         macosx_register_exception_handler ();
13567 #endif
13568
13569         if (debug_options.handle_sigint)
13570                 add_signal_handler (SIGINT, sigint_signal_handler);
13571
13572         add_signal_handler (SIGFPE, sigfpe_signal_handler);
13573         add_signal_handler (SIGQUIT, sigquit_signal_handler);
13574         add_signal_handler (SIGILL, sigill_signal_handler);
13575         add_signal_handler (SIGBUS, sigsegv_signal_handler);
13576         if (mono_jit_trace_calls != NULL)
13577                 add_signal_handler (SIGUSR2, sigusr2_signal_handler);
13578
13579         add_signal_handler (mono_thread_get_abort_signal (), sigusr1_signal_handler);
13580         signal (SIGPIPE, SIG_IGN);
13581
13582         add_signal_handler (SIGABRT, sigabrt_signal_handler);
13583
13584         /* catch SIGSEGV */
13585         add_signal_handler (SIGSEGV, sigsegv_signal_handler);
13586 #endif /* PLATFORM_WIN32 */
13587 }
13588
13589 static void
13590 mono_runtime_cleanup_handlers (void)
13591 {
13592 #ifdef PLATFORM_WIN32
13593         win32_seh_cleanup();
13594 #else
13595         if (debug_options.handle_sigint)
13596                 remove_signal_handler (SIGINT);
13597
13598         remove_signal_handler (SIGFPE);
13599         remove_signal_handler (SIGQUIT);
13600         remove_signal_handler (SIGILL);
13601         remove_signal_handler (SIGBUS);
13602         if (mono_jit_trace_calls != NULL)
13603                 remove_signal_handler (SIGUSR2);
13604
13605         remove_signal_handler (mono_thread_get_abort_signal ());
13606
13607         remove_signal_handler (SIGABRT);
13608
13609         remove_signal_handler (SIGSEGV);
13610 #endif /* PLATFORM_WIN32 */
13611 }
13612
13613
13614 #ifdef HAVE_LINUX_RTC_H
13615 #include <linux/rtc.h>
13616 #include <sys/ioctl.h>
13617 #include <fcntl.h>
13618 static int rtc_fd = -1;
13619
13620 static int
13621 enable_rtc_timer (gboolean enable)
13622 {
13623         int flags;
13624         flags = fcntl (rtc_fd, F_GETFL);
13625         if (flags < 0) {
13626                 perror ("getflags");
13627                 return 0;
13628         }
13629         if (enable)
13630                 flags |= FASYNC;
13631         else
13632                 flags &= ~FASYNC;
13633         if (fcntl (rtc_fd, F_SETFL, flags) == -1) {
13634                 perror ("setflags");
13635                 return 0;
13636         }
13637         return 1;
13638 }
13639 #endif
13640
13641 #ifdef PLATFORM_WIN32
13642 static HANDLE win32_main_thread;
13643 static MMRESULT win32_timer;
13644
13645 static void CALLBACK
13646 win32_time_proc (UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2)
13647 {
13648         CONTEXT context;
13649
13650         context.ContextFlags = CONTEXT_CONTROL;
13651         if (GetThreadContext (win32_main_thread, &context)) {
13652 #ifdef _WIN64
13653                 mono_profiler_stat_hit ((guchar *) context.Rip, &context);
13654 #else
13655                 mono_profiler_stat_hit ((guchar *) context.Eip, &context);
13656 #endif
13657         }
13658 }
13659 #endif
13660
13661 static void
13662 setup_stat_profiler (void)
13663 {
13664 #ifdef ITIMER_PROF
13665         struct itimerval itval;
13666         static int inited = 0;
13667 #ifdef HAVE_LINUX_RTC_H
13668         const char *rtc_freq;
13669         if (!inited && (rtc_freq = g_getenv ("MONO_RTC"))) {
13670                 int freq = 0;
13671                 inited = 1;
13672                 if (*rtc_freq)
13673                         freq = atoi (rtc_freq);
13674                 if (!freq)
13675                         freq = 1024;
13676                 rtc_fd = open ("/dev/rtc", O_RDONLY);
13677                 if (rtc_fd == -1) {
13678                         perror ("open /dev/rtc");
13679                         return;
13680                 }
13681                 add_signal_handler (SIGPROF, sigprof_signal_handler);
13682                 if (ioctl (rtc_fd, RTC_IRQP_SET, freq) == -1) {
13683                         perror ("set rtc freq");
13684                         return;
13685                 }
13686                 if (ioctl (rtc_fd, RTC_PIE_ON, 0) == -1) {
13687                         perror ("start rtc");
13688                         return;
13689                 }
13690                 if (fcntl (rtc_fd, F_SETSIG, SIGPROF) == -1) {
13691                         perror ("setsig");
13692                         return;
13693                 }
13694                 if (fcntl (rtc_fd, F_SETOWN, getpid ()) == -1) {
13695                         perror ("setown");
13696                         return;
13697                 }
13698                 enable_rtc_timer (TRUE);
13699                 return;
13700         }
13701         if (rtc_fd >= 0)
13702                 return;
13703 #endif
13704
13705         itval.it_interval.tv_usec = 999;
13706         itval.it_interval.tv_sec = 0;
13707         itval.it_value = itval.it_interval;
13708         setitimer (ITIMER_PROF, &itval, NULL);
13709         if (inited)
13710                 return;
13711         inited = 1;
13712         add_signal_handler (SIGPROF, sigprof_signal_handler);
13713 #elif defined (PLATFORM_WIN32)
13714         static int inited = 0;
13715         TIMECAPS timecaps;
13716
13717         if (inited)
13718                 return;
13719
13720         inited = 1;
13721         if (timeGetDevCaps (&timecaps, sizeof (timecaps)) != TIMERR_NOERROR)
13722                 return;
13723
13724         if ((win32_main_thread = OpenThread (READ_CONTROL | THREAD_GET_CONTEXT, FALSE, GetCurrentThreadId ())) == NULL)
13725                 return;
13726
13727         if (timeBeginPeriod (1) != TIMERR_NOERROR)
13728                 return;
13729
13730         if ((win32_timer = timeSetEvent (1, 0, win32_time_proc, 0, TIME_PERIODIC)) == 0) {
13731                 timeEndPeriod (1);
13732                 return;
13733         }
13734 #endif
13735 }
13736
13737 /* mono_jit_create_remoting_trampoline:
13738  * @method: pointer to the method info
13739  *
13740  * Creates a trampoline which calls the remoting functions. This
13741  * is used in the vtable of transparent proxies.
13742  * 
13743  * Returns: a pointer to the newly created code 
13744  */
13745 static gpointer
13746 mono_jit_create_remoting_trampoline (MonoMethod *method, MonoRemotingTarget target)
13747 {
13748         MonoMethod *nm;
13749         guint8 *addr = NULL;
13750
13751         if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) || 
13752             (mono_method_signature (method)->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class))) {
13753                 nm = mono_marshal_get_remoting_invoke_for_target (method, target);
13754                 addr = mono_compile_method (nm);
13755         } else {
13756                 addr = mono_compile_method (method);
13757         }
13758         return mono_get_addr_from_ftnptr (addr);
13759 }
13760
13761 #ifdef MONO_ARCH_HAVE_IMT
13762 static gpointer
13763 mini_get_imt_trampoline (void)
13764 {
13765         static gpointer tramp = NULL;
13766         if (!tramp)
13767                 tramp =  mono_arch_create_specific_trampoline (MONO_FAKE_IMT_METHOD, MONO_TRAMPOLINE_JIT, mono_get_root_domain (), NULL);
13768         return tramp;
13769 }
13770 #endif
13771
13772 #ifdef MONO_ARCH_COMMON_VTABLE_TRAMPOLINE
13773 gpointer
13774 mini_get_vtable_trampoline (void)
13775 {
13776         static gpointer tramp = NULL;
13777         if (!tramp)
13778                 tramp =  mono_arch_create_specific_trampoline (MONO_FAKE_VTABLE_METHOD, MONO_TRAMPOLINE_JIT, mono_get_root_domain (), NULL);
13779         return tramp;
13780 }
13781 #endif
13782
13783 static void
13784 mini_parse_debug_options (void)
13785 {
13786         char *options = getenv ("MONO_DEBUG");
13787         gchar **args, **ptr;
13788         
13789         if (!options)
13790                 return;
13791
13792         args = g_strsplit (options, ",", -1);
13793
13794         for (ptr = args; ptr && *ptr; ptr++) {
13795                 const char *arg = *ptr;
13796
13797                 if (!strcmp (arg, "handle-sigint"))
13798                         debug_options.handle_sigint = TRUE;
13799                 else if (!strcmp (arg, "keep-delegates"))
13800                         debug_options.keep_delegates = TRUE;
13801                 else if (!strcmp (arg, "collect-pagefault-stats"))
13802                         debug_options.collect_pagefault_stats = TRUE;
13803                 else if (!strcmp (arg, "break-on-unverified"))
13804                         debug_options.break_on_unverified = TRUE;
13805                 else if (!strcmp (arg, "no-gdb-backtrace"))
13806                         debug_options.no_gdb_backtrace = TRUE;
13807                 else if (!strcmp (arg, "dont-free-domains"))
13808                         mono_dont_free_domains = TRUE;
13809                 else {
13810                         fprintf (stderr, "Invalid option for the MONO_DEBUG env variable: %s\n", arg);
13811                         fprintf (stderr, "Available options: 'handle-sigint', 'keep-delegates', 'collect-pagefault-stats', 'break-on-unverified', 'no-gdb-backtrace', 'dont-free-domains'\n");
13812                         exit (1);
13813                 }
13814         }
13815 }
13816
13817 MonoDebugOptions *
13818 mini_get_debug_options (void)
13819 {
13820         return &debug_options;
13821 }
13822
13823 MonoDomain *
13824 mini_init (const char *filename, const char *runtime_version)
13825 {
13826         MonoDomain *domain;
13827
13828         MONO_PROBE_VES_INIT_BEGIN ();
13829
13830 #ifdef __linux__
13831         if (access ("/proc/self/maps", F_OK) != 0) {
13832                 g_print ("Mono requires /proc to be mounted.\n");
13833                 exit (1);
13834         }
13835 #endif
13836
13837         /* Happens when using the embedding interface */
13838         if (!default_opt_set)
13839                 default_opt = mono_parse_default_optimizations (NULL);
13840
13841         InitializeCriticalSection (&jit_mutex);
13842
13843         if (!global_codeman)
13844                 global_codeman = mono_code_manager_new ();
13845         jit_icall_name_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
13846
13847         mono_arch_cpu_init ();
13848
13849         mono_arch_init ();
13850
13851         mono_trampolines_init ();
13852
13853         mono_exceptions_init ();
13854
13855         if (!g_thread_supported ())
13856                 g_thread_init (NULL);
13857
13858         if (getenv ("MONO_DEBUG") != NULL)
13859                 mini_parse_debug_options ();
13860
13861         mono_gc_base_init ();
13862
13863         mono_jit_tls_id = TlsAlloc ();
13864         setup_jit_tls_data ((gpointer)-1, mono_thread_abort);
13865
13866         mono_burg_init ();
13867
13868         if (default_opt & MONO_OPT_AOT)
13869                 mono_aot_init ();
13870
13871         mono_runtime_install_handlers ();
13872         mono_threads_install_cleanup (mini_thread_cleanup);
13873
13874 #ifdef MONO_ARCH_HAVE_NOTIFY_PENDING_EXC
13875         // This is experimental code so provide an env var to switch it off
13876         if (getenv ("MONO_DISABLE_PENDING_EXCEPTIONS")) {
13877                 printf ("MONO_DISABLE_PENDING_EXCEPTIONS env var set.\n");
13878         } else {
13879                 check_for_pending_exc = FALSE;
13880                 mono_threads_install_notify_pending_exc (mono_arch_notify_pending_exc);
13881         }
13882 #endif
13883
13884 #define JIT_TRAMPOLINES_WORK
13885 #ifdef JIT_TRAMPOLINES_WORK
13886         mono_install_compile_method (mono_jit_compile_method);
13887         mono_install_free_method (mono_jit_free_method);
13888         mono_install_trampoline (mono_create_jit_trampoline);
13889         mono_install_jump_trampoline (mono_create_jump_trampoline);
13890         mono_install_remoting_trampoline (mono_jit_create_remoting_trampoline);
13891         mono_install_delegate_trampoline (mono_create_delegate_trampoline);
13892 #endif
13893 #define JIT_INVOKE_WORKS
13894 #ifdef JIT_INVOKE_WORKS
13895         mono_install_runtime_invoke (mono_jit_runtime_invoke);
13896         mono_install_handler (mono_arch_get_throw_exception ());
13897 #endif
13898         mono_install_stack_walk (mono_jit_walk_stack);
13899         mono_install_get_cached_class_info (mono_aot_get_cached_class_info);
13900         mono_install_get_class_from_name (mono_aot_get_class_from_name);
13901         mono_install_jit_info_find_in_aot (mono_aot_find_jit_info);
13902
13903         if (debug_options.collect_pagefault_stats) {
13904                 mono_raw_buffer_set_make_unreadable (TRUE);
13905                 mono_aot_set_make_unreadable (TRUE);
13906         }
13907
13908         if (runtime_version)
13909                 domain = mono_init_version (filename, runtime_version);
13910         else
13911                 domain = mono_init_from_assembly (filename, filename);
13912 #ifdef MONO_ARCH_HAVE_IMT
13913         mono_install_imt_thunk_builder (mono_arch_build_imt_thunk);
13914         mono_install_imt_trampoline (mini_get_imt_trampoline ());
13915 #if MONO_ARCH_COMMON_VTABLE_TRAMPOLINE
13916         mono_install_vtable_trampoline (mini_get_vtable_trampoline ());
13917 #endif
13918 #endif
13919         mono_icall_init ();
13920
13921         mono_add_internal_call ("System.Diagnostics.StackFrame::get_frame_info", 
13922                                 ves_icall_get_frame_info);
13923         mono_add_internal_call ("System.Diagnostics.StackTrace::get_trace", 
13924                                 ves_icall_get_trace);
13925         mono_add_internal_call ("System.Exception::get_trace", 
13926                                 ves_icall_System_Exception_get_trace);
13927         mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityFrame",
13928                                 ves_icall_System_Security_SecurityFrame_GetSecurityFrame);
13929         mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityStack",
13930                                 ves_icall_System_Security_SecurityFrame_GetSecurityStack);
13931         mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers", 
13932                                 mono_runtime_install_handlers);
13933
13934
13935         create_helper_signature ();
13936
13937 #define JIT_CALLS_WORK
13938 #ifdef JIT_CALLS_WORK
13939         /* Needs to be called here since register_jit_icall depends on it */
13940         mono_marshal_init ();
13941
13942         mono_arch_register_lowlevel_calls ();
13943         register_icall (mono_profiler_method_enter, "mono_profiler_method_enter", NULL, TRUE);
13944         register_icall (mono_profiler_method_leave, "mono_profiler_method_leave", NULL, TRUE);
13945         register_icall (mono_trace_enter_method, "mono_trace_enter_method", NULL, TRUE);
13946         register_icall (mono_trace_leave_method, "mono_trace_leave_method", NULL, TRUE);
13947         register_icall (mono_get_lmf_addr, "mono_get_lmf_addr", "ptr", TRUE);
13948         register_icall (mono_jit_thread_attach, "mono_jit_thread_attach", "void", TRUE);
13949         register_icall (mono_domain_get, "mono_domain_get", "ptr", TRUE);
13950
13951         register_icall (mono_arch_get_throw_exception (), "mono_arch_throw_exception", "void object", TRUE);
13952         register_icall (mono_arch_get_rethrow_exception (), "mono_arch_rethrow_exception", "void object", TRUE);
13953         register_icall (mono_arch_get_throw_exception_by_name (), "mono_arch_throw_exception_by_name", "void ptr", TRUE); 
13954 #if MONO_ARCH_HAVE_THROW_CORLIB_EXCEPTION
13955         register_icall (mono_arch_get_throw_corlib_exception (), "mono_arch_throw_corlib_exception", 
13956                                  "void ptr", TRUE);
13957 #endif
13958         register_icall (mono_thread_get_undeniable_exception, "mono_thread_get_undeniable_exception", "object", FALSE);
13959         register_icall (mono_thread_interruption_checkpoint, "mono_thread_interruption_checkpoint", "void", FALSE);
13960         register_icall (mono_thread_force_interruption_checkpoint, "mono_thread_force_interruption_checkpoint", "void", FALSE);
13961         register_icall (mono_load_remote_field_new, "mono_load_remote_field_new", "object object ptr ptr", FALSE);
13962         register_icall (mono_store_remote_field_new, "mono_store_remote_field_new", "void object ptr ptr object", FALSE);
13963
13964         /* 
13965          * NOTE, NOTE, NOTE, NOTE:
13966          * when adding emulation for some opcodes, remember to also add a dummy
13967          * rule to the burg files, because we need the arity information to be correct.
13968          */
13969 #ifndef MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS
13970         mono_register_opcode_emulation (OP_LMUL, "__emul_lmul", "long long long", mono_llmult, TRUE);
13971         mono_register_opcode_emulation (OP_LDIV, "__emul_ldiv", "long long long", mono_lldiv, FALSE);
13972         mono_register_opcode_emulation (OP_LDIV_UN, "__emul_ldiv_un", "long long long", mono_lldiv_un, FALSE);
13973         mono_register_opcode_emulation (OP_LREM, "__emul_lrem", "long long long", mono_llrem, FALSE);
13974         mono_register_opcode_emulation (OP_LREM_UN, "__emul_lrem_un", "long long long", mono_llrem_un, FALSE);
13975         mono_register_opcode_emulation (OP_LMUL_OVF_UN, "__emul_lmul_ovf_un", "long long long", mono_llmult_ovf_un, FALSE);
13976         mono_register_opcode_emulation (OP_LMUL_OVF, "__emul_lmul_ovf", "long long long", mono_llmult_ovf, FALSE);
13977 #endif
13978
13979 #ifndef MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS
13980         mono_register_opcode_emulation (OP_LSHL, "__emul_lshl", "long long int32", mono_lshl, TRUE);
13981         mono_register_opcode_emulation (OP_LSHR, "__emul_lshr", "long long int32", mono_lshr, TRUE);
13982         mono_register_opcode_emulation (OP_LSHR_UN, "__emul_lshr_un", "long long int32", mono_lshr_un, TRUE);
13983 #endif
13984
13985 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
13986         mono_register_opcode_emulation (CEE_DIV, "__emul_idiv", "int32 int32 int32", mono_idiv, FALSE);
13987         mono_register_opcode_emulation (CEE_DIV_UN, "__emul_idiv_un", "int32 int32 int32", mono_idiv_un, FALSE);
13988         mono_register_opcode_emulation (CEE_REM, "__emul_irem", "int32 int32 int32", mono_irem, FALSE);
13989         mono_register_opcode_emulation (CEE_REM_UN, "__emul_irem_un", "int32 int32 int32", mono_irem_un, FALSE);
13990 #endif
13991
13992 #ifdef MONO_ARCH_EMULATE_MUL_DIV
13993         mono_register_opcode_emulation (CEE_MUL_OVF, "__emul_imul_ovf", "int32 int32 int32", mono_imul_ovf, FALSE);
13994         mono_register_opcode_emulation (CEE_MUL_OVF_UN, "__emul_imul_ovf_un", "int32 int32 int32", mono_imul_ovf_un, FALSE);
13995         mono_register_opcode_emulation (CEE_MUL, "__emul_imul", "int32 int32 int32", mono_imul, TRUE);
13996 #endif
13997 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_SOFT_FLOAT)
13998         mono_register_opcode_emulation (OP_FDIV, "__emul_fdiv", "double double double", mono_fdiv, FALSE);
13999 #endif
14000
14001         mono_register_opcode_emulation (OP_FCONV_TO_U8, "__emul_fconv_to_u8", "ulong double", mono_fconv_u8, FALSE);
14002         mono_register_opcode_emulation (OP_FCONV_TO_U4, "__emul_fconv_to_u4", "uint32 double", mono_fconv_u4, FALSE);
14003         mono_register_opcode_emulation (OP_FCONV_TO_OVF_I8, "__emul_fconv_to_ovf_i8", "long double", mono_fconv_ovf_i8, FALSE);
14004         mono_register_opcode_emulation (OP_FCONV_TO_OVF_U8, "__emul_fconv_to_ovf_u8", "ulong double", mono_fconv_ovf_u8, FALSE);
14005
14006 #ifdef MONO_ARCH_EMULATE_FCONV_TO_I8
14007         mono_register_opcode_emulation (OP_FCONV_TO_I8, "__emul_fconv_to_i8", "long double", mono_fconv_i8, FALSE);
14008 #endif
14009 #ifdef MONO_ARCH_EMULATE_CONV_R8_UN
14010         mono_register_opcode_emulation (CEE_CONV_R_UN, "__emul_conv_r_un", "double int32", mono_conv_to_r8_un, FALSE);
14011 #endif
14012 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8
14013         mono_register_opcode_emulation (OP_LCONV_TO_R8, "__emul_lconv_to_r8", "double long", mono_lconv_to_r8, FALSE);
14014 #endif
14015 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R4
14016         mono_register_opcode_emulation (OP_LCONV_TO_R4, "__emul_lconv_to_r4", "float long", mono_lconv_to_r4, FALSE);
14017 #endif
14018 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8_UN
14019         mono_register_opcode_emulation (OP_LCONV_TO_R_UN, "__emul_lconv_to_r8_un", "double long", mono_lconv_to_r8_un, FALSE);
14020 #endif
14021 #ifdef MONO_ARCH_EMULATE_FREM
14022         mono_register_opcode_emulation (OP_FREM, "__emul_frem", "double double double", fmod, FALSE);
14023 #endif
14024
14025 #ifdef MONO_ARCH_SOFT_FLOAT
14026         mono_register_opcode_emulation (OP_FSUB, "__emul_fsub", "double double double", mono_fsub, FALSE);
14027         mono_register_opcode_emulation (OP_FADD, "__emul_fadd", "double double double", mono_fadd, FALSE);
14028         mono_register_opcode_emulation (OP_FMUL, "__emul_fmul", "double double double", mono_fmul, FALSE);
14029         mono_register_opcode_emulation (OP_FNEG, "__emul_fneg", "double double", mono_fneg, FALSE);
14030         mono_register_opcode_emulation (CEE_CONV_R8, "__emul_conv_r8", "double int32", mono_conv_to_r8, FALSE);
14031         mono_register_opcode_emulation (CEE_CONV_R4, "__emul_conv_r4", "double int32", mono_conv_to_r4, FALSE);
14032         mono_register_opcode_emulation (OP_FCONV_TO_R4, "__emul_fconv_to_r4", "double double", mono_fconv_r4, FALSE);
14033         mono_register_opcode_emulation (OP_FCONV_TO_I1, "__emul_fconv_to_i1", "int8 double", mono_fconv_i1, FALSE);
14034         mono_register_opcode_emulation (OP_FCONV_TO_I2, "__emul_fconv_to_i2", "int16 double", mono_fconv_i2, FALSE);
14035         mono_register_opcode_emulation (OP_FCONV_TO_I4, "__emul_fconv_to_i4", "int32 double", mono_fconv_i4, FALSE);
14036         mono_register_opcode_emulation (OP_FCONV_TO_U1, "__emul_fconv_to_u1", "uint8 double", mono_fconv_u1, FALSE);
14037         mono_register_opcode_emulation (OP_FCONV_TO_U2, "__emul_fconv_to_u2", "uint16 double", mono_fconv_u2, FALSE);
14038
14039         mono_register_opcode_emulation (OP_FBEQ, "__emul_fcmp_eq", "uint32 double double", mono_fcmp_eq, FALSE);
14040         mono_register_opcode_emulation (OP_FBLT, "__emul_fcmp_lt", "uint32 double double", mono_fcmp_lt, FALSE);
14041         mono_register_opcode_emulation (OP_FBGT, "__emul_fcmp_gt", "uint32 double double", mono_fcmp_gt, FALSE);
14042         mono_register_opcode_emulation (OP_FBLE, "__emul_fcmp_le", "uint32 double double", mono_fcmp_le, FALSE);
14043         mono_register_opcode_emulation (OP_FBGE, "__emul_fcmp_ge", "uint32 double double", mono_fcmp_ge, FALSE);
14044         mono_register_opcode_emulation (OP_FBNE_UN, "__emul_fcmp_ne_un", "uint32 double double", mono_fcmp_ne_un, FALSE);
14045         mono_register_opcode_emulation (OP_FBLT_UN, "__emul_fcmp_lt_un", "uint32 double double", mono_fcmp_lt_un, FALSE);
14046         mono_register_opcode_emulation (OP_FBGT_UN, "__emul_fcmp_gt_un", "uint32 double double", mono_fcmp_gt_un, FALSE);
14047         mono_register_opcode_emulation (OP_FBLE_UN, "__emul_fcmp_le_un", "uint32 double double", mono_fcmp_le_un, FALSE);
14048         mono_register_opcode_emulation (OP_FBGE_UN, "__emul_fcmp_ge_un", "uint32 double double", mono_fcmp_ge_un, FALSE);
14049
14050         mono_register_opcode_emulation (OP_FCEQ, "__emul_fcmp_ceq", "uint32 double double", mono_fceq, FALSE);
14051         mono_register_opcode_emulation (OP_FCGT, "__emul_fcmp_cgt", "uint32 double double", mono_fcgt, FALSE);
14052         mono_register_opcode_emulation (OP_FCGT_UN, "__emul_fcmp_cgt_un", "uint32 double double", mono_fcgt_un, FALSE);
14053         mono_register_opcode_emulation (OP_FCLT, "__emul_fcmp_clt", "uint32 double double", mono_fclt, FALSE);
14054         mono_register_opcode_emulation (OP_FCLT_UN, "__emul_fcmp_clt_un", "uint32 double double", mono_fclt_un, FALSE);
14055
14056         register_icall (mono_fload_r4, "mono_fload_r4", "double ptr", FALSE);
14057         register_icall (mono_fstore_r4, "mono_fstore_r4", "void double ptr", FALSE);
14058         register_icall (mono_fload_r4_arg, "mono_fload_r4_arg", "uint32 double", FALSE);
14059 #endif
14060
14061 #if SIZEOF_VOID_P == 4
14062         mono_register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", "uint32 double", mono_fconv_u4, TRUE);
14063 #endif
14064
14065         /* other jit icalls */
14066         register_icall (mono_delegate_ctor, "mono_delegate_ctor", "void object object ptr", FALSE);
14067         register_icall (mono_class_static_field_address , "mono_class_static_field_address", 
14068                                  "ptr ptr ptr", FALSE);
14069         register_icall (mono_ldtoken_wrapper, "mono_ldtoken_wrapper", "ptr ptr ptr ptr", FALSE);
14070         register_icall (mono_ldtoken_wrapper_generic_shared, "mono_ldtoken_wrapper_generic_shared",
14071                 "ptr ptr ptr ptr", FALSE);
14072         register_icall (mono_get_special_static_data, "mono_get_special_static_data", "ptr int", FALSE);
14073         register_icall (mono_ldstr, "mono_ldstr", "object ptr ptr int32", FALSE);
14074         register_icall (mono_helper_stelem_ref_check, "helper_stelem_ref_check", "void object object", FALSE);
14075         register_icall (mono_object_new, "mono_object_new", "object ptr ptr", FALSE);
14076         register_icall (mono_object_new_specific, "mono_object_new_specific", "object ptr", FALSE);
14077         register_icall (mono_array_new, "mono_array_new", "object ptr ptr int32", FALSE);
14078         register_icall (mono_array_new_specific, "mono_array_new_specific", "object ptr int32", FALSE);
14079         register_icall (mono_runtime_class_init, "mono_runtime_class_init", "void ptr", FALSE);
14080         register_icall (mono_ldftn, "mono_ldftn", "ptr ptr", FALSE);
14081         register_icall (mono_ldftn_nosync, "mono_ldftn_nosync", "ptr ptr", FALSE);
14082         register_icall (mono_ldvirtfn, "mono_ldvirtfn", "ptr object ptr", FALSE);
14083         register_icall (mono_ldvirtfn_gshared, "mono_ldvirtfn_gshared", "ptr object ptr", FALSE);
14084         register_icall (mono_helper_compile_generic_method, "compile_generic_method", "ptr object ptr ptr ptr", FALSE);
14085         register_icall (mono_helper_compile_generic_method_wo_context, "compile_generic_method_wo_context",
14086                 "ptr object ptr ptr", FALSE);
14087         register_icall (mono_helper_ldstr, "helper_ldstr", "object ptr int", FALSE);
14088         register_icall (mono_helper_ldstr_mscorlib, "helper_ldstr_mscorlib", "object int", FALSE);
14089         register_icall (mono_helper_newobj_mscorlib, "helper_newobj_mscorlib", "object int", FALSE);
14090         register_icall (mono_value_copy, "mono_value_copy", "void ptr ptr ptr", FALSE);
14091         register_icall (mono_object_castclass, "mono_object_castclass", "object object ptr", FALSE);
14092         register_icall (mono_break, "mono_break", NULL, TRUE);
14093         register_icall (mono_create_corlib_exception_0, "mono_create_corlib_exception_0", "object int", TRUE);
14094         register_icall (mono_create_corlib_exception_1, "mono_create_corlib_exception_1", "object int object", TRUE);
14095         register_icall (mono_create_corlib_exception_2, "mono_create_corlib_exception_2", "object int object object", TRUE);
14096 #endif
14097
14098 #define JIT_RUNTIME_WORKS
14099 #ifdef JIT_RUNTIME_WORKS
14100         mono_install_runtime_cleanup ((MonoDomainFunc)mini_cleanup);
14101         mono_runtime_init (domain, mono_thread_start_cb, mono_thread_attach_cb);
14102 #endif
14103
14104         mono_generic_sharing_init ();
14105
14106         mono_thread_attach (domain);
14107         
14108         MONO_PROBE_VES_INIT_END ();
14109         
14110         return domain;
14111 }
14112
14113 MonoJitStats mono_jit_stats = {0};
14114
14115 static void 
14116 print_jit_stats (void)
14117 {
14118         if (mono_jit_stats.enabled) {
14119                 g_print ("Mono Jit statistics\n");
14120                 g_print ("Compiled methods:       %ld\n", mono_jit_stats.methods_compiled);
14121                 g_print ("Methods from AOT:       %ld\n", mono_jit_stats.methods_aot);
14122                 g_print ("Methods cache lookup:   %ld\n", mono_jit_stats.methods_lookups);
14123                 g_print ("Method trampolines:     %ld\n", mono_jit_stats.method_trampolines);
14124                 g_print ("Basic blocks:           %ld\n", mono_jit_stats.basic_blocks);
14125                 g_print ("Max basic blocks:       %ld\n", mono_jit_stats.max_basic_blocks);
14126                 g_print ("Allocated vars:         %ld\n", mono_jit_stats.allocate_var);
14127                 g_print ("Analyze stack repeat:   %ld\n", mono_jit_stats.analyze_stack_repeat);
14128                 g_print ("Compiled CIL code size: %ld\n", mono_jit_stats.cil_code_size);
14129                 g_print ("Native code size:       %ld\n", mono_jit_stats.native_code_size);
14130                 g_print ("Max code size ratio:    %.2f (%s)\n", mono_jit_stats.max_code_size_ratio/100.0,
14131                                  mono_jit_stats.max_ratio_method);
14132                 g_print ("Biggest method:         %ld (%s)\n", mono_jit_stats.biggest_method_size,
14133                                  mono_jit_stats.biggest_method);
14134                 g_print ("Code reallocs:          %ld\n", mono_jit_stats.code_reallocs);
14135                 g_print ("Allocated code size:    %ld\n", mono_jit_stats.allocated_code_size);
14136                 g_print ("Inlineable methods:     %ld\n", mono_jit_stats.inlineable_methods);
14137                 g_print ("Inlined methods:        %ld\n", mono_jit_stats.inlined_methods);
14138                 g_print ("Locals stack size:      %ld\n", mono_jit_stats.locals_stack_size);
14139
14140                 g_print ("\nCreated object count:   %ld\n", mono_stats.new_object_count);
14141                 g_print ("Delegates created:      %ld\n", mono_stats.delegate_creations);
14142                 g_print ("Initialized classes:    %ld\n", mono_stats.initialized_class_count);
14143                 g_print ("Used classes:           %ld\n", mono_stats.used_class_count);
14144                 g_print ("Generic vtables:        %ld\n", mono_stats.generic_vtable_count);
14145                 g_print ("Methods:                %ld\n", mono_stats.method_count);
14146                 g_print ("Static data size:       %ld\n", mono_stats.class_static_data_size);
14147                 g_print ("VTable data size:       %ld\n", mono_stats.class_vtable_size);
14148                 g_print ("Mscorlib mempool size:  %d\n", mono_mempool_get_allocated (mono_defaults.corlib->mempool));
14149
14150                 g_print ("\nGeneric instances:      %ld\n", mono_stats.generic_instance_count);
14151                 g_print ("Initialized classes:    %ld\n", mono_stats.generic_class_count);
14152                 g_print ("Inflated methods:       %ld / %ld\n", mono_stats.inflated_method_count_2,
14153                          mono_stats.inflated_method_count);
14154                 g_print ("Inflated types:         %ld\n", mono_stats.inflated_type_count);
14155                 g_print ("Generics metadata size: %ld\n", mono_stats.generics_metadata_size);
14156                 g_print ("Generics virtual invokes: %ld\n", mono_jit_stats.generic_virtual_invocations);
14157
14158                 g_print ("Sharable generic methods: %ld\n", mono_stats.generics_sharable_methods);
14159                 g_print ("Unsharable generic methods: %ld\n", mono_stats.generics_unsharable_methods);
14160                 g_print ("Shared generic methods: %ld\n", mono_stats.generics_shared_methods);
14161
14162                 g_print ("Dynamic code allocs:    %ld\n", mono_stats.dynamic_code_alloc_count);
14163                 g_print ("Dynamic code bytes:     %ld\n", mono_stats.dynamic_code_bytes_count);
14164                 g_print ("Dynamic code frees:     %ld\n", mono_stats.dynamic_code_frees_count);
14165
14166                 g_print ("IMT tables size:        %ld\n", mono_stats.imt_tables_size);
14167                 g_print ("IMT number of tables:   %ld\n", mono_stats.imt_number_of_tables);
14168                 g_print ("IMT number of methods:  %ld\n", mono_stats.imt_number_of_methods);
14169                 g_print ("IMT used slots:         %ld\n", mono_stats.imt_used_slots);
14170                 g_print ("IMT colliding slots:    %ld\n", mono_stats.imt_slots_with_collisions);
14171                 g_print ("IMT max collisions:     %ld\n", mono_stats.imt_max_collisions_in_slot);
14172                 g_print ("IMT methods at max col: %ld\n", mono_stats.imt_method_count_when_max_collisions);
14173                 g_print ("IMT thunks size:        %ld\n", mono_stats.imt_thunks_size);
14174
14175                 g_print ("JIT info table inserts: %ld\n", mono_stats.jit_info_table_insert_count);
14176                 g_print ("JIT info table removes: %ld\n", mono_stats.jit_info_table_remove_count);
14177                 g_print ("JIT info table lookups: %ld\n", mono_stats.jit_info_table_lookup_count);
14178
14179                 g_print ("Hazardous pointers:     %ld\n", mono_stats.hazardous_pointer_count);
14180 #ifdef HAVE_SGEN_GC
14181                 g_print ("Minor GC collections:   %ld\n", mono_stats.minor_gc_count);
14182                 g_print ("Major GC collections:   %ld\n", mono_stats.major_gc_count);
14183                 g_print ("Minor GC time in msecs: %lf\n", (double)mono_stats.minor_gc_time_usecs / 1000.0);
14184                 g_print ("Major GC time in msecs: %lf\n", (double)mono_stats.major_gc_time_usecs / 1000.0);
14185 #endif
14186                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
14187                         g_print ("\nDecl security check   : %ld\n", mono_jit_stats.cas_declsec_check);
14188                         g_print ("LinkDemand (user)     : %ld\n", mono_jit_stats.cas_linkdemand);
14189                         g_print ("LinkDemand (icall)    : %ld\n", mono_jit_stats.cas_linkdemand_icall);
14190                         g_print ("LinkDemand (pinvoke)  : %ld\n", mono_jit_stats.cas_linkdemand_pinvoke);
14191                         g_print ("LinkDemand (aptc)     : %ld\n", mono_jit_stats.cas_linkdemand_aptc);
14192                         g_print ("Demand (code gen)     : %ld\n", mono_jit_stats.cas_demand_generation);
14193                 }
14194                 if (debug_options.collect_pagefault_stats) {
14195                         g_print ("Metadata pagefaults   : %d\n", mono_raw_buffer_get_n_pagefaults ());
14196                         g_print ("AOT pagefaults        : %d\n", mono_aot_get_n_pagefaults ());
14197                 }
14198
14199                 g_free (mono_jit_stats.max_ratio_method);
14200                 mono_jit_stats.max_ratio_method = NULL;
14201                 g_free (mono_jit_stats.biggest_method);
14202                 mono_jit_stats.biggest_method = NULL;
14203         }
14204 }
14205
14206 void
14207 mini_cleanup (MonoDomain *domain)
14208 {
14209 #ifdef HAVE_LINUX_RTC_H
14210         if (rtc_fd >= 0)
14211                 enable_rtc_timer (FALSE);
14212 #endif
14213
14214         /* 
14215          * mono_runtime_cleanup() and mono_domain_finalize () need to
14216          * be called early since they need the execution engine still
14217          * fully working (mono_domain_finalize may invoke managed finalizers
14218          * and mono_runtime_cleanup will wait for other threads to finish).
14219          */
14220         mono_domain_finalize (domain, 2000);
14221
14222         /* This accesses metadata so needs to be called before runtime shutdown */
14223         print_jit_stats ();
14224
14225         mono_runtime_cleanup (domain);
14226
14227         mono_profiler_shutdown ();
14228
14229         mono_icall_cleanup ();
14230
14231         mono_runtime_cleanup_handlers ();
14232
14233         mono_domain_free (domain, TRUE);
14234
14235         mono_debugger_cleanup ();
14236
14237         mono_trampolines_cleanup ();
14238
14239         mono_code_manager_destroy (global_codeman);
14240         g_hash_table_destroy (jit_icall_name_hash);
14241         g_free (emul_opcode_map);
14242
14243         mono_arch_cleanup ();
14244
14245         mono_cleanup ();
14246
14247         mono_trace_cleanup ();
14248
14249         mono_counters_dump (-1, stdout);
14250
14251         if (mono_inject_async_exc_method)
14252                 mono_method_desc_free (mono_inject_async_exc_method);
14253
14254         TlsFree(mono_jit_tls_id);
14255
14256         DeleteCriticalSection (&jit_mutex);
14257
14258         DeleteCriticalSection (&mono_delegate_section);
14259 }
14260
14261 void
14262 mono_set_defaults (int verbose_level, guint32 opts)
14263 {
14264         mini_verbose = verbose_level;
14265         default_opt = opts;
14266         default_opt_set = TRUE;
14267 }
14268
14269 static void
14270 mono_precompile_assembly (MonoAssembly *ass, void *user_data)
14271 {
14272         GHashTable *assemblies = (GHashTable*)user_data;
14273         MonoImage *image = mono_assembly_get_image (ass);
14274         MonoMethod *method, *invoke;
14275         int i, count = 0;
14276
14277         if (g_hash_table_lookup (assemblies, ass))
14278                 return;
14279
14280         g_hash_table_insert (assemblies, ass, ass);
14281
14282         if (mini_verbose > 0)
14283                 printf ("PRECOMPILE: %s.\n", mono_image_get_filename (image));
14284
14285         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
14286                 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
14287                 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
14288                         continue;
14289
14290                 count++;
14291                 if (mini_verbose > 1) {
14292                         char * desc = mono_method_full_name (method, TRUE);
14293                         g_print ("Compiling %d %s\n", count, desc);
14294                         g_free (desc);
14295                 }
14296                 mono_compile_method (method);
14297                 if (strcmp (method->name, "Finalize") == 0) {
14298                         invoke = mono_marshal_get_runtime_invoke (method);
14299                         mono_compile_method (invoke);
14300                 }
14301                 if (method->klass->marshalbyref && mono_method_signature (method)->hasthis) {
14302                         invoke = mono_marshal_get_remoting_invoke_with_check (method);
14303                         mono_compile_method (invoke);
14304                 }
14305         }
14306
14307         /* Load and precompile referenced assemblies as well */
14308         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_ASSEMBLYREF); ++i) {
14309                 mono_assembly_load_reference (image, i);
14310                 if (image->references [i])
14311                         mono_precompile_assembly (image->references [i], assemblies);
14312         }
14313 }
14314
14315 void mono_precompile_assemblies ()
14316 {
14317         GHashTable *assemblies = g_hash_table_new (NULL, NULL);
14318
14319         mono_assembly_foreach ((GFunc)mono_precompile_assembly, assemblies);
14320
14321         g_hash_table_destroy (assemblies);
14322 }