2008-05-19 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mono / mini / mini.c
1 /*
2  * mini.c: The new Mono code generator.
3  *
4  * Author:
5  *   Paolo Molaro (lupus@ximian.com)
6  *   Dietmar Maurer (dietmar@ximian.com)
7  *
8  * (C) 2002 Ximian, Inc.
9  */
10
11 #include <config.h>
12 #include <signal.h>
13 #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
68 #include "mini.h"
69 #include <string.h>
70 #include <ctype.h>
71 #include "inssel.h"
72 #include "trace.h"
73
74 #include "jit-icalls.h"
75
76 #include "aliasing.h"
77
78 #include "debug-mini.h"
79
80 #define BRANCH_COST 100
81 #define INLINE_LENGTH_LIMIT 20
82 #define INLINE_FAILURE do {\
83                 if ((cfg->method != method) && (method->wrapper_type == MONO_WRAPPER_NONE))\
84                         goto inline_failure;\
85         } while (0)
86 #define CHECK_CFG_EXCEPTION do {\
87                 if (cfg->exception_type != MONO_EXCEPTION_NONE)\
88                         goto exception_exit;\
89         } while (0)
90 #define METHOD_ACCESS_FAILURE do {      \
91                 char *method_fname = mono_method_full_name (method, TRUE);      \
92                 char *cil_method_fname = mono_method_full_name (cil_method, TRUE);      \
93                 cfg->exception_type = MONO_EXCEPTION_METHOD_ACCESS;     \
94                 cfg->exception_message = g_strdup_printf ("Method `%s' is inaccessible from method `%s'\n", cil_method_fname, method_fname);    \
95                 g_free (method_fname);  \
96                 g_free (cil_method_fname);      \
97                 goto exception_exit;    \
98         } while (0)
99 #define FIELD_ACCESS_FAILURE do {       \
100                 char *method_fname = mono_method_full_name (method, TRUE);      \
101                 char *field_fname = mono_field_full_name (field);       \
102                 cfg->exception_type = MONO_EXCEPTION_FIELD_ACCESS;      \
103                 cfg->exception_message = g_strdup_printf ("Field `%s' is inaccessible from method `%s'\n", field_fname, method_fname);  \
104                 g_free (method_fname);  \
105                 g_free (field_fname);   \
106                 goto exception_exit;    \
107         } while (0)
108 #define GENERIC_SHARING_FAILURE(opcode) do {            \
109                 if (cfg->generic_sharing_context) {     \
110             if (cfg->verbose_level > 1) \
111                             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__); \
112                         cfg->exception_type = MONO_EXCEPTION_GENERIC_SHARING_FAILED;    \
113                         goto exception_exit;    \
114                 }                       \
115         } while (0)
116 #define GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD(opcode) do {                        \
117                 if (method->klass->valuetype)   \
118                         GENERIC_SHARING_FAILURE ((opcode)); \
119         } while (0)
120 #define GET_RGCTX(rgctx) do {                                           \
121                 MonoInst *this = NULL;                                  \
122                 GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD(*ip);       \
123                 if (!(method->flags & METHOD_ATTRIBUTE_STATIC))         \
124                         NEW_ARGLOAD (cfg, this, 0);                     \
125                 (rgctx) = get_runtime_generic_context (cfg, method, this, ip); \
126         } while (0)
127
128 #define MONO_CHECK_THIS(ins) (mono_method_signature (cfg->method)->hasthis && (ins)->ssa_op == MONO_SSA_LOAD && (ins)->inst_left->inst_c0 == 0)
129
130 static void setup_stat_profiler (void);
131 gboolean  mono_arch_print_tree(MonoInst *tree, int arity);
132 static gpointer mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt);
133 static gpointer mono_jit_compile_method (MonoMethod *method);
134 inline static int mono_emit_jit_icall (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoInst **args, const guint8 *ip);
135
136 static void handle_stobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, MonoInst *src, 
137                           const unsigned char *ip, MonoClass *klass, gboolean to_end, gboolean native, gboolean write_barrier);
138
139 static void dec_foreach (MonoInst *tree, MonoCompile *cfg);
140
141 static int mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
142                    int locals_offset, MonoInst *return_var, GList *dont_inline, MonoInst **inline_args, 
143                    guint inline_offset, gboolean is_virtual_call);
144
145 #ifdef MONO_ARCH_SOFT_FLOAT
146 static void
147 handle_store_float (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ptr, MonoInst *val, const unsigned char *ip);
148 #endif
149
150 /* helper methods signature */
151 static MonoMethodSignature *helper_sig_class_init_trampoline = NULL;
152 static MonoMethodSignature *helper_sig_generic_class_init_trampoline = NULL;
153 static MonoMethodSignature *helper_sig_rgctx_lazy_fetch_trampoline = NULL;
154 static MonoMethodSignature *helper_sig_domain_get = NULL;
155
156 static guint32 default_opt = 0;
157 static gboolean default_opt_set = FALSE;
158
159 guint32 mono_jit_tls_id = -1;
160
161 #ifdef HAVE_KW_THREAD
162 static __thread gpointer mono_jit_tls MONO_TLS_FAST;
163 #endif
164
165 MonoTraceSpec *mono_jit_trace_calls = NULL;
166 gboolean mono_break_on_exc = FALSE;
167 #ifndef DISABLE_AOT
168 gboolean mono_compile_aot = FALSE;
169 #endif
170 MonoMethodDesc *mono_inject_async_exc_method = NULL;
171 int mono_inject_async_exc_pos;
172 MonoMethodDesc *mono_break_at_bb_method = NULL;
173 int mono_break_at_bb_bb_num;
174
175 static int mini_verbose = 0;
176
177 #define mono_jit_lock() EnterCriticalSection (&jit_mutex)
178 #define mono_jit_unlock() LeaveCriticalSection (&jit_mutex)
179 static CRITICAL_SECTION jit_mutex;
180
181 static GHashTable *rgctx_lazy_fetch_trampoline_hash = NULL;
182
183 static MonoCodeManager *global_codeman = NULL;
184
185 static GHashTable *jit_icall_name_hash = NULL;
186
187 static MonoDebugOptions debug_options;
188
189 #ifdef VALGRIND_JIT_REGISTER_MAP
190 static int valgrind_register = 0;
191 #endif
192
193 /*
194  * Table written to by the debugger with a 1-based index into the
195  * mono_breakpoint_info table, which contains changes made to
196  * the JIT instructions by the debugger.
197  */
198 gssize
199 mono_breakpoint_info_index [MONO_BREAKPOINT_ARRAY_SIZE];
200
201 /* Whenever to check for pending exceptions in managed-to-native wrappers */
202 gboolean check_for_pending_exc = TRUE;
203
204 gboolean
205 mono_running_on_valgrind (void)
206 {
207 #ifdef HAVE_VALGRIND_MEMCHECK_H
208                 if (RUNNING_ON_VALGRIND){
209 #ifdef VALGRIND_JIT_REGISTER_MAP
210                         valgrind_register = TRUE;
211 #endif
212                         return TRUE;
213                 } else
214                         return FALSE;
215 #else
216                 return FALSE;
217 #endif
218 }
219
220 typedef struct {
221         void *ip;
222         MonoMethod *method;
223 } FindTrampUserData;
224
225 static void
226 find_tramp (gpointer key, gpointer value, gpointer user_data)
227 {
228         FindTrampUserData *ud = (FindTrampUserData*)user_data;
229
230         if (value == ud->ip)
231                 ud->method = (MonoMethod*)key;
232 }
233
234 /* debug function */
235 G_GNUC_UNUSED static char*
236 get_method_from_ip (void *ip)
237 {
238         MonoJitInfo *ji;
239         char *method;
240         char *res;
241         MonoDomain *domain = mono_domain_get ();
242         MonoDebugSourceLocation *location;
243         FindTrampUserData user_data;
244         
245         ji = mono_jit_info_table_find (domain, ip);
246         if (!ji) {
247                 user_data.ip = ip;
248                 user_data.method = NULL;
249                 mono_domain_lock (domain);
250                 g_hash_table_foreach (domain->jit_trampoline_hash, find_tramp, &user_data);
251                 mono_domain_unlock (domain);
252                 if (user_data.method) {
253                         char *mname = mono_method_full_name (user_data.method, TRUE);
254                         res = g_strdup_printf ("<%p - JIT trampoline for %s>", ip, mname);
255                         g_free (mname);
256                         return res;
257                 }
258                 else
259                         return NULL;
260         }
261         method = mono_method_full_name (ji->method, TRUE);
262         /* FIXME: unused ? */
263         location = mono_debug_lookup_source_location (ji->method, (guint32)((guint8*)ip - (guint8*)ji->code_start), domain);
264
265         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);
266
267         mono_debug_free_source_location (location);
268         g_free (method);
269
270         return res;
271 }
272
273 /** 
274  * mono_pmip:
275  * @ip: an instruction pointer address
276  *
277  * This method is used from a debugger to get the name of the
278  * method at address @ip.   This routine is typically invoked from
279  * a debugger like this:
280  *
281  * (gdb) print mono_pmip ($pc)
282  *
283  * Returns: the name of the method at address @ip.
284  */
285 G_GNUC_UNUSED char *
286 mono_pmip (void *ip)
287 {
288         return get_method_from_ip (ip);
289 }
290
291 /** 
292  * mono_print_method_from_ip
293  * @ip: an instruction pointer address
294  *
295  * This method is used from a debugger to get the name of the
296  * method at address @ip.
297  *
298  * This prints the name of the method at address @ip in the standard
299  * output.  Unlike mono_pmip which returns a string, this routine
300  * prints the value on the standard output. 
301  */
302 void
303 mono_print_method_from_ip (void *ip)
304 {
305         MonoJitInfo *ji;
306         char *method;
307         MonoDebugSourceLocation *source;
308         MonoDomain *domain = mono_domain_get ();
309         FindTrampUserData user_data;
310         
311         ji = mono_jit_info_table_find (domain, ip);
312         if (!ji) {
313                 user_data.ip = ip;
314                 user_data.method = NULL;
315                 mono_domain_lock (domain);
316                 g_hash_table_foreach (domain->jit_trampoline_hash, find_tramp, &user_data);
317                 mono_domain_unlock (domain);
318                 if (user_data.method) {
319                         char *mname = mono_method_full_name (user_data.method, TRUE);
320                         printf ("IP %p is a JIT trampoline for %s\n", ip, mname);
321                         g_free (mname);
322                 }
323                 else
324                         g_print ("No method at %p\n", ip);
325                 return;
326         }
327         method = mono_method_full_name (ji->method, TRUE);
328         source = mono_debug_lookup_source_location (ji->method, (guint32)((guint8*)ip - (guint8*)ji->code_start), domain);
329
330         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);
331
332         if (source)
333                 g_print ("%s:%d\n", source->source_file, source->row);
334
335         mono_debug_free_source_location (source);
336         g_free (method);
337 }
338         
339 /* 
340  * mono_method_same_domain:
341  *
342  * Determine whenever two compiled methods are in the same domain, thus
343  * the address of the callee can be embedded in the caller.
344  */
345 gboolean mono_method_same_domain (MonoJitInfo *caller, MonoJitInfo *callee)
346 {
347         if (!caller || !callee)
348                 return FALSE;
349
350         /*
351          * If the call was made from domain-neutral to domain-specific 
352          * code, we can't patch the call site.
353          */
354         if (caller->domain_neutral && !callee->domain_neutral)
355                 return FALSE;
356
357         if ((caller->method->klass == mono_defaults.appdomain_class) &&
358                 (strstr (caller->method->name, "InvokeInDomain"))) {
359                  /* The InvokeInDomain methods change the current appdomain */
360                 return FALSE;
361         }
362
363         return TRUE;
364 }
365
366 /*
367  * mono_global_codeman_reserve:
368  *
369  *  Allocate code memory from the global code manager.
370  */
371 void *mono_global_codeman_reserve (int size)
372 {
373         void *ptr;
374
375         if (!global_codeman) {
376                 /* This can happen during startup */
377                 global_codeman = mono_code_manager_new ();
378                 return mono_code_manager_reserve (global_codeman, size);
379         }
380         else {
381                 mono_jit_lock ();
382                 ptr = mono_code_manager_reserve (global_codeman, size);
383                 mono_jit_unlock ();
384                 return ptr;
385         }
386 }
387
388 MonoJumpInfoToken *
389 mono_jump_info_token_new (MonoMemPool *mp, MonoImage *image, guint32 token)
390 {
391         MonoJumpInfoToken *res = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoToken));
392         res->image = image;
393         res->token = token;
394
395         return res;
396 }
397
398 #define MONO_INIT_VARINFO(vi,id) do { \
399         (vi)->range.first_use.pos.bid = 0xffff; \
400         (vi)->reg = -1; \
401         (vi)->idx = (id); \
402 } while (0)
403
404 //#define UNVERIFIED do { G_BREAKPOINT (); goto unverified; } while (0)
405 #define UNVERIFIED do { if (debug_options.break_on_unverified) G_BREAKPOINT (); else goto unverified; } while (0)
406
407 /*
408  * Basic blocks have two numeric identifiers:
409  * dfn: Depth First Number
410  * block_num: unique ID assigned at bblock creation
411  */
412 #define NEW_BBLOCK(cfg,new_bb) do {     \
413                 new_bb = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock)); \
414                 MONO_INST_LIST_INIT (&new_bb->ins_list); \
415         } while (0)
416
417 #define ADD_BBLOCK(cfg,b) do {  \
418                 cfg->cil_offset_to_bb [(b)->cil_code - cfg->cil_start] = (b);   \
419                 (b)->block_num = cfg->num_bblocks++;    \
420                 (b)->real_offset = real_offset; \
421         } while (0)
422
423 #define GET_BBLOCK(cfg,tblock,ip) do {  \
424                 (tblock) = cfg->cil_offset_to_bb [(ip) - cfg->cil_start]; \
425                 if (!(tblock)) {        \
426                         if ((ip) >= end || (ip) < header->code) UNVERIFIED; \
427                         NEW_BBLOCK (cfg, (tblock));     \
428                         (tblock)->cil_code = (ip);      \
429                         ADD_BBLOCK (cfg, (tblock));     \
430                 } \
431         } while (0)
432
433 #define CHECK_BBLOCK(target,ip,tblock) do {     \
434                 if ((target) < (ip) && \
435                                 MONO_INST_LIST_EMPTY (&(tblock)->ins_list)) { \
436                         bb_recheck = g_list_prepend (bb_recheck, (tblock)); \
437                         if (cfg->verbose_level > 2) \
438                                 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)); \
439                 } \
440         } while (0)
441
442 #define NEW_ICONST(cfg,dest,val) do {   \
443                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
444                 (dest)->opcode = OP_ICONST;     \
445                 (dest)->inst_c0 = (val);        \
446                 (dest)->type = STACK_I4;        \
447         } while (0)
448
449 #define NEW_PCONST(cfg,dest,val) do {   \
450                 MONO_INST_NEW ((cfg), (dest), OP_PCONST);       \
451                 (dest)->inst_p0 = (val);        \
452                 (dest)->type = STACK_PTR;       \
453         } while (0)
454
455
456 #ifdef MONO_ARCH_NEED_GOT_VAR
457
458 #define NEW_PATCH_INFO(cfg,dest,el1,el2) do {   \
459                 MONO_INST_NEW ((cfg), (dest), OP_PATCH_INFO);   \
460                 (dest)->inst_left = (gpointer)(el1);    \
461                 (dest)->inst_right = (gpointer)(el2);   \
462         } while (0)
463
464 #define NEW_AOTCONST(cfg,dest,patch_type,cons) do {                     \
465                 MONO_INST_NEW ((cfg), (dest), OP_NOP); \
466                 (dest)->opcode = cfg->compile_aot ? OP_GOT_ENTRY : OP_PCONST; \
467                 if (cfg->compile_aot) {                                 \
468                         MonoInst *group, *got_var, *got_loc;            \
469                         got_loc = mono_get_got_var (cfg);               \
470                         NEW_TEMPLOAD ((cfg), got_var, got_loc->inst_c0); \
471                         NEW_PATCH_INFO ((cfg), group, cons, patch_type); \
472                         (dest)->inst_p0 = got_var;                      \
473                         (dest)->inst_p1 = group;                        \
474                 } else {                                                \
475                         (dest)->inst_p0 = (cons);                       \
476                         (dest)->inst_i1 = (gpointer)(patch_type);       \
477                 }                                                       \
478                 (dest)->type = STACK_PTR;                               \
479         } while (0)
480
481 #define NEW_AOTCONST_TOKEN(cfg,dest,patch_type,image,token,stack_type,stack_class) do { \
482                 MonoInst *group, *got_var, *got_loc;                    \
483                 MONO_INST_NEW ((cfg), (dest), OP_GOT_ENTRY); \
484                 got_loc = mono_get_got_var (cfg);                       \
485                 NEW_TEMPLOAD ((cfg), got_var, got_loc->inst_c0);        \
486                 NEW_PATCH_INFO ((cfg), group, NULL, patch_type);        \
487                 group->inst_p0 = mono_jump_info_token_new ((cfg)->mempool, (image), (token)); \
488                 (dest)->inst_p0 = got_var;                              \
489                 (dest)->inst_p1 = group;                                \
490                 (dest)->type = (stack_type);                    \
491         (dest)->klass = (stack_class);          \
492         } while (0)
493
494 #else
495
496 #define NEW_AOTCONST(cfg,dest,patch_type,cons) do {    \
497                 MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
498                 (dest)->opcode = cfg->compile_aot ? OP_AOTCONST : OP_PCONST;    \
499                 (dest)->inst_p0 = (cons);       \
500                 (dest)->inst_i1 = (gpointer)(patch_type); \
501                 (dest)->type = STACK_PTR;       \
502     } while (0)
503
504 #define NEW_AOTCONST_TOKEN(cfg,dest,patch_type,image,token,stack_type,stack_class) do { \
505                 MONO_INST_NEW ((cfg), (dest), OP_AOTCONST);     \
506                 (dest)->inst_p0 = mono_jump_info_token_new ((cfg)->mempool, (image), (token));  \
507                 (dest)->inst_p1 = (gpointer)(patch_type); \
508                 (dest)->type = (stack_type);    \
509         (dest)->klass = (stack_class);          \
510     } while (0)
511
512 #endif
513
514 #define NEW_CLASSCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_CLASS, (val))
515
516 #define NEW_IMAGECONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_IMAGE, (val))
517
518 #define NEW_FIELDCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_FIELD, (val))
519
520 #define NEW_METHODCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_METHODCONST, (val))
521
522 #define NEW_VTABLECONST(cfg,dest,vtable) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_VTABLE, cfg->compile_aot ? (gpointer)((vtable)->klass) : (vtable))
523
524 #define NEW_SFLDACONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_SFLDA, (val))
525
526 #define NEW_LDSTRCONST(cfg,dest,image,token) NEW_AOTCONST_TOKEN ((cfg), (dest), MONO_PATCH_INFO_LDSTR, (image), (token), STACK_OBJ, mono_defaults.string_class)
527
528 #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)
529
530 #define NEW_LDTOKENCONST(cfg,dest,image,token) NEW_AOTCONST_TOKEN ((cfg), (dest), MONO_PATCH_INFO_LDTOKEN, (image), (token), STACK_PTR, NULL)
531
532 #define NEW_DECLSECCONST(cfg,dest,image,entry) do { \
533                 if (cfg->compile_aot) { \
534                         NEW_AOTCONST_TOKEN (cfg, dest, MONO_PATCH_INFO_DECLSEC, image, (entry).index, STACK_OBJ, NULL); \
535                 } else { \
536                         NEW_PCONST (cfg, args [0], (entry).blob); \
537                 } \
538         } while (0)
539
540 #define NEW_DOMAINCONST(cfg,dest) do { \
541                 if (cfg->opt & MONO_OPT_SHARED) { \
542                         /* avoid depending on undefined C behavior in sequence points */ \
543                         MonoInst* __domain_var = mono_get_domainvar (cfg); \
544                         NEW_TEMPLOAD (cfg, dest, __domain_var->inst_c0); \
545                 } else { \
546                         NEW_PCONST (cfg, dest, (cfg)->domain); \
547                 } \
548         } while (0)
549
550 #define GET_VARINFO_INST(cfg,num) ((cfg)->varinfo [(num)]->inst)
551
552 #define NEW_ARGLOAD(cfg,dest,num) do {  \
553                 if (arg_array [(num)]->opcode == OP_ICONST) (dest) = arg_array [(num)]; else { \
554                 MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
555                 (dest)->ssa_op = MONO_SSA_LOAD; \
556                 (dest)->inst_i0 = arg_array [(num)];    \
557                 (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
558                 type_to_eval_stack_type ((cfg), param_types [(num)], (dest));   \
559                 (dest)->klass = (dest)->inst_i0->klass; \
560         }} while (0)
561
562 #define NEW_LOCLOAD(cfg,dest,num) do {  \
563                 MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
564                 (dest)->ssa_op = MONO_SSA_LOAD; \
565                 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)];       \
566                 (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
567                 type_to_eval_stack_type ((cfg), header->locals [(num)], (dest));        \
568                 (dest)->klass = (dest)->inst_i0->klass; \
569         } while (0)
570
571 #define NEW_LOCLOADA(cfg,dest,num) do { \
572                 MONO_INST_NEW ((cfg), (dest), OP_LDADDR);       \
573                 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN;        \
574                 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)];       \
575                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
576                 (dest)->type = STACK_MP;        \
577                 (dest)->klass = (dest)->inst_i0->klass; \
578         if (!MONO_TYPE_ISSTRUCT (header->locals [(num)])) \
579            (cfg)->disable_ssa = TRUE; \
580         } while (0)
581
582 #define NEW_RETLOADA(cfg,dest) do {     \
583         if (cfg->vret_addr) { \
584                     MONO_INST_NEW ((cfg), (dest), OP_NOP);      \
585                     (dest)->ssa_op = MONO_SSA_LOAD;     \
586                     (dest)->inst_i0 = cfg->vret_addr; \
587                     (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
588             (dest)->type = STACK_MP; \
589                     (dest)->klass = (dest)->inst_i0->klass;     \
590         } else { \
591                         MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
592                     (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN;    \
593                     (dest)->inst_i0 = (cfg)->ret;       \
594                     (dest)->inst_i0->flags |= MONO_INST_INDIRECT;       \
595                     (dest)->opcode = cfg->ret_var_is_local ? OP_LDADDR : CEE_LDIND_I;   \
596                     (dest)->type = STACK_MP;    \
597                     (dest)->klass = (dest)->inst_i0->klass;     \
598             (cfg)->disable_ssa = TRUE; \
599         } \
600         } while (0)
601
602 #define NEW_ARGLOADA(cfg,dest,num) do { \
603                 if (arg_array [(num)]->opcode == OP_ICONST) goto inline_failure; \
604                 MONO_INST_NEW ((cfg), (dest), OP_LDADDR);       \
605                 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN;        \
606                 (dest)->inst_i0 = arg_array [(num)];    \
607                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
608                 (dest)->type = STACK_MP;        \
609                 (dest)->klass = (dest)->inst_i0->klass; \
610                 (cfg)->disable_ssa = TRUE; \
611         } while (0)
612
613 #define NEW_TEMPLOAD(cfg,dest,num) do { \
614                 MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
615                 (dest)->ssa_op = MONO_SSA_LOAD; \
616                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
617                 (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
618                 type_to_eval_stack_type ((cfg), (dest)->inst_i0->inst_vtype, (dest));   \
619                 (dest)->klass = (dest)->inst_i0->klass; \
620         } while (0)
621
622 #define NEW_TEMPLOADA(cfg,dest,num) do {        \
623                 MONO_INST_NEW ((cfg), (dest), OP_LDADDR);       \
624                 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN;        \
625                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
626                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
627                 (dest)->type = STACK_MP;        \
628                 (dest)->klass = (dest)->inst_i0->klass; \
629         if (!MONO_TYPE_ISSTRUCT (cfg->varinfo [(num)]->inst_vtype)) \
630            (cfg)->disable_ssa = TRUE; \
631         } while (0)
632
633
634 #define NEW_INDLOAD(cfg,dest,addr,vtype) do {   \
635                 MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
636                 (dest)->inst_left = addr;       \
637                 (dest)->opcode = mini_type_to_ldind ((cfg), vtype);     \
638                 type_to_eval_stack_type ((cfg), vtype, (dest)); \
639                 /* FIXME: (dest)->klass = (dest)->inst_i0->klass;*/     \
640         } while (0)
641
642 #define NEW_INDSTORE(cfg,dest,addr,value,vtype) do {    \
643                 MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
644                 (dest)->inst_i0 = addr; \
645                 (dest)->opcode = mini_type_to_stind ((cfg), vtype);     \
646                 (dest)->inst_i1 = (value);      \
647                 /* FIXME: (dest)->klass = (dest)->inst_i0->klass;*/     \
648         } while (0)
649
650 #define NEW_TEMPSTORE(cfg,dest,num,inst) do {   \
651                 MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
652                 (dest)->ssa_op = MONO_SSA_STORE;        \
653                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
654                 (dest)->opcode = mini_type_to_stind ((cfg), (dest)->inst_i0->inst_vtype); \
655                 (dest)->inst_i1 = (inst);       \
656                 (dest)->klass = (dest)->inst_i0->klass; \
657         } while (0)
658
659 #define NEW_LOCSTORE(cfg,dest,num,inst) do {    \
660                 MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
661                 (dest)->opcode = mini_type_to_stind ((cfg), header->locals [(num)]); \
662                 (dest)->ssa_op = MONO_SSA_STORE;        \
663                 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)];       \
664                 (dest)->inst_i1 = (inst);       \
665                 (dest)->klass = (dest)->inst_i0->klass; \
666         } while (0)
667
668 #define NEW_ARGSTORE(cfg,dest,num,inst) do {    \
669                 if (arg_array [(num)]->opcode == OP_ICONST) goto inline_failure; \
670                 MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
671                 (dest)->opcode = mini_type_to_stind ((cfg), param_types [(num)]); \
672                 (dest)->ssa_op = MONO_SSA_STORE;        \
673                 (dest)->inst_i0 = arg_array [(num)];    \
674                 (dest)->inst_i1 = (inst);       \
675                 (dest)->klass = (dest)->inst_i0->klass; \
676         } while (0)
677
678 #define NEW_MEMCPY(cfg,dest,dst,src,memcpy_size,memcpy_align) do { \
679                 MONO_INST_NEW (cfg, dest, OP_MEMCPY); \
680         (dest)->inst_left = (dst); \
681                 (dest)->inst_right = (src); \
682                 (dest)->cil_code = ip; \
683         (dest)->backend.memcpy_args = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoMemcpyArgs)); \
684                 (dest)->backend.memcpy_args->size = (memcpy_size); \
685                 (dest)->backend.memcpy_args->align = (memcpy_align); \
686     } while (0)
687
688 #define NEW_MEMSET(cfg,dest,dst,imm,memcpy_size,memcpy_align) do { \
689                 MONO_INST_NEW (cfg, dest, OP_MEMSET); \
690         (dest)->inst_left = (dst); \
691                 (dest)->inst_imm = (imm); \
692                 (dest)->cil_code = ip; \
693         (dest)->backend.memcpy_args = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoMemcpyArgs)); \
694                 (dest)->backend.memcpy_args->size = (memcpy_size); \
695                 (dest)->backend.memcpy_args->align = (memcpy_align); \
696     } while (0)
697
698 #define NEW_DUMMY_USE(cfg,dest,load) do { \
699                 MONO_INST_NEW ((cfg), (dest), OP_DUMMY_USE);    \
700                 (dest)->inst_left = (load); \
701     } while (0)
702
703 #define NEW_DUMMY_STORE(cfg,dest,num) do { \
704                 MONO_INST_NEW ((cfg), (dest), OP_DUMMY_STORE);  \
705                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
706                 (dest)->klass = (dest)->inst_i0->klass; \
707         } while (0)
708
709 #define ADD_BINOP(op) do {      \
710                 MONO_INST_NEW (cfg, ins, (op)); \
711                 ins->cil_code = ip;     \
712                 sp -= 2;        \
713                 ins->inst_i0 = sp [0];  \
714                 ins->inst_i1 = sp [1];  \
715                 *sp++ = ins;    \
716                 type_from_op (ins);     \
717                 CHECK_TYPE (ins);       \
718         } while (0)
719
720 #define ADD_UNOP(op) do {       \
721                 MONO_INST_NEW (cfg, ins, (op)); \
722                 ins->cil_code = ip;     \
723                 sp--;   \
724                 ins->inst_i0 = sp [0];  \
725                 *sp++ = ins;    \
726                 type_from_op (ins);     \
727                 CHECK_TYPE (ins);       \
728         } while (0)
729
730 #define ADD_BINCOND(next_block) do {    \
731                 MonoInst *cmp;  \
732                 sp -= 2;                \
733                 MONO_INST_NEW(cfg, cmp, OP_COMPARE);    \
734                 cmp->inst_i0 = sp [0];  \
735                 cmp->inst_i1 = sp [1];  \
736                 cmp->cil_code = ins->cil_code;  \
737                 type_from_op (cmp);     \
738                 CHECK_TYPE (cmp);       \
739                 ins->inst_i0 = cmp;     \
740                 MONO_ADD_INS (bblock, ins);     \
741                 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);      \
742                 GET_BBLOCK (cfg, tblock, target);               \
743                 link_bblock (cfg, bblock, tblock);      \
744                 ins->inst_true_bb = tblock;     \
745                 CHECK_BBLOCK (target, ip, tblock);      \
746                 if ((next_block)) {     \
747                         link_bblock (cfg, bblock, (next_block));        \
748                         ins->inst_false_bb = (next_block);      \
749                         start_new_bblock = 1;   \
750                 } else {        \
751                         GET_BBLOCK (cfg, tblock, ip);           \
752                         link_bblock (cfg, bblock, tblock);      \
753                         ins->inst_false_bb = tblock;    \
754                         start_new_bblock = 2;   \
755                 }       \
756         } while (0)
757
758 /* FIXME: handle float, long ... */
759 #define ADD_UNCOND(istrue) do { \
760                 MonoInst *cmp;  \
761                 sp--;           \
762                 MONO_INST_NEW(cfg, cmp, OP_COMPARE);    \
763                 cmp->inst_i0 = sp [0];  \
764                 switch (cmp->inst_i0->type) { \
765                 case STACK_I8: \
766                         cmp->inst_i1 = zero_int64; break; \
767                 case STACK_R8: \
768                         cmp->inst_i1 = zero_r8; break; \
769                 case STACK_PTR: \
770                 case STACK_MP: \
771                         cmp->inst_i1 = zero_ptr; break; \
772                 case STACK_OBJ: \
773                         cmp->inst_i1 = zero_obj; break; \
774                 default: \
775                         cmp->inst_i1 = zero_int32;  \
776                 }  \
777                 cmp->cil_code = ins->cil_code;  \
778                 type_from_op (cmp);     \
779                 CHECK_TYPE (cmp);       \
780                 ins->inst_i0 = cmp;     \
781                 ins->opcode = (istrue)? CEE_BNE_UN: CEE_BEQ;    \
782                 MONO_ADD_INS (bblock, ins);     \
783                 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);      \
784                 GET_BBLOCK (cfg, tblock, target);               \
785                 link_bblock (cfg, bblock, tblock);      \
786                 ins->inst_true_bb = tblock;     \
787                 CHECK_BBLOCK (target, ip, tblock);      \
788                 GET_BBLOCK (cfg, tblock, ip);           \
789                 link_bblock (cfg, bblock, tblock);      \
790                 ins->inst_false_bb = tblock;    \
791                 start_new_bblock = 2;   \
792         } while (0)
793
794 #define NEW_LDELEMA(cfg,dest,sp,k) do { \
795                 MONO_INST_NEW ((cfg), (dest), CEE_LDELEMA);     \
796                 (dest)->inst_left = (sp) [0];   \
797                 (dest)->inst_right = (sp) [1];  \
798                 (dest)->type = STACK_MP;        \
799                 (dest)->klass = (k);    \
800                 (cfg)->flags |= MONO_CFG_HAS_LDELEMA; \
801         } while (0)
802
803 #define NEW_GROUP(cfg,dest,el1,el2) do {        \
804                 MONO_INST_NEW ((cfg), (dest), OP_GROUP);        \
805                 (dest)->inst_left = (el1);      \
806                 (dest)->inst_right = (el2);     \
807         } while (0)
808
809 #if 0
810 static gint
811 compare_bblock (gconstpointer a, gconstpointer b)
812 {
813         const MonoBasicBlock *b1 = a;
814         const MonoBasicBlock *b2 = b;
815
816         return b2->cil_code - b1->cil_code;
817 }
818 #endif
819
820 /* *
821  * link_bblock: Links two basic blocks
822  *
823  * links two basic blocks in the control flow graph, the 'from'
824  * argument is the starting block and the 'to' argument is the block
825  * the control flow ends to after 'from'.
826  */
827 static void
828 link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
829 {
830         MonoBasicBlock **newa;
831         int i, found;
832
833 #if 0
834         if (from->cil_code) {
835                 if (to->cil_code)
836                         g_print ("edge from IL%04x to IL_%04x\n", from->cil_code - cfg->cil_code, to->cil_code - cfg->cil_code);
837                 else
838                         g_print ("edge from IL%04x to exit\n", from->cil_code - cfg->cil_code);
839         } else {
840                 if (to->cil_code)
841                         g_print ("edge from entry to IL_%04x\n", to->cil_code - cfg->cil_code);
842                 else
843                         g_print ("edge from entry to exit\n");
844         }
845 #endif
846         found = FALSE;
847         for (i = 0; i < from->out_count; ++i) {
848                 if (to == from->out_bb [i]) {
849                         found = TRUE;
850                         break;
851                 }
852         }
853         if (!found) {
854                 newa = mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (from->out_count + 1));
855                 for (i = 0; i < from->out_count; ++i) {
856                         newa [i] = from->out_bb [i];
857                 }
858                 newa [i] = to;
859                 from->out_count++;
860                 from->out_bb = newa;
861         }
862
863         found = FALSE;
864         for (i = 0; i < to->in_count; ++i) {
865                 if (from == to->in_bb [i]) {
866                         found = TRUE;
867                         break;
868                 }
869         }
870         if (!found) {
871                 newa = mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (to->in_count + 1));
872                 for (i = 0; i < to->in_count; ++i) {
873                         newa [i] = to->in_bb [i];
874                 }
875                 newa [i] = from;
876                 to->in_count++;
877                 to->in_bb = newa;
878         }
879 }
880
881 /**
882  * mono_unlink_bblock:
883  *
884  *   Unlink two basic blocks.
885  */
886 static void
887 mono_unlink_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
888 {
889         int i, pos;
890         gboolean found;
891
892         found = FALSE;
893         for (i = 0; i < from->out_count; ++i) {
894                 if (to == from->out_bb [i]) {
895                         found = TRUE;
896                         break;
897                 }
898         }
899         if (found) {
900                 pos = 0;
901                 for (i = 0; i < from->out_count; ++i) {
902                         if (from->out_bb [i] != to)
903                                 from->out_bb [pos ++] = from->out_bb [i];
904                 }
905                 g_assert (pos == from->out_count - 1);
906                 from->out_count--;
907         }
908
909         found = FALSE;
910         for (i = 0; i < to->in_count; ++i) {
911                 if (from == to->in_bb [i]) {
912                         found = TRUE;
913                         break;
914                 }
915         }
916         if (found) {
917                 pos = 0;
918                 for (i = 0; i < to->in_count; ++i) {
919                         if (to->in_bb [i] != from)
920                                 to->in_bb [pos ++] = to->in_bb [i];
921                 }
922                 g_assert (pos == to->in_count - 1);
923                 to->in_count--;
924         }
925 }
926
927 /**
928  * mono_find_block_region:
929  *
930  *   We mark each basic block with a region ID. We use that to avoid BB
931  *   optimizations when blocks are in different regions.
932  *
933  * Returns:
934  *   A region token that encodes where this region is, and information
935  *   about the clause owner for this block.
936  *
937  *   The region encodes the try/catch/filter clause that owns this block
938  *   as well as the type.  -1 is a special value that represents a block
939  *   that is in none of try/catch/filter.
940  */
941 static int
942 mono_find_block_region (MonoCompile *cfg, int offset)
943 {
944         MonoMethod *method = cfg->method;
945         MonoMethodHeader *header = mono_method_get_header (method);
946         MonoExceptionClause *clause;
947         int i;
948
949         /* first search for handlers and filters */
950         for (i = 0; i < header->num_clauses; ++i) {
951                 clause = &header->clauses [i];
952                 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->data.filter_offset) &&
953                     (offset < (clause->handler_offset)))
954                         return ((i + 1) << 8) | MONO_REGION_FILTER | clause->flags;
955                            
956                 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
957                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
958                                 return ((i + 1) << 8) | MONO_REGION_FINALLY | clause->flags;
959                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
960                                 return ((i + 1) << 8) | MONO_REGION_FAULT | clause->flags;
961                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
962                                 return ((i + 1) << 8) | MONO_REGION_CATCH | clause->flags;
963                 }
964         }
965
966         /* search the try blocks */
967         for (i = 0; i < header->num_clauses; ++i) {
968                 clause = &header->clauses [i];
969                 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
970                         return ((i + 1) << 8) | clause->flags;
971         }
972
973         return -1;
974 }
975
976 static GList*
977 mono_find_final_block (MonoCompile *cfg, unsigned char *ip, unsigned char *target, int type)
978 {
979         MonoMethod *method = cfg->method;
980         MonoMethodHeader *header = mono_method_get_header (method);
981         MonoExceptionClause *clause;
982         MonoBasicBlock *handler;
983         int i;
984         GList *res = NULL;
985
986         for (i = 0; i < header->num_clauses; ++i) {
987                 clause = &header->clauses [i];
988                 if (MONO_OFFSET_IN_CLAUSE (clause, (ip - header->code)) && 
989                     (!MONO_OFFSET_IN_CLAUSE (clause, (target - header->code)))) {
990                         if (clause->flags == type) {
991                                 handler = cfg->cil_offset_to_bb [clause->handler_offset];
992                                 g_assert (handler);
993                                 res = g_list_append (res, handler);
994                         }
995                 }
996         }
997         return res;
998 }
999
1000 MonoInst *
1001 mono_find_spvar_for_region (MonoCompile *cfg, int region)
1002 {
1003         return g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
1004 }
1005
1006 static void
1007 mono_create_spvar_for_region (MonoCompile *cfg, int region)
1008 {
1009         MonoInst *var;
1010
1011         var = g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
1012         if (var)
1013                 return;
1014
1015         var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1016         /* prevent it from being register allocated */
1017         var->flags |= MONO_INST_INDIRECT;
1018
1019         g_hash_table_insert (cfg->spvars, GINT_TO_POINTER (region), var);
1020 }
1021
1022 static MonoInst *
1023 mono_find_exvar_for_offset (MonoCompile *cfg, int offset)
1024 {
1025         return g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
1026 }
1027
1028 static MonoInst*
1029 mono_create_exvar_for_offset (MonoCompile *cfg, int offset)
1030 {
1031         MonoInst *var;
1032
1033         var = g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
1034         if (var)
1035                 return var;
1036
1037         var = mono_compile_create_var (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL);
1038         /* prevent it from being register allocated */
1039         var->flags |= MONO_INST_INDIRECT;
1040
1041         g_hash_table_insert (cfg->exvars, GINT_TO_POINTER (offset), var);
1042
1043         return var;
1044 }
1045
1046 static void
1047 df_visit (MonoBasicBlock *start, int *dfn, MonoBasicBlock **array)
1048 {
1049         int i;
1050
1051         array [*dfn] = start;
1052         /*g_print ("visit %d at %p (BB%ld)\n", *dfn, start->cil_code, start->block_num);*/
1053         for (i = 0; i < start->out_count; ++i) {
1054                 if (start->out_bb [i]->dfn)
1055                         continue;
1056                 (*dfn)++;
1057                 start->out_bb [i]->dfn = *dfn;
1058                 start->out_bb [i]->df_parent = start;
1059                 array [*dfn] = start->out_bb [i];
1060                 df_visit (start->out_bb [i], dfn, array);
1061         }
1062 }
1063
1064 static MonoBasicBlock*
1065 find_previous (MonoBasicBlock **bblocks, guint32 n_bblocks, MonoBasicBlock *start, const guchar *code)
1066 {
1067         MonoBasicBlock *best = start;
1068         int i;
1069
1070         for (i = 0; i < n_bblocks; ++i) {
1071                 if (bblocks [i]) {
1072                         MonoBasicBlock *bb = bblocks [i];
1073
1074                         if (bb->cil_code && bb->cil_code < code && bb->cil_code > best->cil_code)
1075                                 best = bb;
1076                 }
1077         }
1078
1079         return best;
1080 }
1081
1082 static void
1083 split_bblock (MonoCompile *cfg, MonoBasicBlock *first, MonoBasicBlock *second) {
1084         int i, j;
1085         MonoInst *inst;
1086         MonoBasicBlock *bb;
1087
1088         if (!MONO_INST_LIST_EMPTY (&second->ins_list))
1089                 return;
1090         
1091         /* 
1092          * FIXME: take into account all the details:
1093          * second may have been the target of more than one bblock
1094          */
1095         second->out_count = first->out_count;
1096         second->out_bb = first->out_bb;
1097
1098         for (i = 0; i < first->out_count; ++i) {
1099                 bb = first->out_bb [i];
1100                 for (j = 0; j < bb->in_count; ++j) {
1101                         if (bb->in_bb [j] == first)
1102                                 bb->in_bb [j] = second;
1103                 }
1104         }
1105
1106         first->out_count = 0;
1107         first->out_bb = NULL;
1108         link_bblock (cfg, first, second);
1109
1110         /*g_print ("start search at %p for %p\n", first->cil_code, second->cil_code);*/
1111         MONO_BB_FOR_EACH_INS (first, inst) {
1112                 MonoInst *inst_next;
1113
1114                 /*char *code = mono_disasm_code_one (NULL, cfg->method, inst->next->cil_code, NULL);
1115                 g_print ("found %p: %s", inst->next->cil_code, code);
1116                 g_free (code);*/
1117                 if (inst->cil_code >= second->cil_code)
1118                         continue;
1119
1120                 inst_next = mono_inst_list_next (&inst->node, &first->ins_list);
1121                 if (!inst_next)
1122                         break;
1123
1124                 if (inst_next->cil_code < second->cil_code)
1125                         continue;
1126                         
1127                 second->ins_list.next = inst->node.next;
1128                 second->ins_list.prev = first->ins_list.prev;
1129                 inst->node.next = &first->ins_list;
1130                 first->ins_list.prev = &inst->node;
1131
1132                 second->next_bb = first->next_bb;
1133                 first->next_bb = second;
1134                 return;
1135         }
1136         if (MONO_INST_LIST_EMPTY (&second->ins_list)) {
1137                 g_warning ("bblock split failed in %s::%s\n", cfg->method->klass->name, cfg->method->name);
1138                 //G_BREAKPOINT ();
1139         }
1140 }
1141
1142 static guint32
1143 reverse_branch_op (guint32 opcode)
1144 {
1145         static const int reverse_map [] = {
1146                 CEE_BNE_UN, CEE_BLT, CEE_BLE, CEE_BGT, CEE_BGE,
1147                 CEE_BEQ, CEE_BLT_UN, CEE_BLE_UN, CEE_BGT_UN, CEE_BGE_UN
1148         };
1149         static const int reverse_fmap [] = {
1150                 OP_FBNE_UN, OP_FBLT, OP_FBLE, OP_FBGT, OP_FBGE,
1151                 OP_FBEQ, OP_FBLT_UN, OP_FBLE_UN, OP_FBGT_UN, OP_FBGE_UN
1152         };
1153         static const int reverse_lmap [] = {
1154                 OP_LBNE_UN, OP_LBLT, OP_LBLE, OP_LBGT, OP_LBGE,
1155                 OP_LBEQ, OP_LBLT_UN, OP_LBLE_UN, OP_LBGT_UN, OP_LBGE_UN
1156         };
1157         static const int reverse_imap [] = {
1158                 OP_IBNE_UN, OP_IBLT, OP_IBLE, OP_IBGT, OP_IBGE,
1159                 OP_IBEQ, OP_IBLT_UN, OP_IBLE_UN, OP_IBGT_UN, OP_IBGE_UN
1160         };
1161                                 
1162         if (opcode >= CEE_BEQ && opcode <= CEE_BLT_UN) {
1163                 opcode = reverse_map [opcode - CEE_BEQ];
1164         } else if (opcode >= OP_FBEQ && opcode <= OP_FBLT_UN) {
1165                 opcode = reverse_fmap [opcode - OP_FBEQ];
1166         } else if (opcode >= OP_LBEQ && opcode <= OP_LBLT_UN) {
1167                 opcode = reverse_lmap [opcode - OP_LBEQ];
1168         } else if (opcode >= OP_IBEQ && opcode <= OP_IBLT_UN) {
1169                 opcode = reverse_imap [opcode - OP_IBEQ];
1170         } else
1171                 g_assert_not_reached ();
1172
1173         return opcode;
1174 }
1175
1176 #ifdef MONO_ARCH_SOFT_FLOAT
1177 static int
1178 condbr_to_fp_br (int opcode)
1179 {
1180         switch (opcode) {
1181         case CEE_BEQ: return OP_FBEQ;
1182         case CEE_BGE: return OP_FBGE;
1183         case CEE_BGT: return OP_FBGT;
1184         case CEE_BLE: return OP_FBLE;
1185         case CEE_BLT: return OP_FBLT;
1186         case CEE_BNE_UN: return OP_FBNE_UN;
1187         case CEE_BGE_UN: return OP_FBGE_UN;
1188         case CEE_BGT_UN: return OP_FBGT_UN;
1189         case CEE_BLE_UN: return OP_FBLE_UN;
1190         case CEE_BLT_UN: return OP_FBLT_UN;
1191         }
1192         g_assert_not_reached ();
1193         return 0;
1194 }
1195 #endif
1196
1197 /*
1198  * Returns the type used in the eval stack when @type is loaded.
1199  * FIXME: return a MonoType/MonoClass for the byref and VALUETYPE cases.
1200  */
1201 static void
1202 type_to_eval_stack_type (MonoCompile *cfg, MonoType *type, MonoInst *inst)
1203 {
1204         MonoClass *klass;
1205
1206         inst->klass = klass = mono_class_from_mono_type (type);
1207         if (type->byref) {
1208                 inst->type = STACK_MP;
1209                 return;
1210         }
1211
1212 handle_enum:
1213         switch (type->type) {
1214         case MONO_TYPE_VOID:
1215                 inst->type = STACK_INV;
1216                 return;
1217         case MONO_TYPE_I1:
1218         case MONO_TYPE_U1:
1219         case MONO_TYPE_BOOLEAN:
1220         case MONO_TYPE_I2:
1221         case MONO_TYPE_U2:
1222         case MONO_TYPE_CHAR:
1223         case MONO_TYPE_I4:
1224         case MONO_TYPE_U4:
1225                 inst->type = STACK_I4;
1226                 return;
1227         case MONO_TYPE_I:
1228         case MONO_TYPE_U:
1229         case MONO_TYPE_PTR:
1230         case MONO_TYPE_FNPTR:
1231                 inst->type = STACK_PTR;
1232                 return;
1233         case MONO_TYPE_CLASS:
1234         case MONO_TYPE_STRING:
1235         case MONO_TYPE_OBJECT:
1236         case MONO_TYPE_SZARRAY:
1237         case MONO_TYPE_ARRAY:    
1238                 inst->type = STACK_OBJ;
1239                 return;
1240         case MONO_TYPE_I8:
1241         case MONO_TYPE_U8:
1242                 inst->type = STACK_I8;
1243                 return;
1244         case MONO_TYPE_R4:
1245         case MONO_TYPE_R8:
1246                 inst->type = STACK_R8;
1247                 return;
1248         case MONO_TYPE_VALUETYPE:
1249                 if (type->data.klass->enumtype) {
1250                         type = type->data.klass->enum_basetype;
1251                         goto handle_enum;
1252                 } else {
1253                         inst->klass = klass;
1254                         inst->type = STACK_VTYPE;
1255                         return;
1256                 }
1257         case MONO_TYPE_TYPEDBYREF:
1258                 inst->klass = mono_defaults.typed_reference_class;
1259                 inst->type = STACK_VTYPE;
1260                 return;
1261         case MONO_TYPE_GENERICINST:
1262                 type = &type->data.generic_class->container_class->byval_arg;
1263                 goto handle_enum;
1264         case MONO_TYPE_VAR :
1265         case MONO_TYPE_MVAR :
1266                 /* FIXME: all the arguments must be references for now,
1267                  * later look inside cfg and see if the arg num is
1268                  * really a reference
1269                  */
1270                 g_assert (cfg->generic_sharing_context);
1271                 inst->type = STACK_OBJ;
1272                 return;
1273         default:
1274                 g_error ("unknown type 0x%02x in eval stack type", type->type);
1275         }
1276 }
1277
1278 /*
1279  * The following tables are used to quickly validate the IL code in type_from_op ().
1280  */
1281 static const char
1282 bin_num_table [STACK_MAX] [STACK_MAX] = {
1283         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1284         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
1285         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1286         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
1287         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_R8,  STACK_INV, STACK_INV, STACK_INV},
1288         {STACK_INV, STACK_MP,  STACK_INV, STACK_MP,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV},
1289         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1290         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1291 };
1292
1293 static const char 
1294 neg_table [] = {
1295         STACK_INV, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_INV, STACK_INV, STACK_INV
1296 };
1297
1298 /* reduce the size of this table */
1299 static const char
1300 bin_int_table [STACK_MAX] [STACK_MAX] = {
1301         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1302         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1303         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1304         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1305         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1306         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1307         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1308         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1309 };
1310
1311 static const char
1312 bin_comp_table [STACK_MAX] [STACK_MAX] = {
1313 /*      Inv i  L  p  F  &  O  vt */
1314         {0},
1315         {0, 1, 0, 1, 0, 0, 0, 0}, /* i, int32 */
1316         {0, 0, 1, 0, 0, 0, 0, 0}, /* L, int64 */
1317         {0, 1, 0, 1, 0, 2, 4, 0}, /* p, ptr */
1318         {0, 0, 0, 0, 1, 0, 0, 0}, /* F, R8 */
1319         {0, 0, 0, 2, 0, 1, 0, 0}, /* &, managed pointer */
1320         {0, 0, 0, 4, 0, 0, 3, 0}, /* O, reference */
1321         {0, 0, 0, 0, 0, 0, 0, 0}, /* vt value type */
1322 };
1323
1324 /* reduce the size of this table */
1325 static const char
1326 shift_table [STACK_MAX] [STACK_MAX] = {
1327         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1328         {STACK_INV, STACK_I4,  STACK_INV, STACK_I4,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1329         {STACK_INV, STACK_I8,  STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1330         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1331         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1332         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1333         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1334         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1335 };
1336
1337 /*
1338  * Tables to map from the non-specific opcode to the matching
1339  * type-specific opcode.
1340  */
1341 /* handles from CEE_ADD to CEE_SHR_UN (CEE_REM_UN for floats) */
1342 static const guint16
1343 binops_op_map [STACK_MAX] = {
1344         0, 0, OP_LADD-CEE_ADD, OP_PADD-CEE_ADD, OP_FADD-CEE_ADD, OP_PADD-CEE_ADD
1345 };
1346
1347 /* handles from CEE_NEG to CEE_CONV_U8 */
1348 static const guint16
1349 unops_op_map [STACK_MAX] = {
1350         0, 0, OP_LNEG-CEE_NEG, OP_PNEG-CEE_NEG, OP_FNEG-CEE_NEG, OP_PNEG-CEE_NEG
1351 };
1352
1353 /* handles from CEE_CONV_U2 to CEE_SUB_OVF_UN */
1354 static const guint16
1355 ovfops_op_map [STACK_MAX] = {
1356         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
1357 };
1358
1359 /* handles from CEE_CONV_OVF_I1_UN to CEE_CONV_OVF_U_UN */
1360 static const guint16
1361 ovf2ops_op_map [STACK_MAX] = {
1362         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
1363 };
1364
1365 /* handles from CEE_CONV_OVF_I1 to CEE_CONV_OVF_U8 */
1366 static const guint16
1367 ovf3ops_op_map [STACK_MAX] = {
1368         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
1369 };
1370
1371 /* handles from CEE_CEQ to CEE_CLT_UN */
1372 static const guint16
1373 ceqops_op_map [STACK_MAX] = {
1374         0, 0, OP_LCEQ-OP_CEQ, OP_PCEQ-OP_CEQ, OP_FCEQ-OP_CEQ, OP_LCEQ-OP_CEQ
1375 };
1376
1377 /*
1378  * Sets ins->type (the type on the eval stack) according to the
1379  * type of the opcode and the arguments to it.
1380  * Invalid IL code is marked by setting ins->type to the invalid value STACK_INV.
1381  *
1382  * FIXME: this function sets ins->type unconditionally in some cases, but
1383  * it should set it to invalid for some types (a conv.x on an object)
1384  */
1385 static void
1386 type_from_op (MonoInst *ins) {
1387         switch (ins->opcode) {
1388         /* binops */
1389         case CEE_ADD:
1390         case CEE_SUB:
1391         case CEE_MUL:
1392         case CEE_DIV:
1393         case CEE_REM:
1394                 /* FIXME: check unverifiable args for STACK_MP */
1395                 ins->type = bin_num_table [ins->inst_i0->type] [ins->inst_i1->type];
1396                 ins->opcode += binops_op_map [ins->type];
1397                 return;
1398         case CEE_DIV_UN:
1399         case CEE_REM_UN:
1400         case CEE_AND:
1401         case CEE_OR:
1402         case CEE_XOR:
1403                 ins->type = bin_int_table [ins->inst_i0->type] [ins->inst_i1->type];
1404                 ins->opcode += binops_op_map [ins->type];
1405                 return;
1406         case CEE_SHL:
1407         case CEE_SHR:
1408         case CEE_SHR_UN:
1409                 ins->type = shift_table [ins->inst_i0->type] [ins->inst_i1->type];
1410                 ins->opcode += binops_op_map [ins->type];
1411                 return;
1412         case OP_COMPARE:
1413         case OP_LCOMPARE:
1414                 /* FIXME: handle some specifics with ins->next->type */
1415                 ins->type = bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] ? STACK_I4: STACK_INV;
1416                 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))))
1417                         ins->opcode = OP_LCOMPARE;
1418                 return;
1419         case OP_CEQ:
1420                 ins->type = bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] ? STACK_I4: STACK_INV;
1421                 ins->opcode += ceqops_op_map [ins->inst_i0->type];
1422                 return;
1423                 
1424         case OP_CGT:
1425         case OP_CGT_UN:
1426         case OP_CLT:
1427         case OP_CLT_UN:
1428                 ins->type = (bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] & 1) ? STACK_I4: STACK_INV;
1429                 ins->opcode += ceqops_op_map [ins->inst_i0->type];
1430                 return;
1431         /* unops */
1432         case CEE_NEG:
1433                 ins->type = neg_table [ins->inst_i0->type];
1434                 ins->opcode += unops_op_map [ins->type];
1435                 return;
1436         case CEE_NOT:
1437                 if (ins->inst_i0->type >= STACK_I4 && ins->inst_i0->type <= STACK_PTR)
1438                         ins->type = ins->inst_i0->type;
1439                 else
1440                         ins->type = STACK_INV;
1441                 ins->opcode += unops_op_map [ins->type];
1442                 return;
1443         case CEE_CONV_I1:
1444         case CEE_CONV_I2:
1445         case CEE_CONV_I4:
1446         case CEE_CONV_U4:
1447                 ins->type = STACK_I4;
1448                 ins->opcode += unops_op_map [ins->inst_i0->type];
1449                 return;
1450         case CEE_CONV_R_UN:
1451                 ins->type = STACK_R8;
1452                 switch (ins->inst_i0->type) {
1453                 case STACK_I4:
1454                 case STACK_PTR:
1455                         break;
1456                 case STACK_I8:
1457                         ins->opcode = OP_LCONV_TO_R_UN; 
1458                         break;
1459                 }
1460                 return;
1461         case CEE_CONV_OVF_I1:
1462         case CEE_CONV_OVF_U1:
1463         case CEE_CONV_OVF_I2:
1464         case CEE_CONV_OVF_U2:
1465         case CEE_CONV_OVF_I4:
1466         case CEE_CONV_OVF_U4:
1467                 ins->type = STACK_I4;
1468                 ins->opcode += ovf3ops_op_map [ins->inst_i0->type];
1469                 return;
1470         case CEE_CONV_OVF_I_UN:
1471         case CEE_CONV_OVF_U_UN:
1472                 ins->type = STACK_PTR;
1473                 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1474                 return;
1475         case CEE_CONV_OVF_I1_UN:
1476         case CEE_CONV_OVF_I2_UN:
1477         case CEE_CONV_OVF_I4_UN:
1478         case CEE_CONV_OVF_U1_UN:
1479         case CEE_CONV_OVF_U2_UN:
1480         case CEE_CONV_OVF_U4_UN:
1481                 ins->type = STACK_I4;
1482                 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1483                 return;
1484         case CEE_CONV_U:
1485                 ins->type = STACK_PTR;
1486                 switch (ins->inst_i0->type) {
1487                 case STACK_I4:
1488                         break;
1489                 case STACK_PTR:
1490                 case STACK_MP:
1491 #if SIZEOF_VOID_P == 8
1492                         ins->opcode = OP_LCONV_TO_U;
1493 #endif
1494                         break;
1495                 case STACK_I8:
1496                         ins->opcode = OP_LCONV_TO_U;
1497                         break;
1498                 case STACK_R8:
1499                         ins->opcode = OP_FCONV_TO_U;
1500                         break;
1501                 }
1502                 return;
1503         case CEE_CONV_I8:
1504         case CEE_CONV_U8:
1505                 ins->type = STACK_I8;
1506                 ins->opcode += unops_op_map [ins->inst_i0->type];
1507                 return;
1508         case CEE_CONV_OVF_I8:
1509         case CEE_CONV_OVF_U8:
1510                 ins->type = STACK_I8;
1511                 ins->opcode += ovf3ops_op_map [ins->inst_i0->type];
1512                 return;
1513         case CEE_CONV_OVF_U8_UN:
1514         case CEE_CONV_OVF_I8_UN:
1515                 ins->type = STACK_I8;
1516                 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1517                 return;
1518         case CEE_CONV_R4:
1519         case CEE_CONV_R8:
1520                 ins->type = STACK_R8;
1521                 ins->opcode += unops_op_map [ins->inst_i0->type];
1522                 return;
1523         case OP_CKFINITE:
1524                 ins->type = STACK_R8;           
1525                 return;
1526         case CEE_CONV_U2:
1527         case CEE_CONV_U1:
1528                 ins->type = STACK_I4;
1529                 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1530                 break;
1531         case CEE_CONV_I:
1532         case CEE_CONV_OVF_I:
1533         case CEE_CONV_OVF_U:
1534                 ins->type = STACK_PTR;
1535                 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1536                 return;
1537         case CEE_ADD_OVF:
1538         case CEE_ADD_OVF_UN:
1539         case CEE_MUL_OVF:
1540         case CEE_MUL_OVF_UN:
1541         case CEE_SUB_OVF:
1542         case CEE_SUB_OVF_UN:
1543                 ins->type = bin_num_table [ins->inst_i0->type] [ins->inst_i1->type];
1544                 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1545                 if (ins->type == STACK_R8)
1546                         ins->type = STACK_INV;
1547                 return;
1548         default:
1549                 g_error ("opcode 0x%04x not handled in type from op", ins->opcode);
1550                 break;
1551         }
1552 }
1553
1554 static const char 
1555 ldind_type [] = {
1556         STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_R8, STACK_OBJ
1557 };
1558
1559 /* map ldelem.x to the matching ldind.x opcode */
1560 static const guchar
1561 ldelem_to_ldind [] = {
1562         CEE_LDIND_I1,
1563         CEE_LDIND_U1,
1564         CEE_LDIND_I2,
1565         CEE_LDIND_U2,
1566         CEE_LDIND_I4,
1567         CEE_LDIND_U4,
1568         CEE_LDIND_I8,
1569         CEE_LDIND_I,
1570         CEE_LDIND_R4,
1571         CEE_LDIND_R8,
1572         CEE_LDIND_REF
1573 };
1574
1575 /* map stelem.x to the matching stind.x opcode */
1576 static const guchar
1577 stelem_to_stind [] = {
1578         CEE_STIND_I,
1579         CEE_STIND_I1,
1580         CEE_STIND_I2,
1581         CEE_STIND_I4,
1582         CEE_STIND_I8,
1583         CEE_STIND_R4,
1584         CEE_STIND_R8,
1585         CEE_STIND_REF
1586 };
1587
1588 #if 0
1589
1590 static const char
1591 param_table [STACK_MAX] [STACK_MAX] = {
1592         {0},
1593 };
1594
1595 static int
1596 check_values_to_signature (MonoInst *args, MonoType *this, MonoMethodSignature *sig)
1597 {
1598         int i;
1599
1600         if (sig->hasthis) {
1601                 switch (args->type) {
1602                 case STACK_I4:
1603                 case STACK_I8:
1604                 case STACK_R8:
1605                 case STACK_VTYPE:
1606                 case STACK_INV:
1607                         return 0;
1608                 }
1609                 args++;
1610         }
1611         for (i = 0; i < sig->param_count; ++i) {
1612                 switch (args [i].type) {
1613                 case STACK_INV:
1614                         return 0;
1615                 case STACK_MP:
1616                         if (!sig->params [i]->byref)
1617                                 return 0;
1618                         continue;
1619                 case STACK_OBJ:
1620                         if (sig->params [i]->byref)
1621                                 return 0;
1622                         switch (sig->params [i]->type) {
1623                         case MONO_TYPE_CLASS:
1624                         case MONO_TYPE_STRING:
1625                         case MONO_TYPE_OBJECT:
1626                         case MONO_TYPE_SZARRAY:
1627                         case MONO_TYPE_ARRAY:
1628                                 break;
1629                         default:
1630                                 return 0;
1631                         }
1632                         continue;
1633                 case STACK_R8:
1634                         if (sig->params [i]->byref)
1635                                 return 0;
1636                         if (sig->params [i]->type != MONO_TYPE_R4 && sig->params [i]->type != MONO_TYPE_R8)
1637                                 return 0;
1638                         continue;
1639                 case STACK_PTR:
1640                 case STACK_I4:
1641                 case STACK_I8:
1642                 case STACK_VTYPE:
1643                         break;
1644                 }
1645                 /*if (!param_table [args [i].type] [sig->params [i]->type])
1646                         return 0;*/
1647         }
1648         return 1;
1649 }
1650 #endif
1651
1652 static guint
1653 mini_type_to_ldind (MonoCompile* cfg, MonoType *type)
1654 {
1655         if (cfg->generic_sharing_context && !type->byref) {
1656                 /* FIXME: all the arguments must be references for now,
1657                  * later look inside cfg and see if the arg num is
1658                  * really a reference
1659                  */
1660                 if (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)
1661                         return CEE_LDIND_REF;
1662         }
1663         return mono_type_to_ldind (type);
1664 }
1665
1666 static guint
1667 mini_type_to_stind (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_STIND_REF;
1676         }
1677         return mono_type_to_stind (type);
1678 }
1679
1680 int
1681 mono_op_imm_to_op (int opcode)
1682 {
1683         switch (opcode) {
1684         case OP_ADD_IMM:
1685                 return OP_PADD;
1686         case OP_IADD_IMM:
1687                 return OP_IADD;
1688         case OP_LADD_IMM:
1689                 return OP_LADD;
1690         case OP_ISUB_IMM:
1691                 return OP_ISUB;
1692         case OP_LSUB_IMM:
1693                 return OP_LSUB;
1694         case OP_AND_IMM:
1695 #if SIZEOF_VOID_P == 4
1696                 return OP_IAND;
1697 #else
1698                 return OP_LAND;
1699 #endif
1700         case OP_IAND_IMM:
1701                 return OP_IAND;
1702         case OP_LAND_IMM:
1703                 return OP_LAND;
1704         case OP_IOR_IMM:
1705                 return OP_IOR;
1706         case OP_LOR_IMM:
1707                 return OP_LOR;
1708         case OP_IXOR_IMM:
1709                 return OP_IXOR;
1710         case OP_LXOR_IMM:
1711                 return OP_LXOR;
1712         case OP_ISHL_IMM:
1713                 return OP_ISHL;
1714         case OP_LSHL_IMM:
1715                 return OP_LSHL;
1716         case OP_ISHR_IMM:
1717                 return OP_ISHR;
1718         case OP_LSHR_IMM:
1719                 return OP_LSHR;
1720         case OP_ISHR_UN_IMM:
1721                 return OP_ISHR_UN;
1722         case OP_LSHR_UN_IMM:
1723                 return OP_LSHR_UN;
1724         case OP_IDIV_IMM:
1725                 return OP_IDIV;
1726         case OP_IDIV_UN_IMM:
1727                 return OP_IDIV_UN;
1728         case OP_IREM_UN_IMM:
1729                 return OP_IREM_UN;
1730         case OP_IREM_IMM:
1731                 return OP_IREM;
1732         case OP_DIV_IMM:
1733 #if SIZEOF_VOID_P == 4
1734                 return OP_IDIV;
1735 #else
1736                 return OP_LDIV;
1737 #endif
1738         case OP_REM_IMM:
1739 #if SIZEOF_VOID_P == 4
1740                 return OP_IREM;
1741 #else
1742                 return OP_LREM;
1743 #endif
1744         case OP_ADDCC_IMM:
1745                 return OP_ADDCC;
1746         case OP_ADC_IMM:
1747                 return OP_ADC;
1748         case OP_SUBCC_IMM:
1749                 return OP_SUBCC;
1750         case OP_SBB_IMM:
1751                 return OP_SBB;
1752         case OP_IADC_IMM:
1753                 return OP_IADC;
1754         case OP_ISBB_IMM:
1755                 return OP_ISBB;
1756         case OP_COMPARE_IMM:
1757                 return OP_COMPARE;
1758         case OP_ICOMPARE_IMM:
1759                 return OP_ICOMPARE;
1760         default:
1761                 printf ("%s\n", mono_inst_name (opcode));
1762                 g_assert_not_reached ();
1763         }
1764 }
1765
1766 /*
1767  * mono_decompose_op_imm:
1768  *
1769  *   Replace the OP_.._IMM INS with its non IMM variant.
1770  */
1771 void
1772 mono_decompose_op_imm (MonoCompile *cfg, MonoInst *ins)
1773 {
1774         MonoInst *temp;
1775
1776         MONO_INST_NEW (cfg, temp, OP_ICONST);
1777         temp->inst_c0 = ins->inst_imm;
1778         temp->dreg = mono_regstate_next_int (cfg->rs);
1779         MONO_INST_LIST_ADD_TAIL (&(temp)->node, &(ins)->node);
1780         ins->opcode = mono_op_imm_to_op (ins->opcode);
1781         ins->sreg2 = temp->dreg;
1782 }
1783
1784 /*
1785  * When we need a pointer to the current domain many times in a method, we
1786  * call mono_domain_get() once and we store the result in a local variable.
1787  * This function returns the variable that represents the MonoDomain*.
1788  */
1789 inline static MonoInst *
1790 mono_get_domainvar (MonoCompile *cfg)
1791 {
1792         if (!cfg->domainvar)
1793                 cfg->domainvar = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1794         return cfg->domainvar;
1795 }
1796
1797 /*
1798  * The got_var contains the address of the Global Offset Table when AOT 
1799  * compiling.
1800  */
1801 inline static MonoInst *
1802 mono_get_got_var (MonoCompile *cfg)
1803 {
1804 #ifdef MONO_ARCH_NEED_GOT_VAR
1805         if (!cfg->compile_aot)
1806                 return NULL;
1807         if (!cfg->got_var) {
1808                 cfg->got_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1809         }
1810         return cfg->got_var;
1811 #else
1812         return NULL;
1813 #endif
1814 }
1815
1816 static MonoInst *
1817 mono_get_vtable_var (MonoCompile *cfg)
1818 {
1819         g_assert (cfg->generic_sharing_context);
1820
1821         if (!cfg->rgctx_var) {
1822                 cfg->rgctx_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1823                 /* force the var to be stack allocated */
1824                 cfg->rgctx_var->flags |= MONO_INST_INDIRECT;
1825         }
1826
1827         return cfg->rgctx_var;
1828 }
1829
1830 MonoInst*
1831 mono_compile_create_var (MonoCompile *cfg, MonoType *type, int opcode)
1832 {
1833         MonoInst *inst;
1834         int num = cfg->num_varinfo;
1835
1836         if ((num + 1) >= cfg->varinfo_count) {
1837                 int orig_count = cfg->varinfo_count;
1838                 cfg->varinfo_count = (cfg->varinfo_count + 2) * 2;
1839                 cfg->varinfo = (MonoInst **)g_realloc (cfg->varinfo, sizeof (MonoInst*) * cfg->varinfo_count);
1840                 cfg->vars = (MonoMethodVar *)g_realloc (cfg->vars, sizeof (MonoMethodVar) * cfg->varinfo_count);
1841                 memset (&cfg->vars [orig_count], 0, (cfg->varinfo_count - orig_count) * sizeof (MonoMethodVar));
1842         }
1843
1844         /*g_print ("created temp %d of type 0x%x\n", num, type->type);*/
1845         mono_jit_stats.allocate_var++;
1846
1847         MONO_INST_NEW (cfg, inst, opcode);
1848         inst->inst_c0 = num;
1849         inst->inst_vtype = type;
1850         inst->klass = mono_class_from_mono_type (type);
1851         /* if set to 1 the variable is native */
1852         inst->backend.is_pinvoke = 0;
1853
1854         cfg->varinfo [num] = inst;
1855
1856         MONO_INIT_VARINFO (&cfg->vars [num], num);
1857
1858         cfg->num_varinfo++;
1859         if (cfg->verbose_level > 2)
1860                 g_print ("created temp %d of type %s\n", num, mono_type_get_name (type));
1861         return inst;
1862 }
1863
1864 /*
1865  * Transform a MonoInst into a load from the variable of index var_index.
1866  */
1867 void
1868 mono_compile_make_var_load (MonoCompile *cfg, MonoInst *dest, gssize var_index) {
1869         memset (dest, 0, sizeof (MonoInst));
1870         dest->ssa_op = MONO_SSA_LOAD;
1871         dest->inst_i0 = cfg->varinfo [var_index];
1872         dest->opcode = mini_type_to_ldind (cfg, dest->inst_i0->inst_vtype);
1873         type_to_eval_stack_type (cfg, dest->inst_i0->inst_vtype, dest);
1874         dest->klass = dest->inst_i0->klass;
1875 }
1876
1877 /*
1878  * Create a MonoInst that is a load from the variable of index var_index.
1879  */
1880 MonoInst*
1881 mono_compile_create_var_load (MonoCompile *cfg, gssize var_index) {
1882         MonoInst *dest;
1883         NEW_TEMPLOAD (cfg,dest,var_index);
1884         return dest;
1885 }
1886
1887 /*
1888  * Create a MonoInst that is a store of the given value into the variable of index var_index.
1889  */
1890 MonoInst*
1891 mono_compile_create_var_store (MonoCompile *cfg, gssize var_index, MonoInst *value) {
1892         MonoInst *dest;
1893         NEW_TEMPSTORE (cfg, dest, var_index, value);
1894         return dest;
1895 }
1896
1897 static MonoType*
1898 type_from_stack_type (MonoInst *ins) {
1899         switch (ins->type) {
1900         case STACK_I4: return &mono_defaults.int32_class->byval_arg;
1901         case STACK_I8: return &mono_defaults.int64_class->byval_arg;
1902         case STACK_PTR: return &mono_defaults.int_class->byval_arg;
1903         case STACK_R8: return &mono_defaults.double_class->byval_arg;
1904         case STACK_MP:
1905                 /* 
1906                  * this if used to be commented without any specific reason, but
1907                  * it breaks #80235 when commented
1908                  */
1909                 if (ins->klass)
1910                         return &ins->klass->this_arg;
1911                 else
1912                         return &mono_defaults.object_class->this_arg;
1913         case STACK_OBJ:
1914                 /* ins->klass may not be set for ldnull.
1915                  * Also, if we have a boxed valuetype, we want an object lass,
1916                  * not the valuetype class
1917                  */
1918                 if (ins->klass && !ins->klass->valuetype)
1919                         return &ins->klass->byval_arg;
1920                 return &mono_defaults.object_class->byval_arg;
1921         case STACK_VTYPE: return &ins->klass->byval_arg;
1922         default:
1923                 g_error ("stack type %d to montype not handled\n", ins->type);
1924         }
1925         return NULL;
1926 }
1927
1928 MonoType*
1929 mono_type_from_stack_type (MonoInst *ins) {
1930         return type_from_stack_type (ins);
1931 }
1932
1933 static MonoClass*
1934 array_access_to_klass (int opcode, MonoInst *array_obj)
1935 {
1936         switch (opcode) {
1937         case CEE_LDELEM_U1:
1938                 return mono_defaults.byte_class;
1939         case CEE_LDELEM_U2:
1940                 return mono_defaults.uint16_class;
1941         case CEE_LDELEM_I:
1942         case CEE_STELEM_I:
1943                 return mono_defaults.int_class;
1944         case CEE_LDELEM_I1:
1945         case CEE_STELEM_I1:
1946                 return mono_defaults.sbyte_class;
1947         case CEE_LDELEM_I2:
1948         case CEE_STELEM_I2:
1949                 return mono_defaults.int16_class;
1950         case CEE_LDELEM_I4:
1951         case CEE_STELEM_I4:
1952                 return mono_defaults.int32_class;
1953         case CEE_LDELEM_U4:
1954                 return mono_defaults.uint32_class;
1955         case CEE_LDELEM_I8:
1956         case CEE_STELEM_I8:
1957                 return mono_defaults.int64_class;
1958         case CEE_LDELEM_R4:
1959         case CEE_STELEM_R4:
1960                 return mono_defaults.single_class;
1961         case CEE_LDELEM_R8:
1962         case CEE_STELEM_R8:
1963                 return mono_defaults.double_class;
1964         case CEE_LDELEM_REF:
1965         case CEE_STELEM_REF: {
1966                 MonoClass *klass = array_obj->klass;
1967                 /* FIXME: add assert */
1968                 if (klass && klass->rank)
1969                         return klass->element_class;
1970                 return mono_defaults.object_class;
1971         }
1972         default:
1973                 g_assert_not_reached ();
1974         }
1975         return NULL;
1976 }
1977
1978 void
1979 mono_add_ins_to_end (MonoBasicBlock *bb, MonoInst *inst)
1980 {
1981         MonoInst *last = mono_inst_list_last (&bb->ins_list);
1982
1983         if (last && ((last->opcode >= CEE_BEQ &&
1984                         last->opcode <= CEE_BLT_UN) ||
1985                         last->opcode == OP_BR ||
1986                         last->opcode == OP_SWITCH)) {
1987                 MONO_INST_LIST_ADD_TAIL (&inst->node, &last->node);
1988         } else {
1989                 MONO_ADD_INS (bb, inst);
1990         }
1991 }
1992
1993 void
1994 mono_add_varcopy_to_end (MonoCompile *cfg, MonoBasicBlock *bb, int src, int dest)
1995 {
1996         MonoInst *inst, *load;
1997
1998         NEW_TEMPLOAD (cfg, load, src);
1999
2000         NEW_TEMPSTORE (cfg, inst, dest, load);
2001         /* FIXME: handle CEE_STIND_R4 */
2002         if (inst->opcode == CEE_STOBJ) {
2003                 NEW_TEMPLOADA (cfg, inst, dest);
2004                 handle_stobj (cfg, bb, inst, load, NULL, inst->klass, TRUE, FALSE, FALSE);
2005         } else {
2006                 inst->cil_code = NULL;
2007                 mono_add_ins_to_end (bb, inst);
2008         }
2009 }
2010
2011 /*
2012  * This function is called to handle items that are left on the evaluation stack
2013  * at basic block boundaries. What happens is that we save the values to local variables
2014  * and we reload them later when first entering the target basic block (with the
2015  * handle_loaded_temps () function).
2016  * It is also used to handle items on the stack in store opcodes, since it is
2017  * possible that the variable to be stored into is already on the stack, in
2018  * which case its old value should be used.
2019  * A single joint point will use the same variables (stored in the array bb->out_stack or
2020  * bb->in_stack, if the basic block is before or after the joint point).
2021  * If the stack merge fails at a join point, cfg->unverifiable is set.
2022  */
2023 static void
2024 handle_stack_args (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst **sp, int count)
2025 {
2026         int i, bindex;
2027         MonoBasicBlock *outb;
2028         MonoInst *inst, **locals;
2029         gboolean found;
2030
2031         if (!count)
2032                 return;
2033         if (cfg->verbose_level > 3)
2034                 g_print ("%d item(s) on exit from B%d\n", count, bb->block_num);
2035
2036         if (!bb->out_scount) {
2037                 bb->out_scount = count;
2038                 //g_print ("bblock %d has out:", bb->block_num);
2039                 found = FALSE;
2040                 for (i = 0; i < bb->out_count; ++i) {
2041                         outb = bb->out_bb [i];
2042                         /* exception handlers are linked, but they should not be considered for stack args */
2043                         if (outb->flags & BB_EXCEPTION_HANDLER)
2044                                 continue;
2045                         //g_print (" %d", outb->block_num);
2046                         if (outb->in_stack) {
2047                                 found = TRUE;
2048                                 bb->out_stack = outb->in_stack;
2049                                 break;
2050                         }
2051                 }
2052                 //g_print ("\n");
2053                 if (!found) {
2054                         bb->out_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * count);
2055                         for (i = 0; i < count; ++i) {
2056                                 /* 
2057                                  * try to reuse temps already allocated for this purpouse, if they occupy the same
2058                                  * stack slot and if they are of the same type.
2059                                  * This won't cause conflicts since if 'local' is used to 
2060                                  * store one of the values in the in_stack of a bblock, then
2061                                  * the same variable will be used for the same outgoing stack 
2062                                  * slot as well. 
2063                                  * This doesn't work when inlining methods, since the bblocks
2064                                  * in the inlined methods do not inherit their in_stack from
2065                                  * the bblock they are inlined to. See bug #58863 for an
2066                                  * example.
2067                                  * This hack is disabled since it also prevents proper tracking of types.
2068                                  */
2069 #if 1
2070                                 bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
2071 #else
2072                                 if (cfg->inlined_method)
2073                                         bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
2074                                 else
2075                                         bb->out_stack [i] = mono_compile_get_interface_var (cfg, i, sp [i]);
2076 #endif
2077                         }
2078                 }
2079         }
2080
2081         for (i = 0; i < bb->out_count; ++i) {
2082                 outb = bb->out_bb [i];
2083                 /* exception handlers are linked, but they should not be considered for stack args */
2084                 if (outb->flags & BB_EXCEPTION_HANDLER)
2085                         continue;
2086                 if (outb->in_scount) {
2087                         if (outb->in_scount != bb->out_scount) {
2088                                 cfg->unverifiable = TRUE;
2089                                 return;
2090                         }
2091                         continue; /* check they are the same locals */
2092                 }
2093                 outb->in_scount = count;
2094                 outb->in_stack = bb->out_stack;
2095         }
2096
2097         locals = bb->out_stack;
2098         for (i = 0; i < count; ++i) {
2099                 /* add store ops at the end of the bb, before the branch */
2100                 NEW_TEMPSTORE (cfg, inst, locals [i]->inst_c0, sp [i]);
2101                 if (inst->opcode == CEE_STOBJ) {
2102                         NEW_TEMPLOADA (cfg, inst, locals [i]->inst_c0);
2103                         handle_stobj (cfg, bb, inst, sp [i], sp [i]->cil_code, inst->klass, TRUE, FALSE, FALSE);
2104                 } else {
2105                         inst->cil_code = sp [i]->cil_code;
2106                         mono_add_ins_to_end (bb, inst);
2107                 }
2108                 if (cfg->verbose_level > 3)
2109                         g_print ("storing %d to temp %d\n", i, (int)locals [i]->inst_c0);
2110         }
2111
2112         /*
2113          * It is possible that the out bblocks already have in_stack assigned, and
2114          * the in_stacks differ. In this case, we will store to all the different 
2115          * in_stacks.
2116          */
2117
2118         found = TRUE;
2119         bindex = 0;
2120         while (found) {
2121                 /* Find a bblock which has a different in_stack */
2122                 found = FALSE;
2123                 while (bindex < bb->out_count) {
2124                         outb = bb->out_bb [bindex];
2125                         /* exception handlers are linked, but they should not be considered for stack args */
2126                         if (outb->flags & BB_EXCEPTION_HANDLER) {
2127                                 bindex++;
2128                                 continue;
2129                         }
2130                         if (outb->in_stack != locals) {
2131                                 /* 
2132                                  * Instead of storing sp [i] to locals [i], we need to store
2133                                  * locals [i] to <new locals>[i], since the sp [i] tree can't
2134                                  * be shared between trees.
2135                                  */
2136                                 for (i = 0; i < count; ++i)
2137                                         mono_add_varcopy_to_end (cfg, bb, locals [i]->inst_c0, outb->in_stack [i]->inst_c0);
2138                                 locals = outb->in_stack;
2139                                 found = TRUE;
2140                                 break;
2141                         }
2142                         bindex ++;
2143                 }
2144         }
2145 }
2146
2147 static int
2148 ret_type_to_call_opcode (MonoType *type, int calli, int virt, MonoGenericSharingContext *gsctx)
2149 {
2150         if (type->byref)
2151                 return calli? OP_CALL_REG: virt? OP_CALLVIRT: OP_CALL;
2152
2153 handle_enum:
2154         type = mini_get_basic_type_from_generic (gsctx, type);
2155         switch (type->type) {
2156         case MONO_TYPE_VOID:
2157                 return calli? OP_VOIDCALL_REG: virt? OP_VOIDCALLVIRT: OP_VOIDCALL;
2158         case MONO_TYPE_I1:
2159         case MONO_TYPE_U1:
2160         case MONO_TYPE_BOOLEAN:
2161         case MONO_TYPE_I2:
2162         case MONO_TYPE_U2:
2163         case MONO_TYPE_CHAR:
2164         case MONO_TYPE_I4:
2165         case MONO_TYPE_U4:
2166                 return calli? OP_CALL_REG: virt? OP_CALLVIRT: OP_CALL;
2167         case MONO_TYPE_I:
2168         case MONO_TYPE_U:
2169         case MONO_TYPE_PTR:
2170         case MONO_TYPE_FNPTR:
2171                 return calli? OP_CALL_REG: virt? OP_CALLVIRT: OP_CALL;
2172         case MONO_TYPE_CLASS:
2173         case MONO_TYPE_STRING:
2174         case MONO_TYPE_OBJECT:
2175         case MONO_TYPE_SZARRAY:
2176         case MONO_TYPE_ARRAY:    
2177                 return calli? OP_CALL_REG: virt? OP_CALLVIRT: OP_CALL;
2178         case MONO_TYPE_I8:
2179         case MONO_TYPE_U8:
2180                 return calli? OP_LCALL_REG: virt? OP_LCALLVIRT: OP_LCALL;
2181         case MONO_TYPE_R4:
2182         case MONO_TYPE_R8:
2183                 return calli? OP_FCALL_REG: virt? OP_FCALLVIRT: OP_FCALL;
2184         case MONO_TYPE_VALUETYPE:
2185                 if (type->data.klass->enumtype) {
2186                         type = type->data.klass->enum_basetype;
2187                         goto handle_enum;
2188                 } else
2189                         return calli? OP_VCALL_REG: virt? OP_VCALLVIRT: OP_VCALL;
2190         case MONO_TYPE_TYPEDBYREF:
2191                 return calli? OP_VCALL_REG: virt? OP_VCALLVIRT: OP_VCALL;
2192         case MONO_TYPE_GENERICINST:
2193                 type = &type->data.generic_class->container_class->byval_arg;
2194                 goto handle_enum;
2195         default:
2196                 g_error ("unknown type 0x%02x in ret_type_to_call_opcode", type->type);
2197         }
2198         return -1;
2199 }
2200
2201 void
2202 mono_create_jump_table (MonoCompile *cfg, MonoInst *label, MonoBasicBlock **bbs, int num_blocks)
2203 {
2204         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
2205         MonoJumpInfoBBTable *table;
2206
2207         table = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfoBBTable));
2208         table->table = bbs;
2209         table->table_size = num_blocks;
2210         
2211         ji->ip.label = label;
2212         ji->type = MONO_PATCH_INFO_SWITCH;
2213         ji->data.table = table;
2214         ji->next = cfg->patch_info;
2215         cfg->patch_info = ji;
2216 }
2217
2218 static void
2219 mono_save_token_info (MonoCompile *cfg, MonoImage *image, guint32 token, gpointer key)
2220 {
2221         if (cfg->compile_aot) {
2222                 MonoJumpInfoToken *jump_info_token = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoToken));
2223                 jump_info_token->image = image;
2224                 jump_info_token->token = token;
2225                 g_hash_table_insert (cfg->token_info_hash, key, jump_info_token);
2226         }
2227 }
2228
2229 /*
2230  * When we add a tree of instructions, we need to ensure the instructions currently
2231  * on the stack are executed before (like, if we load a value from a local).
2232  * We ensure this by saving the currently loaded values to temps and rewriting the
2233  * instructions to load the values.
2234  * This is not done for opcodes that terminate a basic block (because it's handled already
2235  * by handle_stack_args ()) and for opcodes that can't change values, like POP.
2236  */
2237 static void
2238 handle_loaded_temps (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst **stack, MonoInst **sp)
2239 {
2240         MonoInst *load, *store, *temp, *ins;
2241
2242         while (stack < sp) {
2243                 ins = *stack;
2244                 /* handle also other constants */
2245                 if ((ins->opcode != OP_ICONST) &&
2246                     /* temps never get written to again, so we can safely avoid duplicating them */
2247                     !(ins->ssa_op == MONO_SSA_LOAD && ins->inst_i0->opcode == OP_LOCAL && ins->inst_i0->flags & MONO_INST_IS_TEMP)) {
2248                         temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
2249                         temp->flags |= MONO_INST_IS_TEMP;
2250                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2251                         store->cil_code = ins->cil_code;
2252                         if (store->opcode == CEE_STOBJ) {
2253                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
2254                                 handle_stobj (cfg, bblock, store, ins, ins->cil_code, temp->klass, FALSE, FALSE, FALSE);
2255                         } else
2256                                 MONO_ADD_INS (bblock, store);
2257                         NEW_TEMPLOAD (cfg, load, temp->inst_c0);
2258                         load->cil_code = ins->cil_code;
2259                         *stack = load;
2260                 }
2261                 stack++;
2262         }
2263 }
2264
2265 /*
2266  * target_type_is_incompatible:
2267  * @cfg: MonoCompile context
2268  *
2269  * Check that the item @arg on the evaluation stack can be stored
2270  * in the target type (can be a local, or field, etc).
2271  * The cfg arg can be used to check if we need verification or just
2272  * validity checks.
2273  *
2274  * Returns: non-0 value if arg can't be stored on a target.
2275  */
2276 static int
2277 target_type_is_incompatible (MonoCompile *cfg, MonoType *target, MonoInst *arg)
2278 {
2279         MonoType *simple_type;
2280         MonoClass *klass;
2281
2282         if (target->byref) {
2283                 /* FIXME: check that the pointed to types match */
2284                 if (arg->type == STACK_MP)
2285                         return arg->klass != mono_class_from_mono_type (target);
2286                 if (arg->type == STACK_PTR)
2287                         return 0;
2288                 return 1;
2289         }
2290         simple_type = mono_type_get_underlying_type (target);
2291         switch (simple_type->type) {
2292         case MONO_TYPE_VOID:
2293                 return 1;
2294         case MONO_TYPE_I1:
2295         case MONO_TYPE_U1:
2296         case MONO_TYPE_BOOLEAN:
2297         case MONO_TYPE_I2:
2298         case MONO_TYPE_U2:
2299         case MONO_TYPE_CHAR:
2300         case MONO_TYPE_I4:
2301         case MONO_TYPE_U4:
2302                 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
2303                         return 1;
2304                 return 0;
2305         case MONO_TYPE_PTR:
2306                 /* STACK_MP is needed when setting pinned locals */
2307                 if (arg->type != STACK_I4 && arg->type != STACK_PTR && arg->type != STACK_MP)
2308                         return 1;
2309                 return 0;
2310         case MONO_TYPE_I:
2311         case MONO_TYPE_U:
2312         case MONO_TYPE_FNPTR:
2313                 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
2314                         return 1;
2315                 return 0;
2316         case MONO_TYPE_OBJECT:
2317                 if (arg->type != STACK_OBJ)
2318                         return 1;
2319                 return 0;
2320         case MONO_TYPE_STRING:
2321                 if (arg->type != STACK_OBJ)
2322                         return 1;
2323                 /* ldnull has arg->klass unset */
2324                 /*if (arg->klass && arg->klass != mono_defaults.string_class) {
2325                         G_BREAKPOINT ();
2326                         return 1;
2327                 }*/
2328                 return 0;
2329         case MONO_TYPE_CLASS:
2330         case MONO_TYPE_SZARRAY:
2331         case MONO_TYPE_ARRAY:    
2332                 if (arg->type != STACK_OBJ)
2333                         return 1;
2334                 /* FIXME: check type compatibility */
2335                 return 0;
2336         case MONO_TYPE_I8:
2337         case MONO_TYPE_U8:
2338                 if (arg->type != STACK_I8)
2339                         return 1;
2340                 return 0;
2341         case MONO_TYPE_R4:
2342         case MONO_TYPE_R8:
2343                 if (arg->type != STACK_R8)
2344                         return 1;
2345                 return 0;
2346         case MONO_TYPE_VALUETYPE:
2347                 if (arg->type != STACK_VTYPE)
2348                         return 1;
2349                 klass = mono_class_from_mono_type (simple_type);
2350                 if (klass != arg->klass)
2351                         return 1;
2352                 return 0;
2353         case MONO_TYPE_TYPEDBYREF:
2354                 if (arg->type != STACK_VTYPE)
2355                         return 1;
2356                 klass = mono_class_from_mono_type (simple_type);
2357                 if (klass != arg->klass)
2358                         return 1;
2359                 return 0;
2360         case MONO_TYPE_GENERICINST:
2361                 if (mono_type_generic_inst_is_valuetype (simple_type)) {
2362                         klass = mono_class_from_mono_type (simple_type);
2363                         if (klass->enumtype)
2364                                 return target_type_is_incompatible (cfg, klass->enum_basetype, arg);
2365                         if (arg->type != STACK_VTYPE)
2366                                 return 1;
2367                         if (klass != arg->klass)
2368                                 return 1;
2369                         return 0;
2370                 } else {
2371                         if (arg->type != STACK_OBJ)
2372                                 return 1;
2373                         /* FIXME: check type compatibility */
2374                         return 0;
2375                 }
2376         case MONO_TYPE_VAR:
2377         case MONO_TYPE_MVAR:
2378                 /* FIXME: all the arguments must be references for now,
2379                  * later look inside cfg and see if the arg num is
2380                  * really a reference
2381                  */
2382                 g_assert (cfg->generic_sharing_context);
2383                 if (arg->type != STACK_OBJ)
2384                         return 1;
2385                 return 0;
2386         default:
2387                 g_error ("unknown type 0x%02x in target_type_is_incompatible", simple_type->type);
2388         }
2389         return 1;
2390 }
2391
2392 /*
2393  * Prepare arguments for passing to a function call.
2394  * Return a non-zero value if the arguments can't be passed to the given
2395  * signature.
2396  * The type checks are not yet complete and some conversions may need
2397  * casts on 32 or 64 bit architectures.
2398  *
2399  * FIXME: implement this using target_type_is_incompatible ()
2400  */
2401 static int
2402 check_call_signature (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args)
2403 {
2404         MonoType *simple_type;
2405         int i;
2406
2407         if (sig->hasthis) {
2408                 if (args [0]->type != STACK_OBJ && args [0]->type != STACK_MP && args [0]->type != STACK_PTR)
2409                         return 1;
2410                 args++;
2411         }
2412         for (i = 0; i < sig->param_count; ++i) {
2413                 if (sig->params [i]->byref) {
2414                         if (args [i]->type != STACK_MP && args [i]->type != STACK_PTR)
2415                                 return 1;
2416                         continue;
2417                 }
2418                 simple_type = sig->params [i];
2419                 simple_type = mini_get_basic_type_from_generic (cfg->generic_sharing_context, simple_type);
2420 handle_enum:
2421                 switch (simple_type->type) {
2422                 case MONO_TYPE_VOID:
2423                         return 1;
2424                         continue;
2425                 case MONO_TYPE_I1:
2426                 case MONO_TYPE_U1:
2427                 case MONO_TYPE_BOOLEAN:
2428                 case MONO_TYPE_I2:
2429                 case MONO_TYPE_U2:
2430                 case MONO_TYPE_CHAR:
2431                 case MONO_TYPE_I4:
2432                 case MONO_TYPE_U4:
2433                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR)
2434                                 return 1;
2435                         continue;
2436                 case MONO_TYPE_I:
2437                 case MONO_TYPE_U:
2438                 case MONO_TYPE_PTR:
2439                 case MONO_TYPE_FNPTR:
2440                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR && args [i]->type != STACK_MP && args [i]->type != STACK_OBJ)
2441                                 return 1;
2442                         continue;
2443                 case MONO_TYPE_CLASS:
2444                 case MONO_TYPE_STRING:
2445                 case MONO_TYPE_OBJECT:
2446                 case MONO_TYPE_SZARRAY:
2447                 case MONO_TYPE_ARRAY:    
2448                         if (args [i]->type != STACK_OBJ)
2449                                 return 1;
2450                         continue;
2451                 case MONO_TYPE_I8:
2452                 case MONO_TYPE_U8:
2453                         if (args [i]->type != STACK_I8)
2454                                 return 1;
2455                         continue;
2456                 case MONO_TYPE_R4:
2457                 case MONO_TYPE_R8:
2458                         if (args [i]->type != STACK_R8)
2459                                 return 1;
2460                         continue;
2461                 case MONO_TYPE_VALUETYPE:
2462                         if (simple_type->data.klass->enumtype) {
2463                                 simple_type = simple_type->data.klass->enum_basetype;
2464                                 goto handle_enum;
2465                         }
2466                         if (args [i]->type != STACK_VTYPE)
2467                                 return 1;
2468                         continue;
2469                 case MONO_TYPE_TYPEDBYREF:
2470                         if (args [i]->type != STACK_VTYPE)
2471                                 return 1;
2472                         continue;
2473                 case MONO_TYPE_GENERICINST:
2474                         simple_type = &simple_type->data.generic_class->container_class->byval_arg;
2475                         goto handle_enum;
2476
2477                 default:
2478                         g_error ("unknown type 0x%02x in check_call_signature",
2479                                  simple_type->type);
2480                 }
2481         }
2482         return 0;
2483 }
2484
2485 inline static int
2486 mono_spill_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoCallInst *call, MonoMethodSignature *sig, gboolean ret_object, 
2487                  const guint8 *ip, gboolean to_end)
2488 {
2489         MonoInst *temp, *store, *ins = (MonoInst*)call;
2490         MonoType *ret = sig->ret;
2491
2492         if (!MONO_TYPE_IS_VOID (ret) || ret_object) {
2493                 if (ret_object) {
2494                         call->inst.type = STACK_OBJ;
2495                         call->inst.opcode = OP_CALL;
2496                         temp = mono_compile_create_var (cfg, &mono_defaults.string_class->byval_arg, OP_LOCAL);
2497                 } else {
2498                         type_to_eval_stack_type (cfg, ret, ins);
2499                         temp = mono_compile_create_var (cfg, ret, OP_LOCAL);
2500                 }
2501                 
2502                 temp->flags |= MONO_INST_IS_TEMP;
2503
2504                 if (MONO_TYPE_ISSTRUCT (ret)) {
2505                         MonoInst *loada, *dummy_store;
2506
2507                         /* 
2508                          * Emit a dummy store to the local holding the result so the
2509                          * liveness info remains correct.
2510                          */
2511                         NEW_DUMMY_STORE (cfg, dummy_store, temp->inst_c0);
2512                         if (to_end)
2513                                 mono_add_ins_to_end (bblock, dummy_store);
2514                         else
2515                                 MONO_ADD_INS (bblock, dummy_store);
2516
2517                         /* we use this to allocate native sized structs */
2518                         temp->backend.is_pinvoke = sig->pinvoke;
2519
2520                         NEW_TEMPLOADA (cfg, loada, temp->inst_c0);
2521                         if (call->inst.opcode == OP_VCALL || call->inst.opcode == OP_VCALL_RGCTX)
2522                                 ins->inst_left = loada;
2523                         else
2524                                 ins->inst_right = loada; /* a virtual or indirect call */
2525
2526                         if (to_end)
2527                                 mono_add_ins_to_end (bblock, ins);
2528                         else
2529                                 MONO_ADD_INS (bblock, ins);
2530                 } else {
2531                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2532                         store->cil_code = ip;
2533                         
2534 #ifdef MONO_ARCH_SOFT_FLOAT
2535                         if (store->opcode == CEE_STIND_R4) {
2536                                 /*FIXME implement proper support for to_end*/
2537                                 g_assert (!to_end);
2538                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
2539                                 handle_store_float (cfg, bblock, store, ins, ip);
2540                         } else
2541 #endif
2542                         if (to_end)
2543                                 mono_add_ins_to_end (bblock, store);
2544                         else
2545                                 MONO_ADD_INS (bblock, store);
2546                 }
2547                 return temp->inst_c0;
2548         } else {
2549                 if (to_end)
2550                         mono_add_ins_to_end (bblock, ins);
2551                 else
2552                         MONO_ADD_INS (bblock, ins);
2553                 return -1;
2554         }
2555 }
2556
2557 inline static MonoCallInst *
2558 mono_emit_call_args (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, 
2559                      MonoInst **args, int calli, int virtual, const guint8 *ip, gboolean to_end)
2560 {
2561         MonoCallInst *call;
2562         MonoInst *arg, *n;
2563
2564         MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (sig->ret, calli, virtual, cfg->generic_sharing_context));
2565
2566 #ifdef MONO_ARCH_SOFT_FLOAT
2567         /* we need to convert the r4 value to an int value */
2568         {
2569                 int i;
2570                 for (i = 0; i < sig->param_count; ++i) {
2571                         if (!sig->params [i]->byref && sig->params [i]->type == MONO_TYPE_R4) {
2572                                 MonoInst *iargs [1];
2573                                 int temp;
2574                                 iargs [0] = args [i + sig->hasthis];
2575
2576                                 temp = mono_emit_jit_icall (cfg, bblock, mono_fload_r4_arg, iargs, ip);
2577                                 NEW_TEMPLOAD (cfg, arg, temp);
2578                                 args [i + sig->hasthis] = arg;
2579                         }
2580                 }
2581         }
2582 #endif
2583
2584         call->inst.cil_code = ip;
2585         call->args = args;
2586         call->signature = sig;
2587         call = mono_arch_call_opcode (cfg, bblock, call, virtual);
2588         type_to_eval_stack_type (cfg, sig->ret, &call->inst);
2589
2590         MONO_INST_LIST_FOR_EACH_ENTRY_SAFE (arg, n, &call->out_args, node) {
2591                 if (!arg->cil_code)
2592                         arg->cil_code = ip;
2593                 if (to_end)
2594                         mono_add_ins_to_end (bblock, arg);
2595                 else
2596                         MONO_ADD_INS (bblock, arg);
2597         }
2598         return call;
2599 }
2600
2601 inline static MonoCallInst*
2602 mono_emit_calli (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, 
2603                  MonoInst **args, MonoInst *addr, const guint8 *ip)
2604 {
2605         MonoCallInst *call = mono_emit_call_args (cfg, bblock, sig, args, TRUE, FALSE, ip, FALSE);
2606
2607         call->inst.inst_i0 = addr;
2608
2609         return call;
2610 }
2611
2612 inline static MonoCallInst*
2613 mono_emit_rgctx_calli (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig,
2614         MonoInst **args, MonoInst *addr, MonoInst *rgctx_arg, const guint8 *ip)
2615 {
2616         MonoCallInst *call = mono_emit_calli (cfg, bblock, sig, args, addr, ip);
2617
2618         if (rgctx_arg) {
2619                 switch (call->inst.opcode) {
2620                 case OP_CALL_REG: call->inst.opcode = OP_CALL_REG_RGCTX; break;
2621                 case OP_VOIDCALL_REG: call->inst.opcode = OP_VOIDCALL_REG_RGCTX; break;
2622                 case OP_FCALL_REG: call->inst.opcode = OP_FCALL_REG_RGCTX; break;
2623                 case OP_LCALL_REG: call->inst.opcode = OP_LCALL_REG_RGCTX; break;
2624                 case OP_VCALL_REG: {
2625                         MonoInst *group;
2626
2627                         NEW_GROUP (cfg, group, call->inst.inst_left, NULL);
2628                         call->inst.inst_left = group;
2629                         call->inst.opcode = OP_VCALL_REG_RGCTX;
2630                         break;
2631                 }
2632                 default: g_assert_not_reached ();
2633                 }
2634
2635                 if (call->inst.opcode != OP_VCALL_REG_RGCTX) {
2636                         g_assert (!call->inst.inst_right);
2637                         call->inst.inst_right = rgctx_arg;
2638                 } else {
2639                         g_assert (!call->inst.inst_left->inst_right);
2640                         call->inst.inst_left->inst_right = rgctx_arg;
2641                 }
2642         }
2643
2644         return call;
2645 }
2646
2647 inline static int
2648 mono_emit_calli_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, 
2649                                                  MonoInst **args, MonoInst *addr, const guint8 *ip)
2650 {
2651         MonoCallInst *call = mono_emit_calli (cfg, bblock, sig, args, addr, ip);
2652
2653         return mono_spill_call (cfg, bblock, call, sig, FALSE, ip, FALSE);
2654 }
2655
2656 static int
2657 mono_emit_rgctx_calli_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig,
2658         MonoInst **args, MonoInst *addr, MonoInst *rgctx_arg, const guint8 *ip)
2659 {
2660         MonoCallInst *call = mono_emit_rgctx_calli (cfg, bblock, sig, args, addr, rgctx_arg, ip);
2661
2662         return mono_spill_call (cfg, bblock, call, sig, FALSE, ip, FALSE);
2663 }
2664
2665 static MonoCallInst*
2666 mono_emit_method_call_full (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method, MonoMethodSignature *sig,
2667                        MonoInst **args, const guint8 *ip, MonoInst *this, gboolean to_end)
2668 {
2669         gboolean virtual = this != NULL;
2670         MonoCallInst *call;
2671
2672         call = mono_emit_call_args (cfg, bblock, sig, args, FALSE, virtual, ip, to_end);
2673
2674         if (this && sig->hasthis && 
2675             (method->klass->marshalbyref || method->klass == mono_defaults.object_class) && 
2676             !(method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !MONO_CHECK_THIS (this)) {
2677                 call->method = mono_marshal_get_remoting_invoke_with_check (method);
2678         } else {
2679                 call->method = method;
2680         }
2681         call->inst.flags |= MONO_INST_HAS_METHOD;
2682         call->inst.inst_left = this;
2683
2684         if (call->method->klass->flags & TYPE_ATTRIBUTE_INTERFACE)
2685                 /* Needed by the code generated in inssel.brg */
2686                 mono_get_got_var (cfg);
2687
2688         return call;
2689 }
2690
2691 static MonoCallInst*
2692 mono_emit_method_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method, MonoMethodSignature *sig,
2693                        MonoInst **args, const guint8 *ip, MonoInst *this)
2694 {
2695         return mono_emit_method_call_full (cfg, bblock, method, sig, args, ip, this, FALSE);
2696 }
2697
2698 inline static int
2699 mono_emit_method_call_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,  
2700                        MonoMethodSignature *signature, MonoInst **args, const guint8 *ip, MonoInst *this)
2701 {
2702         MonoCallInst *call = mono_emit_method_call (cfg, bblock, method, signature, args, ip, this);
2703
2704         return mono_spill_call (cfg, bblock, call, signature, method->string_ctor, ip, FALSE);
2705 }
2706
2707 inline static int
2708 mono_emit_method_call_spilled_full (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,  
2709                        MonoMethodSignature *signature, MonoInst **args, const guint8 *ip, MonoInst *this,
2710                        gboolean ret_object, gboolean to_end)
2711 {
2712         MonoCallInst *call = mono_emit_method_call_full (cfg, bblock, method, signature, args, ip, this, to_end);
2713
2714         return mono_spill_call (cfg, bblock, call, signature, ret_object, ip, to_end);
2715 }
2716
2717 inline static int
2718 mono_emit_native_call (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoMethodSignature *sig,
2719                        MonoInst **args, const guint8 *ip, gboolean ret_object, gboolean to_end)
2720 {
2721         MonoCallInst *call;
2722
2723         g_assert (sig);
2724
2725         call = mono_emit_call_args (cfg, bblock, sig, args, FALSE, FALSE, ip, to_end);
2726         call->fptr = func;
2727
2728         return mono_spill_call (cfg, bblock, call, sig, ret_object, ip, to_end);
2729 }
2730
2731 inline static int
2732 mono_emit_jit_icall (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoInst **args, const guint8 *ip)
2733 {
2734         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (func);
2735         
2736         if (!info) {
2737                 g_warning ("unregistered JIT ICall");
2738                 g_assert_not_reached ();
2739         }
2740
2741         return mono_emit_native_call (cfg, bblock, mono_icall_get_wrapper (info), info->sig, args, ip, FALSE, FALSE);
2742 }
2743
2744 static MonoCallInst*
2745 mono_emit_rgctx_method_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method, MonoMethodSignature *sig,
2746                 MonoInst **args, MonoInst *rgctx_arg, const guint8 *ip, MonoInst *this)
2747 {
2748         MonoCallInst *call = mono_emit_method_call_full (cfg, bblock, method, sig, args, ip, this, FALSE);
2749
2750         if (rgctx_arg) {
2751                 switch (call->inst.opcode) {
2752                 case OP_CALL: call->inst.opcode = OP_CALL_RGCTX; break;
2753                 case OP_VOIDCALL: call->inst.opcode = OP_VOIDCALL_RGCTX; break;
2754                 case OP_FCALL: call->inst.opcode = OP_FCALL_RGCTX; break;
2755                 case OP_LCALL: call->inst.opcode = OP_LCALL_RGCTX; break;
2756                 case OP_VCALL: call->inst.opcode = OP_VCALL_RGCTX; break;
2757                 default: g_assert_not_reached ();
2758                 }
2759
2760                 if (call->inst.opcode != OP_VCALL_RGCTX) {
2761                         g_assert (!call->inst.inst_left);
2762                         call->inst.inst_left = rgctx_arg;
2763                 } else {
2764                         g_assert (!call->inst.inst_right);
2765                         call->inst.inst_right = rgctx_arg;
2766                 }
2767         }
2768
2769         return call;
2770 }
2771
2772 inline static int
2773 mono_emit_rgctx_method_call_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,  
2774                 MonoMethodSignature *signature, MonoInst **args, MonoInst *rgctx_arg, const guint8 *ip,
2775                 MonoInst *this)
2776 {
2777         MonoCallInst *call = mono_emit_rgctx_method_call (cfg, bblock, method, signature, args, rgctx_arg, ip, this);
2778
2779         return mono_spill_call (cfg, bblock, call, signature, method->string_ctor, ip, FALSE);
2780 }
2781
2782 static void
2783 mono_emulate_opcode (MonoCompile *cfg, MonoInst *tree, MonoInst **iargs, MonoJitICallInfo *info)
2784 {
2785         MonoInst *ins, *temp = NULL, *store, *load;
2786         MonoInstList *head, *list;
2787         int nargs;
2788         MonoCallInst *call;
2789
2790         //g_print ("emulating: ");
2791         //mono_print_tree_nl (tree);
2792         MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (info->sig->ret, FALSE, FALSE, cfg->generic_sharing_context));
2793         ins = (MonoInst*)call;
2794         MONO_INST_LIST_INIT (&ins->node);
2795         
2796         call->inst.cil_code = tree->cil_code;
2797         call->args = iargs;
2798         call->signature = info->sig;
2799
2800         call = mono_arch_call_opcode (cfg, cfg->cbb, call, FALSE);
2801
2802         if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
2803                 temp = mono_compile_create_var (cfg, info->sig->ret, OP_LOCAL);
2804                 temp->flags |= MONO_INST_IS_TEMP;
2805                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2806                 MONO_INST_LIST_INIT (&store->node);
2807                 /* FIXME: handle CEE_STIND_R4 */
2808                 store->cil_code = tree->cil_code;
2809         } else {
2810                 store = ins;
2811         }
2812
2813         nargs = info->sig->param_count + info->sig->hasthis;
2814
2815         if (nargs) {
2816                 MONO_INST_LIST_ADD_TAIL (&store->node,
2817                                         &call->out_args);
2818                 list = &call->out_args;
2819         } else {
2820                 list = &store->node;
2821         }
2822
2823         if (cfg->prev_ins) {
2824                 /* 
2825                  * This assumes that that in a tree, emulate_opcode is called for a
2826                  * node before it is called for its children. dec_foreach needs to
2827                  * take this into account.
2828                  */
2829                 head = &cfg->prev_ins->node;
2830         } else {
2831                 head = &cfg->cbb->ins_list;
2832         }
2833
2834         MONO_INST_LIST_SPLICE_INIT (list, head);
2835
2836         call->fptr = mono_icall_get_wrapper (info);
2837
2838         if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
2839                 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
2840                 *tree = *load;
2841         }
2842 }
2843
2844 /*
2845  * This entry point could be used later for arbitrary method
2846  * redirection.
2847  */
2848 inline static int
2849 mini_redirect_call (int *temp, MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,  
2850                        MonoMethodSignature *signature, MonoInst **args, const guint8 *ip, MonoInst *this)
2851 {
2852
2853         if (method->klass == mono_defaults.string_class) {
2854                 /* managed string allocation support */
2855                 if (strcmp (method->name, "InternalAllocateStr") == 0) {
2856                         MonoInst *iargs [2];
2857                         MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
2858                         MonoMethod *managed_alloc = mono_gc_get_managed_allocator (vtable, FALSE);
2859                         if (!managed_alloc)
2860                                 return FALSE;
2861                         NEW_VTABLECONST (cfg, iargs [0], vtable);
2862                         iargs [1] = args [0];
2863                         *temp = mono_emit_method_call_spilled (cfg, bblock, managed_alloc, mono_method_signature (managed_alloc), iargs, ip, this);
2864                         return TRUE;
2865                 }
2866         }
2867         return FALSE;
2868 }
2869
2870 static MonoMethodSignature *
2871 mono_get_array_new_va_signature (int arity)
2872 {
2873         static GHashTable *sighash = NULL;
2874         MonoMethodSignature *res;
2875         int i;
2876
2877         mono_jit_lock ();
2878         if (!sighash) {
2879                 sighash = g_hash_table_new (NULL, NULL);
2880         }
2881         else if ((res = g_hash_table_lookup (sighash, GINT_TO_POINTER (arity)))) {
2882                 mono_jit_unlock ();
2883                 return res;
2884         }
2885
2886         res = mono_metadata_signature_alloc (mono_defaults.corlib, arity + 1);
2887
2888         res->pinvoke = 1;
2889 #ifdef MONO_ARCH_VARARG_ICALLS
2890         /* Only set this only some archs since not all backends can handle varargs+pinvoke */
2891         res->call_convention = MONO_CALL_VARARG;
2892 #endif
2893
2894 #ifdef PLATFORM_WIN32
2895         res->call_convention = MONO_CALL_C;
2896 #endif
2897
2898         res->params [0] = &mono_defaults.int_class->byval_arg;  
2899         for (i = 0; i < arity; i++)
2900                 res->params [i + 1] = &mono_defaults.int_class->byval_arg;
2901
2902         res->ret = &mono_defaults.int_class->byval_arg;
2903
2904         g_hash_table_insert (sighash, GINT_TO_POINTER (arity), res);
2905         mono_jit_unlock ();
2906
2907         return res;
2908 }
2909
2910 #ifdef MONO_ARCH_SOFT_FLOAT
2911 static void
2912 handle_store_float (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ptr, MonoInst *val, const unsigned char *ip)
2913 {
2914         MonoInst *iargs [2];
2915         iargs [0] = val;
2916         iargs [1] = ptr;
2917
2918         mono_emit_jit_icall (cfg, bblock, mono_fstore_r4, iargs, ip);
2919 }
2920
2921 static int
2922 handle_load_float (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ptr, const unsigned char *ip)
2923 {
2924         MonoInst *iargs [1];
2925         iargs [0] = ptr;
2926
2927         return mono_emit_jit_icall (cfg, bblock, mono_fload_r4, iargs, ip);
2928 }
2929
2930 #define LDLOC_SOFT_FLOAT(cfg,ins,idx,ip) do {\
2931                 if (header->locals [(idx)]->type == MONO_TYPE_R4 && !header->locals [(idx)]->byref) {   \
2932                         int temp;       \
2933                         NEW_LOCLOADA (cfg, (ins), (idx));       \
2934                         temp = handle_load_float (cfg, bblock, (ins), (ip));    \
2935                         NEW_TEMPLOAD (cfg, (ins), temp);        \
2936                 }       \
2937         } while (0)
2938 #define STLOC_SOFT_FLOAT(cfg,ins,idx,ip) do {\
2939                 if (header->locals [(idx)]->type == MONO_TYPE_R4 && !header->locals [(idx)]->byref) {   \
2940                         int temp;       \
2941                         NEW_LOCLOADA (cfg, (ins), (idx));       \
2942                         handle_store_float (cfg, bblock, (ins), *sp, (ip));     \
2943                         MONO_INST_NEW (cfg, (ins), OP_NOP);     \
2944                 }       \
2945         } while (0)
2946 #define LDARG_SOFT_FLOAT(cfg,ins,idx,ip) do {\
2947                 if (param_types [(idx)]->type == MONO_TYPE_R4 && !param_types [(idx)]->byref) { \
2948                         int temp;       \
2949                         NEW_ARGLOADA (cfg, (ins), (idx));       \
2950                         temp = handle_load_float (cfg, bblock, (ins), (ip));    \
2951                         NEW_TEMPLOAD (cfg, (ins), temp);        \
2952                 }       \
2953         } while (0)
2954 #define STARG_SOFT_FLOAT(cfg,ins,idx,ip) do {\
2955                 if (param_types [(idx)]->type == MONO_TYPE_R4 && !param_types [(idx)]->byref) { \
2956                         int temp;       \
2957                         NEW_ARGLOADA (cfg, (ins), (idx));       \
2958                         handle_store_float (cfg, bblock, (ins), *sp, (ip));     \
2959                         MONO_INST_NEW (cfg, (ins), OP_NOP);     \
2960                 }       \
2961         } while (0)
2962 #else
2963 #define LDLOC_SOFT_FLOAT(cfg,ins,idx,ip)
2964 #define STLOC_SOFT_FLOAT(cfg,ins,idx,ip)
2965 #define LDARG_SOFT_FLOAT(cfg,ins,idx,ip)
2966 #define STARG_SOFT_FLOAT(cfg,ins,idx,ip)
2967 #endif
2968
2969 static MonoMethod*
2970 get_memcpy_method (void)
2971 {
2972         static MonoMethod *memcpy_method = NULL;
2973         if (!memcpy_method) {
2974                 memcpy_method = mono_class_get_method_from_name (mono_defaults.string_class, "memcpy", 3);
2975                 if (!memcpy_method)
2976                         g_error ("Old corlib found. Install a new one");
2977         }
2978         return memcpy_method;
2979 }
2980
2981 static void
2982 handle_stobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, MonoInst *src, const unsigned char *ip, MonoClass *klass, gboolean to_end, gboolean native, gboolean write_barrier) {
2983         MonoInst *iargs [3];
2984         int n;
2985         guint32 align = 0;
2986         MonoMethod *memcpy_method;
2987
2988         g_assert (klass);
2989         /*
2990          * This check breaks with spilled vars... need to handle it during verification anyway.
2991          * g_assert (klass && klass == src->klass && klass == dest->klass);
2992          */
2993
2994         if (native)
2995                 n = mono_class_native_size (klass, &align);
2996         else
2997                 n = mono_class_value_size (klass, &align);
2998
2999 #if HAVE_WRITE_BARRIERS
3000         /* if native is true there should be no references in the struct */
3001         if (write_barrier && klass->has_references && !native) {
3002                 iargs [0] = dest;
3003                 iargs [1] = src;
3004                 NEW_PCONST (cfg, iargs [2], klass);
3005
3006                 mono_emit_jit_icall (cfg, bblock, mono_value_copy, iargs, ip);
3007                 return;
3008         }
3009 #endif
3010
3011         /* FIXME: add write barrier handling */
3012         if ((cfg->opt & MONO_OPT_INTRINS) && !to_end && n <= sizeof (gpointer) * 5) {
3013                 MonoInst *inst;
3014                 if (dest->opcode == OP_LDADDR) {
3015                         /* Keep liveness info correct */
3016                         NEW_DUMMY_STORE (cfg, inst, dest->inst_i0->inst_c0);
3017                         MONO_ADD_INS (bblock, inst);
3018                 }
3019                 NEW_MEMCPY (cfg, inst, dest, src, n, align);
3020                 MONO_ADD_INS (bblock, inst);
3021                 return;
3022         }
3023         iargs [0] = dest;
3024         iargs [1] = src;
3025         NEW_ICONST (cfg, iargs [2], n);
3026
3027         memcpy_method = get_memcpy_method ();
3028         mono_emit_method_call_spilled_full (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL, FALSE, to_end);
3029 }
3030
3031 static MonoMethod*
3032 get_memset_method (void)
3033 {
3034         static MonoMethod *memset_method = NULL;
3035         if (!memset_method) {
3036                 memset_method = mono_class_get_method_from_name (mono_defaults.string_class, "memset", 3);
3037                 if (!memset_method)
3038                         g_error ("Old corlib found. Install a new one");
3039         }
3040         return memset_method;
3041 }
3042
3043 static void
3044 handle_initobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, const guchar *ip, MonoClass *klass, MonoInst **stack_start, MonoInst **sp)
3045 {
3046         MonoInst *iargs [3];
3047         MonoInst *ins, *zero_int32;
3048         int n;
3049         guint32 align;
3050         MonoMethod *memset_method;
3051
3052         NEW_ICONST (cfg, zero_int32, 0);
3053
3054         mono_class_init (klass);
3055         n = mono_class_value_size (klass, &align);
3056         MONO_INST_NEW (cfg, ins, 0);
3057         ins->cil_code = ip;
3058         ins->inst_left = dest;
3059         ins->inst_right = zero_int32;
3060         if (n == 1) {
3061                 ins->opcode = CEE_STIND_I1;
3062                 MONO_ADD_INS (bblock, ins);
3063         } else if ((n == 2) && (align >= 2)) {
3064                 ins->opcode = CEE_STIND_I2;
3065                 MONO_ADD_INS (bblock, ins);
3066         } else if ((n == 2) && (align >= 4)) {
3067                 ins->opcode = CEE_STIND_I4;
3068                 MONO_ADD_INS (bblock, ins);
3069         } else if (n <= sizeof (gpointer) * 5) {
3070                 NEW_MEMSET (cfg, ins, dest, 0, n, align);
3071                 MONO_ADD_INS (bblock, ins);
3072         } else {
3073                 memset_method = get_memset_method ();
3074                 handle_loaded_temps (cfg, bblock, stack_start, sp);
3075                 iargs [0] = dest;
3076                 NEW_ICONST (cfg, iargs [1], 0);
3077                 NEW_ICONST (cfg, iargs [2], n);
3078                 mono_emit_method_call_spilled (cfg, bblock, memset_method, memset_method->signature, iargs, ip, NULL);
3079         }
3080 }
3081
3082 static int
3083 handle_alloc (MonoCompile *cfg, MonoBasicBlock *bblock, MonoClass *klass, gboolean for_box, const guchar *ip)
3084 {
3085         MonoInst *iargs [2];
3086         void *alloc_ftn;
3087
3088         if (cfg->opt & MONO_OPT_SHARED) {
3089                 NEW_DOMAINCONST (cfg, iargs [0]);
3090                 NEW_CLASSCONST (cfg, iargs [1], klass);
3091
3092                 alloc_ftn = mono_object_new;
3093         } else if (cfg->compile_aot && bblock->out_of_line && klass->type_token && klass->image == mono_defaults.corlib) {
3094                 /* This happens often in argument checking code, eg. throw new FooException... */
3095                 /* Avoid relocations by calling a helper function specialized to mscorlib */
3096                 NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (klass->type_token));
3097                 return mono_emit_jit_icall (cfg, bblock, mono_helper_newobj_mscorlib, iargs, ip);
3098         } else {
3099                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
3100                 MonoMethod *managed_alloc = mono_gc_get_managed_allocator (vtable, for_box);
3101                 gboolean pass_lw;
3102
3103                 if (managed_alloc) {
3104                         NEW_VTABLECONST (cfg, iargs [0], vtable);
3105                         return mono_emit_method_call_spilled (cfg, bblock, managed_alloc, mono_method_signature (managed_alloc), iargs, ip, NULL);
3106                 }
3107                 alloc_ftn = mono_class_get_allocation_ftn (vtable, for_box, &pass_lw);
3108                 if (pass_lw) {
3109                         guint32 lw = vtable->klass->instance_size;
3110                         lw = ((lw + (sizeof (gpointer) - 1)) & ~(sizeof (gpointer) - 1)) / sizeof (gpointer);
3111                         NEW_ICONST (cfg, iargs [0], lw);
3112                         NEW_VTABLECONST (cfg, iargs [1], vtable);
3113                 }
3114                 else
3115                         NEW_VTABLECONST (cfg, iargs [0], vtable);
3116         }
3117
3118         return mono_emit_jit_icall (cfg, bblock, alloc_ftn, iargs, ip);
3119 }
3120
3121 static int
3122 handle_alloc_from_inst (MonoCompile *cfg, MonoBasicBlock *bblock, MonoClass *klass, MonoInst *vtable_inst,
3123                 gboolean for_box, const guchar *ip)
3124 {
3125         MonoInst *iargs [2];
3126         MonoMethod *managed_alloc = NULL;
3127         /*
3128           FIXME: we cannot get managed_alloc here because we can't get
3129           the class's vtable (because it's not a closed class)
3130
3131         MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
3132         MonoMethod *managed_alloc = mono_gc_get_managed_allocator (vtable, for_box);
3133         */
3134
3135         g_assert (!(cfg->opt & MONO_OPT_SHARED));
3136         g_assert (!cfg->compile_aot);
3137
3138         if (managed_alloc) {
3139                 iargs [0] = vtable_inst;
3140                 return mono_emit_method_call_spilled (cfg, bblock, managed_alloc, mono_method_signature (managed_alloc), iargs, ip, NULL);
3141         }
3142
3143         iargs [0] = vtable_inst;
3144
3145         return mono_emit_jit_icall (cfg, bblock, mono_object_new_specific, iargs, ip);
3146 }
3147
3148 /**
3149  * Handles unbox of a Nullable<T>, returning a temp variable
3150  * where the result is stored
3151  */
3152 static int
3153 handle_unbox_nullable (MonoCompile* cfg, MonoBasicBlock* bblock, MonoInst* val, const guchar *ip, MonoClass* klass)
3154 {
3155        MonoMethod* method = mono_class_get_method_from_name (klass, "Unbox", 1);
3156        return mono_emit_method_call_spilled (cfg, bblock, method, mono_method_signature (method), &val, ip, NULL);
3157         
3158 }
3159
3160
3161 static MonoInst*
3162 handle_box_copy (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *val, const guchar *ip, MonoClass *klass, int temp)
3163 {
3164         MonoInst *dest, *vtoffset, *add, *vstore;
3165
3166         NEW_TEMPLOAD (cfg, dest, temp);
3167         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
3168         MONO_INST_NEW (cfg, add, OP_PADD);
3169         add->inst_left = dest;
3170         add->inst_right = vtoffset;
3171         add->cil_code = ip;
3172         add->klass = klass;
3173         MONO_INST_NEW (cfg, vstore, CEE_STIND_I);
3174         vstore->opcode = mini_type_to_stind (cfg, &klass->byval_arg);
3175         vstore->cil_code = ip;
3176         vstore->inst_left = add;
3177         vstore->inst_right = val;
3178
3179 #ifdef MONO_ARCH_SOFT_FLOAT
3180         if (vstore->opcode == CEE_STIND_R4) {
3181                 handle_store_float (cfg, bblock, add, val, ip);
3182         } else
3183 #endif
3184         if (vstore->opcode == CEE_STOBJ) {
3185                 handle_stobj (cfg, bblock, add, val, ip, klass, FALSE, FALSE, TRUE);
3186         } else
3187                 MONO_ADD_INS (bblock, vstore);
3188
3189         NEW_TEMPLOAD (cfg, dest, temp);
3190         return dest;
3191 }
3192
3193 static MonoInst *
3194 handle_box (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *val, const guchar *ip, MonoClass *klass)
3195 {
3196         MonoInst *dest;
3197         int temp;
3198
3199         if (mono_class_is_nullable (klass)) {
3200                 MonoMethod* method = mono_class_get_method_from_name (klass, "Box", 1);
3201                 temp = mono_emit_method_call_spilled (cfg, bblock, method, mono_method_signature (method), &val, ip, NULL);
3202                 NEW_TEMPLOAD (cfg, dest, temp);
3203                 return dest;
3204         }
3205
3206         temp = handle_alloc (cfg, bblock, klass, TRUE, ip);
3207
3208         return handle_box_copy (cfg, bblock, val, ip, klass, temp);
3209 }
3210
3211 static MonoInst *
3212 handle_box_from_inst (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *val, const guchar *ip,
3213                 MonoClass *klass, MonoInst *vtable_inst)
3214 {
3215         int temp;
3216
3217         g_assert (!mono_class_is_nullable (klass));
3218
3219         temp = handle_alloc_from_inst (cfg, bblock, klass, vtable_inst, TRUE, ip);
3220
3221         return handle_box_copy (cfg, bblock, val, ip, klass, temp);
3222 }
3223
3224 static MonoInst*
3225 handle_delegate_ctor (MonoCompile *cfg, MonoBasicBlock *bblock, MonoClass *klass, MonoInst *target, MonoMethod *method, unsigned char *ip)
3226 {
3227         gpointer *trampoline;
3228         MonoInst *obj, *ins, *store, *offset_ins, *method_ins, *tramp_ins;
3229         int temp;
3230
3231         temp = handle_alloc (cfg, bblock, klass, FALSE, ip);
3232
3233         /* Inline the contents of mono_delegate_ctor */
3234
3235         /* Set target field */
3236         /* Optimize away setting of NULL target */
3237         if (!(target->opcode == OP_PCONST && target->inst_p0 == 0)) {
3238                 NEW_TEMPLOAD (cfg, obj, temp);
3239                 NEW_ICONST (cfg, offset_ins, G_STRUCT_OFFSET (MonoDelegate, target));
3240                 MONO_INST_NEW (cfg, ins, OP_PADD);
3241                 ins->cil_code = ip;
3242                 ins->inst_left = obj;
3243                 ins->inst_right = offset_ins;
3244
3245                 MONO_INST_NEW (cfg, store, CEE_STIND_REF);
3246                 store->cil_code = ip;
3247                 store->inst_left = ins;
3248                 store->inst_right = target;
3249                 mono_bblock_add_inst (bblock, store);
3250         }
3251
3252         /* Set method field */
3253         NEW_TEMPLOAD (cfg, obj, temp);
3254         NEW_ICONST (cfg, offset_ins, G_STRUCT_OFFSET (MonoDelegate, method));
3255         MONO_INST_NEW (cfg, ins, OP_PADD);
3256         ins->cil_code = ip;
3257         ins->inst_left = obj;
3258         ins->inst_right = offset_ins;
3259
3260         NEW_METHODCONST (cfg, method_ins, method);
3261
3262         MONO_INST_NEW (cfg, store, CEE_STIND_I);
3263         store->cil_code = ip;
3264         store->inst_left = ins;
3265         store->inst_right = method_ins;
3266         mono_bblock_add_inst (bblock, store);
3267
3268         /* Set invoke_impl field */
3269         NEW_TEMPLOAD (cfg, obj, temp);
3270         NEW_ICONST (cfg, offset_ins, G_STRUCT_OFFSET (MonoDelegate, invoke_impl));
3271         MONO_INST_NEW (cfg, ins, OP_PADD);
3272         ins->cil_code = ip;
3273         ins->inst_left = obj;
3274         ins->inst_right = offset_ins;
3275
3276         trampoline = mono_create_delegate_trampoline (klass);
3277         NEW_AOTCONST (cfg, tramp_ins, MONO_PATCH_INFO_ABS, trampoline);
3278
3279         MONO_INST_NEW (cfg, store, CEE_STIND_I);
3280         store->cil_code = ip;
3281         store->inst_left = ins;
3282         store->inst_right = tramp_ins;
3283         mono_bblock_add_inst (bblock, store);
3284
3285         /* All the checks which are in mono_delegate_ctor () are done by the delegate trampoline */
3286
3287         NEW_TEMPLOAD (cfg, obj, temp);
3288
3289         return obj;
3290 }
3291
3292 static int
3293 handle_array_new (MonoCompile *cfg, MonoBasicBlock *bblock, int rank, MonoInst **sp, unsigned char *ip)
3294 {
3295         MonoMethodSignature *esig;
3296         char icall_name [256];
3297         char *name;
3298         MonoJitICallInfo *info;
3299
3300         /* Need to register the icall so it gets an icall wrapper */
3301         sprintf (icall_name, "ves_array_new_va_%d", rank);
3302
3303         mono_jit_lock ();
3304         info = mono_find_jit_icall_by_name (icall_name);
3305         if (info == NULL) {
3306                 esig = mono_get_array_new_va_signature (rank);
3307                 name = g_strdup (icall_name);
3308                 info = mono_register_jit_icall (mono_array_new_va, name, esig, FALSE);
3309
3310                 g_hash_table_insert (jit_icall_name_hash, name, name);
3311         }
3312         mono_jit_unlock ();
3313
3314         cfg->flags |= MONO_CFG_HAS_VARARGS;
3315
3316         /* FIXME: This uses info->sig, but it should use the signature of the wrapper */
3317         return mono_emit_native_call (cfg, bblock, mono_icall_get_wrapper (info), info->sig, sp, ip, TRUE, FALSE);
3318 }
3319
3320 static void
3321 mono_emit_load_got_addr (MonoCompile *cfg)
3322 {
3323         MonoInst *load, *store, *dummy_use;
3324         MonoInst *get_got;
3325
3326         if (!cfg->got_var || cfg->got_var_allocated)
3327                 return;
3328
3329         MONO_INST_NEW (cfg, get_got, OP_LOAD_GOTADDR);
3330         NEW_TEMPSTORE (cfg, store, cfg->got_var->inst_c0, get_got);
3331
3332         /* Add it to the start of the first bblock */
3333         MONO_INST_LIST_ADD (&store->node, &cfg->bb_entry->ins_list);
3334
3335         cfg->got_var_allocated = TRUE;
3336
3337         /* 
3338          * Add a dummy use to keep the got_var alive, since real uses might
3339          * only be generated in the decompose or instruction selection phases.
3340          * Add it to end_bblock, so the variable's lifetime covers the whole
3341          * method.
3342          */
3343         NEW_TEMPLOAD (cfg, load, cfg->got_var->inst_c0);
3344         NEW_DUMMY_USE (cfg, dummy_use, load);
3345         MONO_ADD_INS (cfg->bb_exit, dummy_use);
3346 }
3347
3348 #define CODE_IS_STLOC(ip) (((ip) [0] >= CEE_STLOC_0 && (ip) [0] <= CEE_STLOC_3) || ((ip) [0] == CEE_STLOC_S))
3349
3350 static gboolean
3351 mini_class_is_system_array (MonoClass *klass)
3352 {
3353         if (klass->parent == mono_defaults.array_class)
3354                 return TRUE;
3355         else
3356                 return FALSE;
3357 }
3358
3359 static gboolean
3360 mono_method_check_inlining (MonoCompile *cfg, MonoMethod *method)
3361 {
3362         MonoMethodHeader *header = mono_method_get_header (method);
3363         MonoMethodSignature *signature = mono_method_signature (method);
3364         MonoVTable *vtable;
3365         int i;
3366
3367         if (cfg->generic_sharing_context)
3368                 return FALSE;
3369
3370         if (method->inline_failure)
3371                 return FALSE;
3372
3373 #ifdef MONO_ARCH_HAVE_LMF_OPS
3374         if (((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
3375                  (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) &&
3376             !MONO_TYPE_ISSTRUCT (signature->ret) && !mini_class_is_system_array (method->klass))
3377                 return TRUE;
3378 #endif
3379
3380         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3381             (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
3382             (method->iflags & METHOD_IMPL_ATTRIBUTE_NOINLINING) ||
3383             (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) ||
3384             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3385             (method->klass->marshalbyref) ||
3386             !header || header->num_clauses ||
3387             /* fixme: why cant we inline valuetype returns? */
3388             MONO_TYPE_ISSTRUCT (signature->ret))
3389                 return FALSE;
3390
3391 #ifdef MONO_ARCH_SOFT_FLOAT
3392         /* this complicates things, fix later */
3393         if (signature->ret->type == MONO_TYPE_R4)
3394                 return FALSE;
3395 #endif
3396         /* its not worth to inline methods with valuetype arguments?? */
3397         for (i = 0; i < signature->param_count; i++) {
3398                 if (MONO_TYPE_ISSTRUCT (signature->params [i])) {
3399                         return FALSE;
3400                 }
3401 #ifdef MONO_ARCH_SOFT_FLOAT
3402                 /* this complicates things, fix later */
3403                 if (!signature->params [i]->byref && signature->params [i]->type == MONO_TYPE_R4)
3404                         return FALSE;
3405 #endif
3406         }
3407
3408         /*
3409          * if we can initialize the class of the method right away, we do,
3410          * otherwise we don't allow inlining if the class needs initialization,
3411          * since it would mean inserting a call to mono_runtime_class_init()
3412          * inside the inlined code
3413          */
3414         if (!(cfg->opt & MONO_OPT_SHARED)) {
3415                 vtable = mono_class_vtable (cfg->domain, method->klass);
3416                 if (method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) {
3417                         if (cfg->run_cctors && method->klass->has_cctor) {
3418                                 /* This makes so that inline cannot trigger */
3419                                 /* .cctors: too many apps depend on them */
3420                                 /* running with a specific order... */
3421                                 if (! vtable->initialized)
3422                                         return FALSE;
3423                                 mono_runtime_class_init (vtable);
3424                         }
3425                 }
3426                 else if (!vtable->initialized && mono_class_needs_cctor_run (method->klass, NULL))
3427                         return FALSE;
3428         } else {
3429                 /* 
3430                  * If we're compiling for shared code
3431                  * the cctor will need to be run at aot method load time, for example,
3432                  * or at the end of the compilation of the inlining method.
3433                  */
3434                 if (mono_class_needs_cctor_run (method->klass, NULL) && !((method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3435                         return FALSE;
3436         }
3437         //if (!MONO_TYPE_IS_VOID (signature->ret)) return FALSE;
3438
3439         /*
3440          * CAS - do not inline methods with declarative security
3441          * Note: this has to be before any possible return TRUE;
3442          */
3443         if (mono_method_has_declsec (method))
3444                 return FALSE;
3445
3446         /* also consider num_locals? */
3447         if (getenv ("MONO_INLINELIMIT")) {
3448                 if (header->code_size < atoi (getenv ("MONO_INLINELIMIT"))) {
3449                         return TRUE;
3450                 }
3451         } else if (header->code_size < INLINE_LENGTH_LIMIT)
3452                 return TRUE;
3453
3454         return FALSE;
3455 }
3456
3457 static gboolean
3458 mini_field_access_needs_cctor_run (MonoCompile *cfg, MonoMethod *method, MonoVTable *vtable)
3459 {
3460         if (vtable->initialized && !cfg->compile_aot)
3461                 return FALSE;
3462
3463         if (vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)
3464                 return FALSE;
3465
3466         if (!mono_class_needs_cctor_run (vtable->klass, method))
3467                 return FALSE;
3468
3469         if (! (method->flags & METHOD_ATTRIBUTE_STATIC) && (vtable->klass == method->klass))
3470                 /* The initialization is already done before the method is called */
3471                 return FALSE;
3472
3473         return TRUE;
3474 }
3475
3476 static MonoInst*
3477 mini_get_ldelema_ins (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *cmethod, MonoInst **sp, unsigned char *ip, gboolean is_set)
3478 {
3479         int temp, rank;
3480         MonoInst *addr;
3481         MonoMethod *addr_method;
3482         int element_size;
3483
3484         rank = mono_method_signature (cmethod)->param_count - (is_set? 1: 0);
3485
3486         if (rank == 1) {
3487                 MONO_INST_NEW (cfg, addr, CEE_LDELEMA);
3488                 addr->inst_left = sp [0];
3489                 addr->inst_right = sp [1];
3490                 addr->cil_code = ip;
3491                 addr->type = STACK_MP;
3492                 addr->klass = cmethod->klass->element_class;
3493                 return addr;
3494         }
3495
3496         if (rank == 2 && (cfg->opt & MONO_OPT_INTRINS)) {
3497 #if defined(MONO_ARCH_EMULATE_MUL_DIV) && !defined(MONO_ARCH_NO_EMULATE_MUL)
3498                 /* OP_LDELEMA2D depends on OP_LMUL */
3499 #else
3500                 MonoInst *indexes;
3501                 NEW_GROUP (cfg, indexes, sp [1], sp [2]);
3502                 MONO_INST_NEW (cfg, addr, OP_LDELEMA2D);
3503                 addr->inst_left = sp [0];
3504                 addr->inst_right = indexes;
3505                 addr->cil_code = ip;
3506                 addr->type = STACK_MP;
3507                 addr->klass = cmethod->klass->element_class;
3508                 return addr;
3509 #endif
3510         }
3511
3512         element_size = mono_class_array_element_size (cmethod->klass->element_class);
3513         addr_method = mono_marshal_get_array_address (rank, element_size);
3514         temp = mono_emit_method_call_spilled (cfg, bblock, addr_method, addr_method->signature, sp, ip, NULL);
3515         NEW_TEMPLOAD (cfg, addr, temp);
3516         return addr;
3517
3518 }
3519
3520 static MonoJitICallInfo **emul_opcode_map = NULL;
3521
3522 MonoJitICallInfo *
3523 mono_find_jit_opcode_emulation (int opcode)
3524 {
3525         g_assert (opcode >= 0 && opcode <= OP_LAST);
3526         if  (emul_opcode_map)
3527                 return emul_opcode_map [opcode];
3528         else
3529                 return NULL;
3530 }
3531
3532 static int
3533 is_unsigned_regsize_type (MonoType *type)
3534 {
3535         switch (type->type) {
3536         case MONO_TYPE_U1:
3537         case MONO_TYPE_U2:
3538         case MONO_TYPE_U4:
3539 #if SIZEOF_VOID_P == 8
3540         /*case MONO_TYPE_U8: this requires different opcodes in inssel.brg */
3541 #endif
3542                 return TRUE;
3543         default:
3544                 return FALSE;
3545         }
3546 }
3547
3548 static MonoInst*
3549 mini_get_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
3550 {
3551         MonoInst *ins = NULL;
3552         
3553         static MonoClass *runtime_helpers_class = NULL;
3554         if (! runtime_helpers_class)
3555                 runtime_helpers_class = mono_class_from_name (mono_defaults.corlib,
3556                         "System.Runtime.CompilerServices", "RuntimeHelpers");
3557
3558         if (cmethod->klass == mono_defaults.string_class) {
3559                 if (strcmp (cmethod->name, "get_Chars") == 0) {
3560                         MONO_INST_NEW (cfg, ins, OP_GETCHR);
3561                         ins->inst_i0 = args [0];
3562                         ins->inst_i1 = args [1];
3563                         return ins;
3564                 } else if (strcmp (cmethod->name, "get_Length") == 0) {
3565                         MONO_INST_NEW (cfg, ins, OP_STRLEN);
3566                         ins->inst_i0 = args [0];
3567                         return ins;
3568                 } else if (strcmp (cmethod->name, "InternalSetChar") == 0) {
3569                         MonoInst *get_addr;
3570                         MONO_INST_NEW (cfg, get_addr, OP_STR_CHAR_ADDR);
3571                         get_addr->inst_i0 = args [0];
3572                         get_addr->inst_i1 = args [1];
3573                         MONO_INST_NEW (cfg, ins, CEE_STIND_I2);
3574                         ins->inst_i0 = get_addr;
3575                         ins->inst_i1 = args [2];
3576                         return ins;
3577                 } else 
3578                         return NULL;
3579         } else if (cmethod->klass == mono_defaults.object_class) {
3580                 if (strcmp (cmethod->name, "GetType") == 0) {
3581                         MONO_INST_NEW (cfg, ins, OP_GETTYPE);
3582                         ins->inst_i0 = args [0];
3583                         return ins;
3584                 /* The OP_GETHASHCODE rule depends on OP_MUL */
3585 #if !defined(MONO_ARCH_EMULATE_MUL_DIV) && !defined(HAVE_MOVING_COLLECTOR)
3586                 } else if (strcmp (cmethod->name, "InternalGetHashCode") == 0) {
3587                         MONO_INST_NEW (cfg, ins, OP_GETHASHCODE);
3588                         ins->inst_i0 = args [0];
3589                         return ins;
3590 #endif
3591                 } else if (strcmp (cmethod->name, ".ctor") == 0) {
3592                         MONO_INST_NEW (cfg, ins, OP_NOP);
3593                         return ins;
3594                 } else
3595                         return NULL;
3596         } else if (cmethod->klass == mono_defaults.array_class) {
3597                 if (cmethod->name [0] != 'g')
3598                         return NULL;
3599
3600                 if (strcmp (cmethod->name, "get_Rank") == 0) {
3601                         MONO_INST_NEW (cfg, ins, OP_ARRAY_RANK);
3602                         ins->inst_i0 = args [0];
3603                         return ins;
3604                 } else if (strcmp (cmethod->name, "get_Length") == 0) {
3605                         MONO_INST_NEW (cfg, ins, CEE_LDLEN);
3606                         ins->inst_i0 = args [0];
3607                         return ins;
3608                 } else
3609                         return NULL;
3610         } else if (cmethod->klass == runtime_helpers_class) {
3611                 if (strcmp (cmethod->name, "get_OffsetToStringData") == 0) {
3612                         NEW_ICONST (cfg, ins, G_STRUCT_OFFSET (MonoString, chars));
3613                         return ins;
3614                 } else
3615                         return NULL;
3616         } else if (cmethod->klass == mono_defaults.thread_class) {
3617                 if (strcmp (cmethod->name, "get_CurrentThread") == 0 && (ins = mono_arch_get_thread_intrinsic (cfg)))
3618                         return ins;
3619                 if (strcmp (cmethod->name, "MemoryBarrier") == 0) {
3620                         MONO_INST_NEW (cfg, ins, OP_MEMORY_BARRIER);
3621                         return ins;
3622                 }
3623         } else if (mini_class_is_system_array (cmethod->klass) &&
3624                         strcmp (cmethod->name, "GetGenericValueImpl") == 0) {
3625                 MonoInst *sp [2];
3626                 MonoInst *ldelem, *store, *load;
3627                 MonoClass *eklass = mono_class_from_mono_type (fsig->params [1]);
3628                 int n;
3629                 n = mini_type_to_stind (cfg, &eklass->byval_arg);
3630                 if (n == CEE_STOBJ)
3631                         return NULL;
3632                 sp [0] = args [0];
3633                 sp [1] = args [1];
3634                 NEW_LDELEMA (cfg, ldelem, sp, eklass);
3635                 ldelem->flags |= MONO_INST_NORANGECHECK;
3636                 MONO_INST_NEW (cfg, store, n);
3637                 MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, &eklass->byval_arg));
3638                 type_to_eval_stack_type (cfg, &eklass->byval_arg, load);
3639                 load->inst_left = ldelem;
3640                 store->inst_left = args [2];
3641                 store->inst_right = load;
3642                 return store;
3643         } else if (cmethod->klass == mono_defaults.math_class) {
3644                 if (strcmp (cmethod->name, "Min") == 0) {
3645                         if (is_unsigned_regsize_type (fsig->params [0])) {
3646                                 MONO_INST_NEW (cfg, ins, OP_MIN);
3647                                 ins->inst_i0 = args [0];
3648                                 ins->inst_i1 = args [1];
3649                                 return ins;
3650                         }
3651                 } else if (strcmp (cmethod->name, "Max") == 0) {
3652                         if (is_unsigned_regsize_type (fsig->params [0])) {
3653                                 MONO_INST_NEW (cfg, ins, OP_MAX);
3654                                 ins->inst_i0 = args [0];
3655                                 ins->inst_i1 = args [1];
3656                                 return ins;
3657                         }
3658                 }
3659         } else if (cmethod->klass->image == mono_defaults.corlib &&
3660                            (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
3661                            (strcmp (cmethod->klass->name, "Interlocked") == 0)) {
3662                 ins = NULL;
3663
3664 #if SIZEOF_VOID_P == 8
3665                 if (strcmp (cmethod->name, "Read") == 0 && (fsig->params [0]->type == MONO_TYPE_I8)) {
3666                         /* 64 bit reads are already atomic */
3667                         MONO_INST_NEW (cfg, ins, CEE_LDIND_I8);
3668                         ins->inst_i0 = args [0];
3669                 }
3670 #endif
3671
3672 #ifdef MONO_ARCH_HAVE_ATOMIC_ADD
3673                 if (strcmp (cmethod->name, "Increment") == 0) {
3674                         MonoInst *ins_iconst;
3675                         guint32 opcode;
3676
3677                         if (fsig->params [0]->type == MONO_TYPE_I4)
3678                                 opcode = OP_ATOMIC_ADD_NEW_I4;
3679                         else if (fsig->params [0]->type == MONO_TYPE_I8)
3680                                 opcode = OP_ATOMIC_ADD_NEW_I8;
3681                         else
3682                                 g_assert_not_reached ();
3683
3684 #if SIZEOF_VOID_P == 4
3685                         if (opcode == OP_ATOMIC_ADD_NEW_I8)
3686                                 return NULL;
3687 #endif
3688
3689                         MONO_INST_NEW (cfg, ins, opcode);
3690                         MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
3691                         ins_iconst->inst_c0 = 1;
3692
3693                         ins->inst_i0 = args [0];
3694                         ins->inst_i1 = ins_iconst;
3695                 } else if (strcmp (cmethod->name, "Decrement") == 0) {
3696                         MonoInst *ins_iconst;
3697                         guint32 opcode;
3698
3699                         if (fsig->params [0]->type == MONO_TYPE_I4)
3700                                 opcode = OP_ATOMIC_ADD_NEW_I4;
3701                         else if (fsig->params [0]->type == MONO_TYPE_I8)
3702                                 opcode = OP_ATOMIC_ADD_NEW_I8;
3703                         else
3704                                 g_assert_not_reached ();
3705
3706 #if SIZEOF_VOID_P == 4
3707                         if (opcode == OP_ATOMIC_ADD_NEW_I8)
3708                                 return NULL;
3709 #endif
3710
3711                         MONO_INST_NEW (cfg, ins, opcode);
3712                         MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
3713                         ins_iconst->inst_c0 = -1;
3714
3715                         ins->inst_i0 = args [0];
3716                         ins->inst_i1 = ins_iconst;
3717                 } else if (strcmp (cmethod->name, "Add") == 0) {
3718                         guint32 opcode;
3719
3720                         if (fsig->params [0]->type == MONO_TYPE_I4)
3721                                 opcode = OP_ATOMIC_ADD_NEW_I4;
3722                         else if (fsig->params [0]->type == MONO_TYPE_I8)
3723                                 opcode = OP_ATOMIC_ADD_NEW_I8;
3724                         else
3725                                 g_assert_not_reached ();
3726
3727 #if SIZEOF_VOID_P == 4
3728                         if (opcode == OP_ATOMIC_ADD_NEW_I8)
3729                                 return NULL;
3730 #endif
3731                         
3732                         MONO_INST_NEW (cfg, ins, opcode);
3733
3734                         ins->inst_i0 = args [0];
3735                         ins->inst_i1 = args [1];
3736                 }
3737 #endif /* MONO_ARCH_HAVE_ATOMIC_ADD */
3738
3739 #ifdef MONO_ARCH_HAVE_ATOMIC_EXCHANGE
3740                 if (strcmp (cmethod->name, "Exchange") == 0) {
3741                         guint32 opcode;
3742
3743                         if (fsig->params [0]->type == MONO_TYPE_I4)
3744                                 opcode = OP_ATOMIC_EXCHANGE_I4;
3745 #if SIZEOF_VOID_P == 8
3746                         else if ((fsig->params [0]->type == MONO_TYPE_I8) ||
3747                                          (fsig->params [0]->type == MONO_TYPE_I) ||
3748                                          (fsig->params [0]->type == MONO_TYPE_OBJECT))
3749                                 opcode = OP_ATOMIC_EXCHANGE_I8;
3750 #else
3751                         else if ((fsig->params [0]->type == MONO_TYPE_I) ||
3752                                          (fsig->params [0]->type == MONO_TYPE_OBJECT))
3753                                 opcode = OP_ATOMIC_EXCHANGE_I4;
3754 #endif
3755                         else
3756                                 return NULL;
3757
3758 #if SIZEOF_VOID_P == 4
3759                         if (opcode == OP_ATOMIC_EXCHANGE_I8)
3760                                 return NULL;
3761 #endif
3762
3763                         MONO_INST_NEW (cfg, ins, opcode);
3764
3765                         ins->inst_i0 = args [0];
3766                         ins->inst_i1 = args [1];
3767                 }
3768 #endif /* MONO_ARCH_HAVE_ATOMIC_EXCHANGE */
3769
3770                 if (ins)
3771                         return ins;
3772         } else if (cmethod->klass->image == mono_defaults.corlib) {
3773                 if (cmethod->name [0] == 'B' && strcmp (cmethod->name, "Break") == 0
3774                                 && strcmp (cmethod->klass->name, "Debugger") == 0) {
3775                         MONO_INST_NEW (cfg, ins, OP_BREAK);
3776                         return ins;
3777                 }
3778                 if (cmethod->name [0] == 'g' && strcmp (cmethod->name, "get_IsRunningOnWindows") == 0
3779                                 && strcmp (cmethod->klass->name, "Environment") == 0) {
3780 #ifdef PLATFORM_WIN32
3781                         NEW_ICONST (cfg, ins, 1);
3782 #else
3783                         NEW_ICONST (cfg, ins, 0);
3784 #endif
3785                         return ins;
3786                 }
3787         }
3788
3789         return mono_arch_get_inst_for_method (cfg, cmethod, fsig, args);
3790 }
3791
3792 static void
3793 mono_save_args (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, MonoInst **sp, MonoInst **args)
3794 {
3795         MonoInst *store, *temp;
3796         int i;
3797
3798         g_assert (!MONO_TYPE_ISSTRUCT (sig->ret));
3799
3800         if (!sig->hasthis && sig->param_count == 0) 
3801                 return;
3802
3803         if (sig->hasthis) {
3804                 if (sp [0]->opcode == OP_ICONST) {
3805                         *args++ = sp [0];
3806                 } else {
3807                         temp = mono_compile_create_var (cfg, type_from_stack_type (*sp), OP_LOCAL);
3808                         *args++ = temp;
3809                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
3810                         /* FIXME: handle CEE_STIND_R4 */
3811                         store->cil_code = sp [0]->cil_code;
3812                         MONO_ADD_INS (bblock, store);
3813                 }
3814                 sp++;
3815         }
3816
3817         for (i = 0; i < sig->param_count; ++i) {
3818                 if (sp [0]->opcode == OP_ICONST) {
3819                         *args++ = sp [0];
3820                 } else {
3821                         temp = mono_compile_create_var (cfg, sig->params [i], OP_LOCAL);
3822                         *args++ = temp;
3823                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
3824                         store->cil_code = sp [0]->cil_code;
3825                         /* FIXME: handle CEE_STIND_R4 */
3826                         if (store->opcode == CEE_STOBJ) {
3827                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
3828                                 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, temp->klass, FALSE, FALSE, FALSE);
3829 #ifdef MONO_ARCH_SOFT_FLOAT
3830                         } else if (store->opcode == CEE_STIND_R4) {
3831                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
3832                                 handle_store_float (cfg, bblock, store, *sp, sp [0]->cil_code);
3833 #endif
3834                         } else {
3835                                 MONO_ADD_INS (bblock, store);
3836                         } 
3837                 }
3838                 sp++;
3839         }
3840 }
3841 #define MONO_INLINE_CALLED_LIMITED_METHODS 0
3842 #define MONO_INLINE_CALLER_LIMITED_METHODS 0
3843
3844 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
3845 static char*
3846 mono_inline_called_method_name_limit = NULL;
3847 static gboolean check_inline_called_method_name_limit (MonoMethod *called_method) {
3848         char *called_method_name = mono_method_full_name (called_method, TRUE);
3849         int strncmp_result;
3850         
3851         if (mono_inline_called_method_name_limit == NULL) {
3852                 char *limit_string = getenv ("MONO_INLINE_CALLED_METHOD_NAME_LIMIT");
3853                 if (limit_string != NULL) {
3854                         mono_inline_called_method_name_limit = limit_string;
3855                 } else {
3856                         mono_inline_called_method_name_limit = (char *) "";
3857                 }
3858         }
3859         
3860         strncmp_result = strncmp (called_method_name, mono_inline_called_method_name_limit, strlen (mono_inline_called_method_name_limit));
3861         g_free (called_method_name);
3862         
3863         //return (strncmp_result <= 0);
3864         return (strncmp_result == 0);
3865 }
3866 #endif
3867
3868 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
3869 static char*
3870 mono_inline_caller_method_name_limit = NULL;
3871 static gboolean check_inline_caller_method_name_limit (MonoMethod *caller_method) {
3872         char *caller_method_name = mono_method_full_name (caller_method, TRUE);
3873         int strncmp_result;
3874         
3875         if (mono_inline_caller_method_name_limit == NULL) {
3876                 char *limit_string = getenv ("MONO_INLINE_CALLER_METHOD_NAME_LIMIT");
3877                 if (limit_string != NULL) {
3878                         mono_inline_caller_method_name_limit = limit_string;
3879                 } else {
3880                         mono_inline_caller_method_name_limit = (char *) "";
3881                 }
3882         }
3883         
3884         strncmp_result = strncmp (caller_method_name, mono_inline_caller_method_name_limit, strlen (mono_inline_caller_method_name_limit));
3885         g_free (caller_method_name);
3886         
3887         //return (strncmp_result <= 0);
3888         return (strncmp_result == 0);
3889 }
3890 #endif
3891
3892 static int
3893 inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoBasicBlock *bblock, MonoInst **sp,
3894                 guchar *ip, guint real_offset, GList *dont_inline, MonoBasicBlock **last_b, gboolean inline_allways)
3895 {
3896         MonoInst *ins, *rvar = NULL;
3897         MonoMethodHeader *cheader;
3898         MonoBasicBlock *ebblock, *sbblock;
3899         int i, costs, new_locals_offset;
3900         MonoMethod *prev_inlined_method;
3901         MonoBasicBlock **prev_cil_offset_to_bb;
3902         unsigned char* prev_cil_start;
3903         guint32 prev_cil_offset_to_bb_len;
3904
3905         g_assert (cfg->exception_type == MONO_EXCEPTION_NONE);
3906
3907 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
3908         if ((! inline_allways) && ! check_inline_called_method_name_limit (cmethod))
3909                 return 0;
3910 #endif
3911 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
3912         if ((! inline_allways) && ! check_inline_caller_method_name_limit (cfg->method))
3913                 return 0;
3914 #endif
3915
3916         if (bblock->out_of_line && !inline_allways)
3917                 return 0;
3918
3919         if (cfg->verbose_level > 2)
3920                 g_print ("INLINE START %p %s -> %s\n", cmethod,  mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
3921
3922         if (!cmethod->inline_info) {
3923                 mono_jit_stats.inlineable_methods++;
3924                 cmethod->inline_info = 1;
3925         }
3926         /* allocate space to store the return value */
3927         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
3928                 rvar =  mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
3929         }
3930
3931         /* allocate local variables */
3932         cheader = mono_method_get_header (cmethod);
3933         new_locals_offset = cfg->num_varinfo;
3934         for (i = 0; i < cheader->num_locals; ++i)
3935                 mono_compile_create_var (cfg, cheader->locals [i], OP_LOCAL);
3936
3937         /* allocate starte and end blocks */
3938         NEW_BBLOCK (cfg, sbblock);
3939         sbblock->block_num = cfg->num_bblocks++;
3940         sbblock->real_offset = real_offset;
3941
3942         NEW_BBLOCK (cfg, ebblock);
3943         ebblock->block_num = cfg->num_bblocks++;
3944         ebblock->real_offset = real_offset;
3945
3946         prev_inlined_method = cfg->inlined_method;
3947         cfg->inlined_method = cmethod;
3948         prev_cil_offset_to_bb = cfg->cil_offset_to_bb;
3949         prev_cil_offset_to_bb_len = cfg->cil_offset_to_bb_len;
3950         prev_cil_start = cfg->cil_start;
3951
3952         costs = mono_method_to_ir (cfg, cmethod, sbblock, ebblock, new_locals_offset, rvar, dont_inline, sp, real_offset, *ip == CEE_CALLVIRT);
3953
3954         cfg->inlined_method = prev_inlined_method;
3955         cfg->cil_offset_to_bb = prev_cil_offset_to_bb;
3956         cfg->cil_offset_to_bb_len = prev_cil_offset_to_bb_len;
3957         cfg->cil_start = prev_cil_start;
3958
3959         if ((costs >= 0 && costs < 60) || inline_allways) {
3960                 if (cfg->verbose_level > 2)
3961                         g_print ("INLINE END %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
3962                 
3963                 mono_jit_stats.inlined_methods++;
3964
3965                 /* always add some code to avoid block split failures */
3966                 MONO_INST_NEW (cfg, ins, OP_NOP);
3967                 MONO_ADD_INS (bblock, ins);
3968                 ins->cil_code = ip;
3969
3970                 bblock->next_bb = sbblock;
3971                 link_bblock (cfg, bblock, sbblock);
3972
3973                 if (rvar) {
3974                         NEW_TEMPLOAD (cfg, ins, rvar->inst_c0);
3975 #ifdef MONO_ARCH_SOFT_FLOAT
3976                         if (ins->opcode == CEE_LDIND_R4) {
3977                                 int temp;
3978                                 NEW_TEMPLOADA (cfg, ins, rvar->inst_c0);
3979                                 temp = handle_load_float (cfg, bblock, ins, ip);
3980                                 NEW_TEMPLOAD (cfg, ins, temp);
3981                         }
3982 #endif
3983                         *sp++ = ins;
3984                 }
3985                 *last_b = ebblock;
3986                 return costs + 1;
3987         } else {
3988                 if (cfg->verbose_level > 2)
3989                         g_print ("INLINE ABORTED %s\n", mono_method_full_name (cmethod, TRUE));
3990                 cfg->exception_type = MONO_EXCEPTION_NONE;
3991                 mono_loader_clear_error ();
3992                 cmethod->inline_failure = TRUE;
3993         }
3994         return 0;
3995 }
3996
3997 /*
3998  * Some of these comments may well be out-of-date.
3999  * Design decisions: we do a single pass over the IL code (and we do bblock 
4000  * splitting/merging in the few cases when it's required: a back jump to an IL
4001  * address that was not already seen as bblock starting point).
4002  * Code is validated as we go (full verification is still better left to metadata/verify.c).
4003  * Complex operations are decomposed in simpler ones right away. We need to let the 
4004  * arch-specific code peek and poke inside this process somehow (except when the 
4005  * optimizations can take advantage of the full semantic info of coarse opcodes).
4006  * All the opcodes of the form opcode.s are 'normalized' to opcode.
4007  * MonoInst->opcode initially is the IL opcode or some simplification of that 
4008  * (OP_LOAD, OP_STORE). The arch-specific code may rearrange it to an arch-specific 
4009  * opcode with value bigger than OP_LAST.
4010  * At this point the IR can be handed over to an interpreter, a dumb code generator
4011  * or to the optimizing code generator that will translate it to SSA form.
4012  *
4013  * Profiling directed optimizations.
4014  * We may compile by default with few or no optimizations and instrument the code
4015  * or the user may indicate what methods to optimize the most either in a config file
4016  * or through repeated runs where the compiler applies offline the optimizations to 
4017  * each method and then decides if it was worth it.
4018  *
4019  */
4020
4021 #define CHECK_TYPE(ins) if (!(ins)->type) UNVERIFIED
4022 #define CHECK_STACK(num) if ((sp - stack_start) < (num)) UNVERIFIED
4023 #define CHECK_STACK_OVF(num) if (((sp - stack_start) + (num)) > header->max_stack) UNVERIFIED
4024 #define CHECK_ARG(num) if ((unsigned)(num) >= (unsigned)num_args) UNVERIFIED
4025 #define CHECK_LOCAL(num) if ((unsigned)(num) >= (unsigned)header->num_locals) UNVERIFIED
4026 #define CHECK_OPSIZE(size) if (ip + size > end) UNVERIFIED
4027 #define CHECK_UNVERIFIABLE(cfg) if (cfg->unverifiable) UNVERIFIED
4028 #define CHECK_TYPELOAD(klass) if (!(klass) || (klass)->exception_type) {cfg->exception_ptr = klass; goto load_error;}
4029
4030 /* offset from br.s -> br like opcodes */
4031 #define BIG_BRANCH_OFFSET 13
4032
4033 static inline gboolean
4034 ip_in_bb (MonoCompile *cfg, MonoBasicBlock *bb, const guint8* ip)
4035 {
4036         MonoBasicBlock *b = cfg->cil_offset_to_bb [ip - cfg->cil_start];
4037         
4038         return b == NULL || b == bb;
4039 }
4040
4041 static int
4042 get_basic_blocks (MonoCompile *cfg, MonoMethodHeader* header, guint real_offset, unsigned char *start, unsigned char *end, unsigned char **pos)
4043 {
4044         unsigned char *ip = start;
4045         unsigned char *target;
4046         int i;
4047         guint cli_addr;
4048         MonoBasicBlock *bblock;
4049         const MonoOpcode *opcode;
4050
4051         while (ip < end) {
4052                 cli_addr = ip - start;
4053                 i = mono_opcode_value ((const guint8 **)&ip, end);
4054                 if (i < 0)
4055                         UNVERIFIED;
4056                 opcode = &mono_opcodes [i];
4057                 switch (opcode->argument) {
4058                 case MonoInlineNone:
4059                         ip++; 
4060                         break;
4061                 case MonoInlineString:
4062                 case MonoInlineType:
4063                 case MonoInlineField:
4064                 case MonoInlineMethod:
4065                 case MonoInlineTok:
4066                 case MonoInlineSig:
4067                 case MonoShortInlineR:
4068                 case MonoInlineI:
4069                         ip += 5;
4070                         break;
4071                 case MonoInlineVar:
4072                         ip += 3;
4073                         break;
4074                 case MonoShortInlineVar:
4075                 case MonoShortInlineI:
4076                         ip += 2;
4077                         break;
4078                 case MonoShortInlineBrTarget:
4079                         target = start + cli_addr + 2 + (signed char)ip [1];
4080                         GET_BBLOCK (cfg, bblock, target);
4081                         ip += 2;
4082                         if (ip < end)
4083                                 GET_BBLOCK (cfg, bblock, ip);
4084                         break;
4085                 case MonoInlineBrTarget:
4086                         target = start + cli_addr + 5 + (gint32)read32 (ip + 1);
4087                         GET_BBLOCK (cfg, bblock, target);
4088                         ip += 5;
4089                         if (ip < end)
4090                                 GET_BBLOCK (cfg, bblock, ip);
4091                         break;
4092                 case MonoInlineSwitch: {
4093                         guint32 n = read32 (ip + 1);
4094                         guint32 j;
4095                         ip += 5;
4096                         cli_addr += 5 + 4 * n;
4097                         target = start + cli_addr;
4098                         GET_BBLOCK (cfg, bblock, target);
4099                         
4100                         for (j = 0; j < n; ++j) {
4101                                 target = start + cli_addr + (gint32)read32 (ip);
4102                                 GET_BBLOCK (cfg, bblock, target);
4103                                 ip += 4;
4104                         }
4105                         break;
4106                 }
4107                 case MonoInlineR:
4108                 case MonoInlineI8:
4109                         ip += 9;
4110                         break;
4111                 default:
4112                         g_assert_not_reached ();
4113                 }
4114
4115                 if (i == CEE_THROW) {
4116                         unsigned char *bb_start = ip - 1;
4117                         
4118                         /* Find the start of the bblock containing the throw */
4119                         bblock = NULL;
4120                         while ((bb_start >= start) && !bblock) {
4121                                 bblock = cfg->cil_offset_to_bb [(bb_start) - start];
4122                                 bb_start --;
4123                         }
4124                         if (bblock)
4125                                 bblock->out_of_line = 1;
4126                 }
4127         }
4128         return 0;
4129 unverified:
4130         *pos = ip;
4131         return 1;
4132 }
4133
4134 static MonoInst*
4135 emit_tree (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ins, const guint8* ip_next)
4136 {
4137         MonoInst *store, *temp, *load;
4138         
4139         if (ip_in_bb (cfg, bblock, ip_next) &&
4140                 (CODE_IS_STLOC (ip_next) || *ip_next == CEE_RET))
4141                         return ins;
4142         
4143         temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
4144         temp->flags |= MONO_INST_IS_TEMP;
4145         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
4146         /* FIXME: handle CEE_STIND_R4 */
4147         store->cil_code = ins->cil_code;
4148         MONO_ADD_INS (bblock, store);
4149         NEW_TEMPLOAD (cfg, load, temp->inst_c0);
4150         load->cil_code = ins->cil_code;
4151         return load;
4152 }
4153
4154 static inline MonoMethod *
4155 mini_get_method_allow_open (MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context)
4156 {
4157         MonoMethod *method;
4158
4159         if (m->wrapper_type != MONO_WRAPPER_NONE)
4160                 return mono_method_get_wrapper_data (m, token);
4161
4162         method = mono_get_method_full (m->klass->image, token, klass, context);
4163
4164         return method;
4165 }
4166
4167 static inline MonoMethod *
4168 mini_get_method (MonoCompile *cfg, MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context)
4169 {
4170         MonoMethod *method = mini_get_method_allow_open (m, token, klass, context);
4171
4172         if (method && cfg && !cfg->generic_sharing_context && mono_class_is_open_constructed_type (&method->klass->byval_arg))
4173                 return NULL;
4174
4175         return method;
4176 }
4177
4178 static inline MonoClass*
4179 mini_get_class (MonoMethod *method, guint32 token, MonoGenericContext *context)
4180 {
4181         MonoClass *klass;
4182
4183         if (method->wrapper_type != MONO_WRAPPER_NONE)
4184                 klass = mono_method_get_wrapper_data (method, token);
4185         else
4186                 klass = mono_class_get_full (method->klass->image, token, context);
4187         if (klass)
4188                 mono_class_init (klass);
4189         return klass;
4190 }
4191
4192 /*
4193  * Returns TRUE if the JIT should abort inlining because "callee"
4194  * is influenced by security attributes.
4195  */
4196 static
4197 gboolean check_linkdemand (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee, MonoBasicBlock *bblock, unsigned char *ip)
4198 {
4199         guint32 result;
4200         
4201         if ((cfg->method != caller) && mono_method_has_declsec (callee)) {
4202                 return TRUE;
4203         }
4204         
4205         result = mono_declsec_linkdemand (cfg->domain, caller, callee);
4206         if (result == MONO_JIT_SECURITY_OK)
4207                 return FALSE;
4208
4209         if (result == MONO_JIT_LINKDEMAND_ECMA) {
4210                 /* Generate code to throw a SecurityException before the actual call/link */
4211                 MonoSecurityManager *secman = mono_security_manager_get_methods ();
4212                 MonoInst *args [2];
4213
4214                 NEW_ICONST (cfg, args [0], 4);
4215                 NEW_METHODCONST (cfg, args [1], caller);
4216                 mono_emit_method_call_spilled (cfg, bblock, secman->linkdemandsecurityexception, mono_method_signature (secman->linkdemandsecurityexception), args, ip, NULL);
4217         } else if (cfg->exception_type == MONO_EXCEPTION_NONE) {
4218                  /* don't hide previous results */
4219                 cfg->exception_type = MONO_EXCEPTION_SECURITY_LINKDEMAND;
4220                 cfg->exception_data = result;
4221                 return TRUE;
4222         }
4223         
4224         return FALSE;
4225 }
4226
4227 static MonoMethod*
4228 method_access_exception (void)
4229 {
4230         static MonoMethod *method = NULL;
4231
4232         if (!method) {
4233                 MonoSecurityManager *secman = mono_security_manager_get_methods ();
4234                 method = mono_class_get_method_from_name (secman->securitymanager,
4235                                                           "MethodAccessException", 2);
4236         }
4237         g_assert (method);
4238         return method;
4239 }
4240
4241 static void
4242 emit_throw_method_access_exception (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee,
4243                                     MonoBasicBlock *bblock, unsigned char *ip)
4244 {
4245         MonoMethod *thrower = method_access_exception ();
4246         MonoInst *args [2];
4247
4248         NEW_METHODCONST (cfg, args [0], caller);
4249         NEW_METHODCONST (cfg, args [1], callee);
4250         mono_emit_method_call_spilled (cfg, bblock, thrower,
4251                 mono_method_signature (thrower), args, ip, NULL);
4252 }
4253
4254 static MonoMethod*
4255 verification_exception (void)
4256 {
4257         static MonoMethod *method = NULL;
4258
4259         if (!method) {
4260                 MonoSecurityManager *secman = mono_security_manager_get_methods ();
4261                 method = mono_class_get_method_from_name (secman->securitymanager,
4262                                                           "VerificationException", 0);
4263         }
4264         g_assert (method);
4265         return method;
4266 }
4267
4268 static void
4269 emit_throw_verification_exception (MonoCompile *cfg, MonoBasicBlock *bblock, unsigned char *ip)
4270 {
4271         MonoMethod *thrower = verification_exception ();
4272
4273         mono_emit_method_call_spilled (cfg, bblock, thrower,
4274                 mono_method_signature (thrower),
4275                 NULL, ip, NULL);
4276 }
4277
4278 static void
4279 ensure_method_is_allowed_to_call_method (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee,
4280                                          MonoBasicBlock *bblock, unsigned char *ip)
4281 {
4282         MonoSecurityCoreCLRLevel caller_level = mono_security_core_clr_method_level (caller, TRUE);
4283         MonoSecurityCoreCLRLevel callee_level = mono_security_core_clr_method_level (callee, TRUE);
4284         gboolean is_safe = TRUE;
4285
4286         if (!(caller_level >= callee_level ||
4287                         caller_level == MONO_SECURITY_CORE_CLR_SAFE_CRITICAL ||
4288                         callee_level == MONO_SECURITY_CORE_CLR_SAFE_CRITICAL)) {
4289                 is_safe = FALSE;
4290         }
4291
4292         if (!is_safe)
4293                 emit_throw_method_access_exception (cfg, caller, callee, bblock, ip);
4294 }
4295
4296 static gboolean
4297 method_is_safe (MonoMethod *method)
4298 {
4299         /*
4300         if (strcmp (method->name, "unsafeMethod") == 0)
4301                 return FALSE;
4302         */
4303         return TRUE;
4304 }
4305
4306 /*
4307  * Check that the IL instructions at ip are the array initialization
4308  * sequence and return the pointer to the data and the size.
4309  */
4310 static const char*
4311 initialize_array_data (MonoMethod *method, gboolean aot, unsigned char *ip, MonoInst *newarr, int *out_size)
4312 {
4313         /*
4314          * newarr[System.Int32]
4315          * dup
4316          * ldtoken field valuetype ...
4317          * call void class [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class [mscorlib]System.Array, valuetype [mscorlib]System.RuntimeFieldHandle)
4318          */
4319         if (ip [0] == CEE_DUP && ip [1] == CEE_LDTOKEN && ip [5] == 0x4 && ip [6] == CEE_CALL) {
4320                 MonoClass *klass = newarr->inst_newa_class;
4321                 guint32 field_token = read32 (ip + 2);
4322                 guint32 field_index = field_token & 0xffffff;
4323                 guint32 token = read32 (ip + 7);
4324                 guint32 rva;
4325                 const char *data_ptr;
4326                 int size = 0;
4327                 MonoMethod *cmethod;
4328                 MonoClass *dummy_class;
4329                 MonoClassField *field = mono_field_from_token (method->klass->image, field_token, &dummy_class, NULL);
4330                 int dummy_align;
4331
4332                 if (!field)
4333                         return NULL;
4334
4335                 if (newarr->inst_newa_len->opcode != OP_ICONST)
4336                         return NULL;
4337                 cmethod = mini_get_method (NULL, method, token, NULL, NULL);
4338                 if (!cmethod)
4339                         return NULL;
4340                 if (strcmp (cmethod->name, "InitializeArray") || strcmp (cmethod->klass->name, "RuntimeHelpers") || cmethod->klass->image != mono_defaults.corlib)
4341                         return NULL;
4342                 switch (mono_type_get_underlying_type (&klass->byval_arg)->type) {
4343                 case MONO_TYPE_BOOLEAN:
4344                 case MONO_TYPE_I1:
4345                 case MONO_TYPE_U1:
4346                         size = 1; break;
4347                 /* we need to swap on big endian, so punt. Should we handle R4 and R8 as well? */
4348 #if G_BYTE_ORDER == G_LITTLE_ENDIAN
4349                 case MONO_TYPE_CHAR:
4350                 case MONO_TYPE_I2:
4351                 case MONO_TYPE_U2:
4352                         size = 2; break;
4353                 case MONO_TYPE_I4:
4354                 case MONO_TYPE_U4:
4355                 case MONO_TYPE_R4:
4356                         size = 4; break;
4357                 case MONO_TYPE_R8:
4358 #ifdef ARM_FPU_FPA
4359                         return NULL; /* stupid ARM FP swapped format */
4360 #endif
4361                 case MONO_TYPE_I8:
4362                 case MONO_TYPE_U8:
4363                         size = 8; break;
4364 #endif
4365                 default:
4366                         return NULL;
4367                 }
4368                 size *= newarr->inst_newa_len->inst_c0;
4369                 if (size > mono_type_size (field->type, &dummy_align))
4370                     return NULL;
4371                 *out_size = size;
4372                 /*g_print ("optimized in %s: size: %d, numelems: %d\n", method->name, size, newarr->inst_newa_len->inst_c0);*/
4373                 field_index = read32 (ip + 2) & 0xffffff;
4374                 mono_metadata_field_info (method->klass->image, field_index - 1, NULL, &rva, NULL);
4375                 data_ptr = mono_image_rva_map (method->klass->image, rva);
4376                 /*g_print ("field: 0x%08x, rva: %d, rva_ptr: %p\n", read32 (ip + 2), rva, data_ptr);*/
4377                 /* for aot code we do the lookup on load */
4378                 if (aot && data_ptr)
4379                         return GUINT_TO_POINTER (rva);
4380                 return data_ptr;
4381         }
4382         return NULL;
4383 }
4384
4385 static void
4386 set_exception_type_from_invalid_il (MonoCompile *cfg, MonoMethod *method, unsigned char *ip)
4387 {
4388         char *method_fname = mono_method_full_name (method, TRUE);
4389         char *method_code;
4390
4391         if (mono_method_get_header (method)->code_size == 0)
4392                 method_code = g_strdup ("method body is empty.");
4393         else
4394                 method_code = mono_disasm_code_one (NULL, method, ip, NULL);
4395         cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
4396         cfg->exception_message = g_strdup_printf ("Invalid IL code in %s: %s\n", method_fname, method_code);
4397         g_free (method_fname);
4398         g_free (method_code);
4399 }
4400
4401 static MonoInst*
4402 get_runtime_generic_context (MonoCompile *cfg, MonoMethod *method, MonoInst *this, unsigned char *ip)
4403 {
4404         g_assert (!method->klass->valuetype);
4405
4406         if (method->flags & METHOD_ATTRIBUTE_STATIC) {
4407                 MonoInst *vtable_loc, *vtable_var;
4408
4409                 vtable_loc = mono_get_vtable_var (cfg);
4410                 NEW_TEMPLOAD (cfg, vtable_var, vtable_loc->inst_c0);
4411
4412                 return vtable_var;
4413         } else {
4414                 MonoInst *vtable;
4415
4416                 MONO_INST_NEW (cfg, vtable, CEE_LDIND_I);
4417                 vtable->cil_code = ip;
4418                 vtable->inst_left = this;
4419                 vtable->type = STACK_PTR;
4420
4421                 return vtable;
4422         }
4423 }
4424
4425 static gpointer
4426 create_rgctx_lazy_fetch_trampoline (guint32 offset)
4427 {
4428         static gboolean inited = FALSE;
4429         static int num_trampolines = 0;
4430
4431         gpointer tramp, ptr;
4432
4433         mono_jit_lock ();
4434         if (rgctx_lazy_fetch_trampoline_hash)
4435                 tramp = g_hash_table_lookup (rgctx_lazy_fetch_trampoline_hash, GUINT_TO_POINTER (offset));
4436         else
4437                 tramp = NULL;
4438         mono_jit_unlock ();
4439         if (tramp)
4440                 return tramp;
4441
4442         tramp = mono_arch_create_rgctx_lazy_fetch_trampoline (offset);
4443         ptr = mono_create_ftnptr (mono_get_root_domain (), tramp);
4444
4445         mono_jit_lock ();
4446         if (!rgctx_lazy_fetch_trampoline_hash)
4447                 rgctx_lazy_fetch_trampoline_hash = g_hash_table_new (NULL, NULL);
4448         g_hash_table_insert (rgctx_lazy_fetch_trampoline_hash, GUINT_TO_POINTER (offset), ptr);
4449         mono_jit_unlock ();
4450
4451         if (!inited) {
4452                 mono_counters_register ("RGCTX num lazy fetch trampolines",
4453                                 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &num_trampolines);
4454                 inited = TRUE;
4455         }
4456         num_trampolines++;
4457
4458         return ptr;
4459 }
4460
4461 /*
4462  * Generates rgc->other_infos [index].XXX if index is non-negative, or
4463  * rgc->extra_other_infos [-index + 1] if index is negative.  XXX is
4464  * specified by rgctx_type;
4465  */
4466 static MonoInst*
4467 get_runtime_generic_context_other_table_ptr (MonoCompile *cfg, MonoBasicBlock *bblock,
4468         MonoInst *rgc_ptr, int slot, const unsigned char *ip)
4469 {
4470         MonoMethodSignature *sig = helper_sig_rgctx_lazy_fetch_trampoline;
4471         guint8 *tramp = create_rgctx_lazy_fetch_trampoline (slot);
4472         int temp;
4473         MonoInst *field;
4474
4475         temp = mono_emit_native_call (cfg, bblock, tramp, sig, &rgc_ptr, ip, FALSE, FALSE);
4476
4477         NEW_TEMPLOAD (cfg, field, temp);
4478
4479         return field;
4480 }
4481
4482 static MonoInst*
4483 get_runtime_generic_context_other_ptr (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *bblock,
4484         MonoInst *rgc_ptr, guint32 token, int token_source, int rgctx_type, unsigned char *ip, int index)
4485 {
4486         MonoInst *args [6];
4487         int temp;
4488         MonoInst *result;
4489
4490         g_assert (method->wrapper_type == MONO_WRAPPER_NONE);
4491
4492         NEW_CLASSCONST (cfg, args [0], method->klass);
4493         args [1] = rgc_ptr;
4494         NEW_ICONST (cfg, args [2], token);
4495         NEW_ICONST (cfg, args [3], token_source);
4496         NEW_ICONST (cfg, args [4], rgctx_type);
4497         NEW_ICONST (cfg, args [5], index);
4498
4499         temp = mono_emit_jit_icall (cfg, bblock, mono_helper_get_rgctx_other_ptr, args, ip);
4500         NEW_TEMPLOAD (cfg, result, temp);
4501
4502         return result;
4503 }
4504
4505 static MonoInst*
4506 get_runtime_generic_context_ptr (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *bblock,
4507         MonoClass *klass, guint32 type_token, int token_source, MonoGenericContext *generic_context, MonoInst *rgctx,
4508         int rgctx_type, unsigned char *ip)
4509 {
4510         int arg_num = -1;
4511         int relation = mono_class_generic_class_relation (klass, rgctx_type, method->klass, generic_context, &arg_num);
4512
4513         switch (relation) {
4514         case MINI_GENERIC_CLASS_RELATION_OTHER_TABLE:
4515                 return get_runtime_generic_context_other_table_ptr (cfg, bblock, rgctx, arg_num, ip);
4516         case MINI_GENERIC_CLASS_RELATION_OTHER:
4517                 return get_runtime_generic_context_other_ptr (cfg, method, bblock, rgctx,
4518                         type_token, token_source, rgctx_type, ip, arg_num);
4519         default:
4520                 g_assert_not_reached ();
4521                 return NULL;
4522         }
4523 }
4524
4525 static MonoInst*
4526 get_runtime_generic_context_method (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *bblock,
4527         MonoMethod *cmethod, MonoGenericContext *generic_context, MonoInst *rgctx, int rgctx_type, const unsigned char *ip)
4528 {
4529         int arg_num = mono_class_lookup_or_register_other_info (method->klass, cmethod, rgctx_type, generic_context);
4530
4531         return get_runtime_generic_context_other_table_ptr (cfg, bblock, rgctx, arg_num, ip);
4532 }
4533
4534 static gboolean
4535 generic_class_is_reference_type (MonoCompile *cfg, MonoClass *klass)
4536 {
4537         MonoType *type;
4538
4539         if (cfg->generic_sharing_context)
4540                 type = mini_get_basic_type_from_generic (cfg->generic_sharing_context, &klass->byval_arg);
4541         else
4542                 type = &klass->byval_arg;
4543         return MONO_TYPE_IS_REFERENCE (type);
4544 }
4545
4546 static gboolean
4547 mini_assembly_can_skip_verification (MonoDomain *domain, MonoMethod *method)
4548 {
4549         MonoAssembly *assembly = method->klass->image->assembly;
4550         if (method->wrapper_type != MONO_WRAPPER_NONE)
4551                 return FALSE;
4552         if (assembly->in_gac || assembly->image == mono_defaults.corlib)
4553                 return FALSE;
4554         if (mono_security_get_mode () != MONO_SECURITY_MODE_NONE)
4555                 return FALSE;
4556         return mono_assembly_has_skip_verification (assembly);
4557 }
4558
4559 /*
4560  * mini_method_verify:
4561  * 
4562  * Verify the method using the new verfier.
4563  * 
4564  * Returns true if the method is invalid. 
4565  */
4566 static gboolean
4567 mini_method_verify (MonoCompile *cfg, MonoMethod *method)
4568 {
4569         GSList *tmp, *res;
4570         gboolean is_fulltrust;
4571         MonoLoaderError *error;
4572
4573         if (method->verification_success)
4574                 return FALSE;
4575
4576         is_fulltrust = mono_verifier_is_method_full_trust (method);
4577
4578         if (!mono_verifier_is_enabled_for_method (method))
4579                 return FALSE;
4580
4581         res = mono_method_verify_with_current_settings (method, cfg->skip_visibility);
4582
4583         if ((error = mono_loader_get_last_error ())) {
4584                 cfg->exception_type = error->exception_type;
4585                 if (res)
4586                         mono_free_verify_list (res);
4587                 return TRUE;
4588         }
4589
4590         if (res) { 
4591                 for (tmp = res; tmp; tmp = tmp->next) {
4592                         MonoVerifyInfoExtended *info = (MonoVerifyInfoExtended *)tmp->data;
4593                         if (info->info.status == MONO_VERIFY_ERROR) {
4594                                 cfg->exception_type = info->exception_type;
4595                                 cfg->exception_message = g_strdup (info->info.message);
4596                                 mono_free_verify_list (res);
4597                                 return TRUE;
4598                         }
4599                         if (info->info.status == MONO_VERIFY_NOT_VERIFIABLE && !is_fulltrust) {
4600                                 cfg->exception_type = info->exception_type;
4601                                 cfg->exception_message = g_strdup (info->info.message);
4602                                 mono_free_verify_list (res);
4603                                 return TRUE;
4604                         }
4605                 }
4606                 mono_free_verify_list (res);
4607         }
4608         method->verification_success = 1;
4609         return FALSE;
4610 }
4611
4612 /*
4613  * mono_method_to_ir: translates IL into basic blocks containing trees
4614  */
4615 static int
4616 mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
4617                    int locals_offset, MonoInst *return_var, GList *dont_inline, MonoInst **inline_args, 
4618                    guint inline_offset, gboolean is_virtual_call)
4619 {
4620         MonoInst *zero_int32, *zero_int64, *zero_ptr, *zero_obj, *zero_r8;
4621         MonoInst *ins, **sp, **stack_start;
4622         MonoBasicBlock *bblock, *tblock = NULL, *init_localsbb = NULL;
4623         MonoMethod *cmethod, *method_definition;
4624         MonoInst **arg_array;
4625         MonoMethodHeader *header;
4626         MonoImage *image;
4627         guint32 token, ins_flag;
4628         MonoClass *klass;
4629         MonoClass *constrained_call = NULL;
4630         unsigned char *ip, *end, *target, *err_pos;
4631         static double r8_0 = 0.0;
4632         MonoMethodSignature *sig;
4633         MonoGenericContext *generic_context = NULL;
4634         MonoGenericContainer *generic_container = NULL;
4635         MonoType **param_types;
4636         GList *bb_recheck = NULL, *tmp;
4637         int i, n, start_new_bblock, ialign;
4638         int num_calls = 0, inline_costs = 0;
4639         int breakpoint_id = 0;
4640         guint32 align;
4641         guint real_offset, num_args;
4642         MonoBoolean security, pinvoke;
4643         MonoSecurityManager* secman = NULL;
4644         MonoDeclSecurityActions actions;
4645         GSList *class_inits = NULL;
4646         gboolean dont_verify, dont_verify_stloc, readonly = FALSE;
4647
4648         /* serialization and xdomain stuff may need access to private fields and methods */
4649         dont_verify = method->klass->image->assembly->corlib_internal? TRUE: FALSE;
4650         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE;
4651         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH;
4652         dont_verify |= method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE; /* bug #77896 */
4653         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP;
4654         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP_INVOKE;
4655
4656         /* turn off visibility checks for smcs */
4657         dont_verify |= mono_security_get_mode () == MONO_SECURITY_MODE_SMCS_HACK;
4658
4659         /* still some type unsafety issues in marshal wrappers... (unknown is PtrToStructure) */
4660         dont_verify_stloc = method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE;
4661         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_UNKNOWN;
4662         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED;
4663
4664         image = method->klass->image;
4665         header = mono_method_get_header (method);
4666         generic_container = method->generic_container;
4667         sig = mono_method_signature (method);
4668         num_args = sig->hasthis + sig->param_count;
4669         ip = (unsigned char*)header->code;
4670         cfg->cil_start = ip;
4671         end = ip + header->code_size;
4672         mono_jit_stats.cil_code_size += header->code_size;
4673
4674         method_definition = method;
4675         while (method_definition->is_inflated) {
4676                 MonoMethodInflated *imethod = (MonoMethodInflated *) method_definition;
4677                 method_definition = imethod->declaring;
4678         }
4679
4680         /* SkipVerification is not allowed if core-clr is enabled */
4681         if (!dont_verify && mini_assembly_can_skip_verification (cfg->domain, method)) {
4682                 dont_verify = TRUE;
4683                 dont_verify_stloc = TRUE;
4684         }
4685
4686         if (!dont_verify && mini_method_verify (cfg, method_definition))
4687                 goto exception_exit;
4688
4689         if (sig->is_inflated)
4690                 generic_context = mono_method_get_context (method);
4691         else if (generic_container)
4692                 generic_context = &generic_container->context;
4693
4694         if (!cfg->generic_sharing_context)
4695                 g_assert (!sig->has_type_parameters);
4696
4697         if (cfg->method == method)
4698                 real_offset = 0;
4699         else
4700                 real_offset = inline_offset;
4701
4702         cfg->cil_offset_to_bb = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoBasicBlock*) * header->code_size);
4703         cfg->cil_offset_to_bb_len = header->code_size;
4704
4705         if (cfg->verbose_level > 2)
4706                 g_print ("method to IR %s\n", mono_method_full_name (method, TRUE));
4707
4708         dont_inline = g_list_prepend (dont_inline, method);
4709         if (cfg->method == method) {
4710
4711                 if (cfg->prof_options & MONO_PROFILE_INS_COVERAGE)
4712                         cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, header->code_size);
4713
4714                 /* ENTRY BLOCK */
4715                 NEW_BBLOCK (cfg, start_bblock);
4716                 cfg->bb_entry = start_bblock;
4717                 start_bblock->cil_code = NULL;
4718                 start_bblock->cil_length = 0;
4719                 start_bblock->block_num = cfg->num_bblocks++;
4720
4721                 /* EXIT BLOCK */
4722                 NEW_BBLOCK (cfg, end_bblock);
4723                 cfg->bb_exit = end_bblock;
4724                 end_bblock->cil_code = NULL;
4725                 end_bblock->cil_length = 0;
4726                 end_bblock->block_num = cfg->num_bblocks++;
4727                 g_assert (cfg->num_bblocks == 2);
4728
4729                 arg_array = alloca (sizeof (MonoInst *) * num_args);
4730                 for (i = num_args - 1; i >= 0; i--)
4731                         arg_array [i] = cfg->varinfo [i];
4732
4733                 if (header->num_clauses) {
4734                         cfg->spvars = g_hash_table_new (NULL, NULL);
4735                         cfg->exvars = g_hash_table_new (NULL, NULL);
4736                 }
4737                 /* handle exception clauses */
4738                 for (i = 0; i < header->num_clauses; ++i) {
4739                         MonoBasicBlock *try_bb;
4740                         MonoExceptionClause *clause = &header->clauses [i];
4741
4742                         GET_BBLOCK (cfg, try_bb, ip + clause->try_offset);
4743                         try_bb->real_offset = clause->try_offset;
4744                         GET_BBLOCK (cfg, tblock, ip + clause->handler_offset);
4745                         tblock->real_offset = clause->handler_offset;
4746                         tblock->flags |= BB_EXCEPTION_HANDLER;
4747
4748                         link_bblock (cfg, try_bb, tblock);
4749
4750                         if (*(ip + clause->handler_offset) == CEE_POP)
4751                                 tblock->flags |= BB_EXCEPTION_DEAD_OBJ;
4752
4753                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY ||
4754                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER ||
4755                             clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) {
4756                                 MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
4757                                 MONO_ADD_INS (tblock, ins);
4758
4759                                 /* todo: is a fault block unsafe to optimize? */
4760                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
4761                                         tblock->flags |= BB_EXCEPTION_UNSAFE;
4762                         }
4763
4764
4765                         /*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);
4766                           while (p < end) {
4767                           g_print ("%s", mono_disasm_code_one (NULL, method, p, &p));
4768                           }*/
4769                         /* catch and filter blocks get the exception object on the stack */
4770                         if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE ||
4771                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
4772                                 MonoInst *load, *dummy_use;
4773
4774                                 /* mostly like handle_stack_args (), but just sets the input args */
4775                                 /* g_print ("handling clause at IL_%04x\n", clause->handler_offset); */
4776                                 tblock->in_scount = 1;
4777                                 tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
4778                                 tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
4779
4780                                 /* 
4781                                  * Add a dummy use for the exvar so its liveness info will be
4782                                  * correct.
4783                                  */
4784                                 NEW_TEMPLOAD (cfg, load, tblock->in_stack [0]->inst_c0);
4785                                 NEW_DUMMY_USE (cfg, dummy_use, load);
4786                                 MONO_ADD_INS (tblock, dummy_use);
4787                                 
4788                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
4789                                         GET_BBLOCK (cfg, tblock, ip + clause->data.filter_offset);
4790                                         tblock->real_offset = clause->data.filter_offset;
4791                                         tblock->in_scount = 1;
4792                                         tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
4793                                         /* The filter block shares the exvar with the handler block */
4794                                         tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
4795                                         MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
4796                                         MONO_ADD_INS (tblock, ins);
4797                                 }
4798                         }
4799
4800                         if (clause->flags != MONO_EXCEPTION_CLAUSE_FILTER &&
4801                                         clause->data.catch_class &&
4802                                         cfg->generic_sharing_context &&
4803                                         mono_class_check_context_used (clause->data.catch_class)) {
4804                                 /*
4805                                  * In shared generic code with catch
4806                                  * clauses containing type variables
4807                                  * the exception handling code has to
4808                                  * be able to get to the rgctx.
4809                                  * Therefore we have to make sure that
4810                                  * the rgctx argument (for static
4811                                  * methods) or the "this" argument
4812                                  * (for non-static methods) are live.
4813                                  */
4814                                 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
4815                                         mono_get_vtable_var (cfg);
4816                                 } else {
4817                                         MonoInst *this, *dummy_use;
4818                                         MonoType *this_type;
4819
4820                                         if (method->klass->valuetype)
4821                                                 this_type = &method->klass->this_arg;
4822                                         else
4823                                                 this_type = &method->klass->byval_arg;
4824
4825                                         if (arg_array [0]->opcode == OP_ICONST) {
4826                                                 this = arg_array [0];
4827                                         } else {
4828                                                 this = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));
4829                                                 this->ssa_op = MONO_SSA_LOAD;
4830                                                 this->inst_i0 = arg_array [0];
4831                                                 this->opcode = mini_type_to_ldind ((cfg), this->inst_i0->inst_vtype);
4832                                                 type_to_eval_stack_type ((cfg), this_type, this);
4833                                                 this->klass = this->inst_i0->klass;
4834                                         }
4835
4836                                         NEW_DUMMY_USE (cfg, dummy_use, this);
4837                                         MONO_ADD_INS (tblock, dummy_use);
4838                                 }
4839                         }
4840                 }
4841         } else {
4842                 arg_array = alloca (sizeof (MonoInst *) * num_args);
4843                 mono_save_args (cfg, start_bblock, sig, inline_args, arg_array);
4844         }
4845
4846         /* FIRST CODE BLOCK */
4847         NEW_BBLOCK (cfg, bblock);
4848         bblock->cil_code = ip;
4849
4850         ADD_BBLOCK (cfg, bblock);
4851
4852         if (cfg->method == method) {
4853                 breakpoint_id = mono_debugger_method_has_breakpoint (method);
4854                 if (breakpoint_id && (mono_debug_format != MONO_DEBUG_FORMAT_DEBUGGER)) {
4855                         MONO_INST_NEW (cfg, ins, OP_BREAK);
4856                         MONO_ADD_INS (bblock, ins);
4857                 }
4858         }
4859
4860         if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS)
4861                 secman = mono_security_manager_get_methods ();
4862
4863         security = (secman && mono_method_has_declsec (method));
4864         /* at this point having security doesn't mean we have any code to generate */
4865         if (security && (cfg->method == method)) {
4866                 /* Only Demand, NonCasDemand and DemandChoice requires code generation.
4867                  * And we do not want to enter the next section (with allocation) if we
4868                  * have nothing to generate */
4869                 security = mono_declsec_get_demands (method, &actions);
4870         }
4871
4872         /* we must Demand SecurityPermission.Unmanaged before P/Invoking */
4873         pinvoke = (secman && (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE));
4874         if (pinvoke) {
4875                 MonoMethod *wrapped = mono_marshal_method_from_wrapper (method);
4876                 if (wrapped && (wrapped->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4877                         MonoCustomAttrInfo* custom = mono_custom_attrs_from_method (wrapped);
4878
4879                         /* unless the method or it's class has the [SuppressUnmanagedCodeSecurity] attribute */
4880                         if (custom && mono_custom_attrs_has_attr (custom, secman->suppressunmanagedcodesecurity)) {
4881                                 pinvoke = FALSE;
4882                         }
4883                         if (custom)
4884                                 mono_custom_attrs_free (custom);
4885
4886                         if (pinvoke) {
4887                                 custom = mono_custom_attrs_from_class (wrapped->klass);
4888                                 if (custom && mono_custom_attrs_has_attr (custom, secman->suppressunmanagedcodesecurity)) {
4889                                         pinvoke = FALSE;
4890                                 }
4891                                 if (custom)
4892                                         mono_custom_attrs_free (custom);
4893                         }
4894                 } else {
4895                         /* not a P/Invoke after all */
4896                         pinvoke = FALSE;
4897                 }
4898         }
4899         
4900         if ((header->init_locals || (cfg->method == method && (cfg->opt & MONO_OPT_SHARED))) || cfg->compile_aot || security || pinvoke) {
4901                 /* we use a separate basic block for the initialization code */
4902                 NEW_BBLOCK (cfg, init_localsbb);
4903                 cfg->bb_init = init_localsbb;
4904                 init_localsbb->real_offset = real_offset;
4905                 start_bblock->next_bb = init_localsbb;
4906                 init_localsbb->next_bb = bblock;
4907                 link_bblock (cfg, start_bblock, init_localsbb);
4908                 link_bblock (cfg, init_localsbb, bblock);
4909                 init_localsbb->block_num = cfg->num_bblocks++;
4910         } else {
4911                 start_bblock->next_bb = bblock;
4912                 link_bblock (cfg, start_bblock, bblock);
4913         }
4914
4915         /* at this point we know, if security is TRUE, that some code needs to be generated */
4916         if (security && (cfg->method == method)) {
4917                 MonoInst *args [2];
4918
4919                 mono_jit_stats.cas_demand_generation++;
4920
4921                 if (actions.demand.blob) {
4922                         /* Add code for SecurityAction.Demand */
4923                         NEW_DECLSECCONST (cfg, args[0], image, actions.demand);
4924                         NEW_ICONST (cfg, args [1], actions.demand.size);
4925                         /* Calls static void SecurityManager.InternalDemand (byte* permissions, int size); */
4926                         mono_emit_method_call_spilled (cfg, init_localsbb, secman->demand, mono_method_signature (secman->demand), args, ip, NULL);
4927                 }
4928                 if (actions.noncasdemand.blob) {
4929                         /* CLR 1.x uses a .noncasdemand (but 2.x doesn't) */
4930                         /* For Mono we re-route non-CAS Demand to Demand (as the managed code must deal with it anyway) */
4931                         NEW_DECLSECCONST (cfg, args[0], image, actions.noncasdemand);
4932                         NEW_ICONST (cfg, args [1], actions.noncasdemand.size);
4933                         /* Calls static void SecurityManager.InternalDemand (byte* permissions, int size); */
4934                         mono_emit_method_call_spilled (cfg, init_localsbb, secman->demand, mono_method_signature (secman->demand), args, ip, NULL);
4935                 }
4936                 if (actions.demandchoice.blob) {
4937                         /* New in 2.0, Demand must succeed for one of the permissions (i.e. not all) */
4938                         NEW_DECLSECCONST (cfg, args[0], image, actions.demandchoice);
4939                         NEW_ICONST (cfg, args [1], actions.demandchoice.size);
4940                         /* Calls static void SecurityManager.InternalDemandChoice (byte* permissions, int size); */
4941                         mono_emit_method_call_spilled (cfg, init_localsbb, secman->demandchoice, mono_method_signature (secman->demandchoice), args, ip, NULL);
4942                 }
4943         }
4944
4945         /* we must Demand SecurityPermission.Unmanaged before p/invoking */
4946         if (pinvoke) {
4947                 mono_emit_method_call_spilled (cfg, init_localsbb, secman->demandunmanaged, mono_method_signature (secman->demandunmanaged), NULL, ip, NULL);
4948         }
4949
4950         if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
4951                 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
4952                         MonoMethod *wrapped = mono_marshal_method_from_wrapper (method);
4953                         if (wrapped && (wrapped->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4954                                 if (!(method->klass && method->klass->image &&
4955                                                 mono_security_core_clr_is_platform_image (method->klass->image))) {
4956                                         emit_throw_method_access_exception (cfg, method, wrapped, bblock, ip);
4957                                 }
4958                         }
4959                 }
4960                 if (!method_is_safe (method))
4961                         emit_throw_verification_exception (cfg, bblock, ip);
4962         }
4963
4964         if (header->code_size == 0)
4965                 UNVERIFIED;
4966
4967         if (get_basic_blocks (cfg, header, real_offset, ip, end, &err_pos)) {
4968                 ip = err_pos;
4969                 UNVERIFIED;
4970         }
4971
4972         if (cfg->method == method)
4973                 mono_debug_init_method (cfg, bblock, breakpoint_id);
4974
4975         param_types = mono_mempool_alloc (cfg->mempool, sizeof (MonoType*) * num_args);
4976         if (sig->hasthis)
4977                 param_types [0] = method->klass->valuetype?&method->klass->this_arg:&method->klass->byval_arg;
4978         for (n = 0; n < sig->param_count; ++n)
4979                 param_types [n + sig->hasthis] = sig->params [n];
4980         for (n = 0; n < header->num_locals; ++n) {
4981                 if (header->locals [n]->type == MONO_TYPE_VOID && !header->locals [n]->byref)
4982                         UNVERIFIED;
4983         }
4984         class_inits = NULL;
4985
4986         /* do this somewhere outside - not here */
4987         NEW_ICONST (cfg, zero_int32, 0);
4988         NEW_ICONST (cfg, zero_int64, 0);
4989         zero_int64->type = STACK_I8;
4990         NEW_PCONST (cfg, zero_ptr, 0);
4991         NEW_PCONST (cfg, zero_obj, 0);
4992         zero_obj->type = STACK_OBJ;
4993
4994         MONO_INST_NEW (cfg, zero_r8, OP_R8CONST);
4995         zero_r8->type = STACK_R8;
4996         zero_r8->inst_p0 = &r8_0;
4997
4998         /* add a check for this != NULL to inlined methods */
4999         if (is_virtual_call) {
5000                 MONO_INST_NEW (cfg, ins, OP_CHECK_THIS);
5001                 NEW_ARGLOAD (cfg, ins->inst_left, 0);
5002                 ins->cil_code = ip;
5003                 MONO_ADD_INS (bblock, ins);
5004         }
5005
5006         /* we use a spare stack slot in SWITCH and NEWOBJ and others */
5007         stack_start = sp = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (header->max_stack + 1));
5008
5009         ins_flag = 0;
5010         start_new_bblock = 0;
5011         while (ip < end) {
5012
5013                 if (cfg->method == method)
5014                         real_offset = ip - header->code;
5015                 else
5016                         real_offset = inline_offset;
5017                 cfg->ip = ip;
5018
5019                 if (start_new_bblock) {
5020                         bblock->cil_length = ip - bblock->cil_code;
5021                         if (start_new_bblock == 2) {
5022                                 g_assert (ip == tblock->cil_code);
5023                         } else {
5024                                 GET_BBLOCK (cfg, tblock, ip);
5025                         }
5026                         bblock->next_bb = tblock;
5027                         bblock = tblock;
5028                         start_new_bblock = 0;
5029                         for (i = 0; i < bblock->in_scount; ++i) {
5030                                 if (cfg->verbose_level > 3)
5031                                         g_print ("loading %d from temp %d\n", i, (int)bblock->in_stack [i]->inst_c0);                                           
5032                                 NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
5033                                 *sp++ = ins;
5034                         }
5035                         g_slist_free (class_inits);
5036                         class_inits = NULL;
5037                 } else {
5038                         if ((tblock = cfg->cil_offset_to_bb [ip - cfg->cil_start]) && (tblock != bblock)) {
5039                                 link_bblock (cfg, bblock, tblock);
5040                                 if (sp != stack_start) {
5041                                         handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5042                                         sp = stack_start;
5043                                         CHECK_UNVERIFIABLE (cfg);
5044                                 }
5045                                 bblock->next_bb = tblock;
5046                                 bblock = tblock;
5047                                 for (i = 0; i < bblock->in_scount; ++i) {
5048                                         if (cfg->verbose_level > 3)
5049                                                 g_print ("loading %d from temp %d\n", i, (int)bblock->in_stack [i]->inst_c0);                                           
5050                                         NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
5051                                         *sp++ = ins;
5052                                 }
5053                                 g_slist_free (class_inits);
5054                                 class_inits = NULL;
5055                         }
5056                 }
5057
5058                 bblock->real_offset = real_offset;
5059
5060                 if ((cfg->method == method) && cfg->coverage_info) {
5061                         MonoInst *store, *one;
5062                         guint32 cil_offset = ip - header->code;
5063                         cfg->coverage_info->data [cil_offset].cil_code = ip;
5064
5065                         /* TODO: Use an increment here */
5066                         NEW_ICONST (cfg, one, 1);
5067                         one->cil_code = ip;
5068
5069                         NEW_PCONST (cfg, ins, &(cfg->coverage_info->data [cil_offset].count));
5070                         ins->cil_code = ip;
5071
5072                         MONO_INST_NEW (cfg, store, CEE_STIND_I);
5073                         store->cil_code = ip;
5074                         store->inst_left = ins;
5075                         store->inst_right = one;
5076
5077                         MONO_ADD_INS (bblock, store);
5078                 }
5079
5080                 if (cfg->verbose_level > 3)
5081                         g_print ("converting (in B%d: stack: %d) %s", bblock->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
5082
5083                 switch (*ip) {
5084                 case CEE_NOP:
5085                         MONO_INST_NEW (cfg, ins, OP_NOP);
5086                         ins->cil_code = ip++;
5087                         MONO_ADD_INS (bblock, ins);
5088                         break;
5089                 case CEE_BREAK:
5090                         MONO_INST_NEW (cfg, ins, OP_BREAK);
5091                         ins->cil_code = ip++;
5092                         MONO_ADD_INS (bblock, ins);
5093                         break;
5094                 case CEE_LDARG_0:
5095                 case CEE_LDARG_1:
5096                 case CEE_LDARG_2:
5097                 case CEE_LDARG_3:
5098                         CHECK_STACK_OVF (1);
5099                         n = (*ip)-CEE_LDARG_0;
5100                         CHECK_ARG (n);
5101                         NEW_ARGLOAD (cfg, ins, n);
5102                         LDARG_SOFT_FLOAT (cfg, ins, n, ip);
5103                         ins->cil_code = ip++;
5104                         *sp++ = ins;
5105                         break;
5106                 case CEE_LDLOC_0:
5107                 case CEE_LDLOC_1:
5108                 case CEE_LDLOC_2:
5109                 case CEE_LDLOC_3:
5110                         CHECK_STACK_OVF (1);
5111                         n = (*ip)-CEE_LDLOC_0;
5112                         CHECK_LOCAL (n);
5113                         NEW_LOCLOAD (cfg, ins, n);
5114                         LDLOC_SOFT_FLOAT (cfg, ins, n, ip);
5115                         ins->cil_code = ip++;
5116                         *sp++ = ins;
5117                         break;
5118                 case CEE_STLOC_0:
5119                 case CEE_STLOC_1:
5120                 case CEE_STLOC_2:
5121                 case CEE_STLOC_3:
5122                         CHECK_STACK (1);
5123                         n = (*ip)-CEE_STLOC_0;
5124                         CHECK_LOCAL (n);
5125                         --sp;
5126                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5127                         NEW_LOCSTORE (cfg, ins, n, *sp);
5128                         ins->cil_code = ip;
5129                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
5130                                 UNVERIFIED;
5131                         STLOC_SOFT_FLOAT (cfg, ins, n, ip);
5132                         if (ins->opcode == CEE_STOBJ) {
5133                                 NEW_LOCLOADA (cfg, ins, n);
5134                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
5135                         } else
5136                                 MONO_ADD_INS (bblock, ins);
5137                         ++ip;
5138                         inline_costs += 1;
5139                         break;
5140                 case CEE_LDARG_S:
5141                         CHECK_OPSIZE (2);
5142                         CHECK_STACK_OVF (1);
5143                         CHECK_ARG (ip [1]);
5144                         NEW_ARGLOAD (cfg, ins, ip [1]);
5145                         LDARG_SOFT_FLOAT (cfg, ins, ip [1], ip);
5146                         ins->cil_code = ip;
5147                         *sp++ = ins;
5148                         ip += 2;
5149                         break;
5150                 case CEE_LDARGA_S:
5151                         CHECK_OPSIZE (2);
5152                         CHECK_STACK_OVF (1);
5153                         CHECK_ARG (ip [1]);
5154                         NEW_ARGLOADA (cfg, ins, ip [1]);
5155                         ins->cil_code = ip;
5156                         *sp++ = ins;
5157                         ip += 2;
5158                         break;
5159                 case CEE_STARG_S:
5160                         CHECK_OPSIZE (2);
5161                         CHECK_STACK (1);
5162                         --sp;
5163                         CHECK_ARG (ip [1]);
5164                         NEW_ARGSTORE (cfg, ins, ip [1], *sp);
5165                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5166                         ins->cil_code = ip;
5167                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [ip [1]], *sp))
5168                                 UNVERIFIED;
5169                         STARG_SOFT_FLOAT (cfg, ins, ip [1], ip);
5170                         if (ins->opcode == CEE_STOBJ) {
5171                                 NEW_ARGLOADA (cfg, ins, ip [1]);
5172                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
5173                         } else
5174                                 MONO_ADD_INS (bblock, ins);
5175                         ip += 2;
5176                         break;
5177                 case CEE_LDLOC_S:
5178                         CHECK_OPSIZE (2);
5179                         CHECK_STACK_OVF (1);
5180                         CHECK_LOCAL (ip [1]);
5181                         NEW_LOCLOAD (cfg, ins, ip [1]);
5182                         LDLOC_SOFT_FLOAT (cfg, ins, ip [1], ip);
5183                         ins->cil_code = ip;
5184                         *sp++ = ins;
5185                         ip += 2;
5186                         break;
5187                 case CEE_LDLOCA_S:
5188                         CHECK_OPSIZE (2);
5189                         CHECK_STACK_OVF (1);
5190                         CHECK_LOCAL (ip [1]);
5191                         NEW_LOCLOADA (cfg, ins, ip [1]);
5192                         ins->cil_code = ip;
5193                         *sp++ = ins;
5194                         ip += 2;
5195                         break;
5196                 case CEE_STLOC_S:
5197                         CHECK_OPSIZE (2);
5198                         CHECK_STACK (1);
5199                         --sp;
5200                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5201                         CHECK_LOCAL (ip [1]);
5202                         NEW_LOCSTORE (cfg, ins, ip [1], *sp);
5203                         ins->cil_code = ip;
5204                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [ip [1]], *sp))
5205                                 UNVERIFIED;
5206                         STLOC_SOFT_FLOAT (cfg, ins, ip [1], ip);
5207                         if (ins->opcode == CEE_STOBJ) {
5208                                 NEW_LOCLOADA (cfg, ins, ip [1]);
5209                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
5210                         } else
5211                                 MONO_ADD_INS (bblock, ins);
5212                         ip += 2;
5213                         inline_costs += 1;
5214                         break;
5215                 case CEE_LDNULL:
5216                         CHECK_STACK_OVF (1);
5217                         NEW_PCONST (cfg, ins, NULL);
5218                         ins->cil_code = ip;
5219                         ins->type = STACK_OBJ;
5220                         ++ip;
5221                         *sp++ = ins;
5222                         break;
5223                 case CEE_LDC_I4_M1:
5224                         CHECK_STACK_OVF (1);
5225                         NEW_ICONST (cfg, ins, -1);
5226                         ins->cil_code = ip;
5227                         ++ip;
5228                         *sp++ = ins;
5229                         break;
5230                 case CEE_LDC_I4_0:
5231                 case CEE_LDC_I4_1:
5232                 case CEE_LDC_I4_2:
5233                 case CEE_LDC_I4_3:
5234                 case CEE_LDC_I4_4:
5235                 case CEE_LDC_I4_5:
5236                 case CEE_LDC_I4_6:
5237                 case CEE_LDC_I4_7:
5238                 case CEE_LDC_I4_8:
5239                         CHECK_STACK_OVF (1);
5240                         NEW_ICONST (cfg, ins, (*ip) - CEE_LDC_I4_0);
5241                         ins->cil_code = ip;
5242                         ++ip;
5243                         *sp++ = ins;
5244                         break;
5245                 case CEE_LDC_I4_S:
5246                         CHECK_OPSIZE (2);
5247                         CHECK_STACK_OVF (1);
5248                         ++ip;
5249                         NEW_ICONST (cfg, ins, *((signed char*)ip));
5250                         ins->cil_code = ip;
5251                         ++ip;
5252                         *sp++ = ins;
5253                         break;
5254                 case CEE_LDC_I4:
5255                         CHECK_OPSIZE (5);
5256                         CHECK_STACK_OVF (1);
5257                         NEW_ICONST (cfg, ins, (gint32)read32 (ip + 1));
5258                         ins->cil_code = ip;
5259                         ip += 5;
5260                         *sp++ = ins;
5261                         break;
5262                 case CEE_LDC_I8:
5263                         CHECK_OPSIZE (9);
5264                         CHECK_STACK_OVF (1);
5265                         MONO_INST_NEW (cfg, ins, OP_I8CONST);
5266                         ins->cil_code = ip;
5267                         ins->type = STACK_I8;
5268                         ++ip;
5269                         ins->inst_l = (gint64)read64 (ip);
5270                         ip += 8;
5271                         *sp++ = ins;
5272                         break;
5273                 case CEE_LDC_R4: {
5274                         float *f;
5275                         /* we should really allocate this only late in the compilation process */
5276                         mono_domain_lock (cfg->domain);
5277                         f = mono_mempool_alloc (cfg->domain->mp, sizeof (float));
5278                         mono_domain_unlock (cfg->domain);
5279                         CHECK_OPSIZE (5);
5280                         CHECK_STACK_OVF (1);
5281                         MONO_INST_NEW (cfg, ins, OP_R4CONST);
5282                         ins->type = STACK_R8;
5283                         ++ip;
5284                         readr4 (ip, f);
5285                         ins->inst_p0 = f;
5286
5287                         ip += 4;
5288                         *sp++ = ins;                    
5289                         break;
5290                 }
5291                 case CEE_LDC_R8: {
5292                         double *d;
5293                         mono_domain_lock (cfg->domain);
5294                         d = mono_mempool_alloc (cfg->domain->mp, sizeof (double));
5295                         mono_domain_unlock (cfg->domain);
5296                         CHECK_OPSIZE (9);
5297                         CHECK_STACK_OVF (1);
5298                         MONO_INST_NEW (cfg, ins, OP_R8CONST);
5299                         ins->type = STACK_R8;
5300                         ++ip;
5301                         readr8 (ip, d);
5302                         ins->inst_p0 = d;
5303
5304                         ip += 8;
5305                         *sp++ = ins;                    
5306                         break;
5307                 }
5308                 case CEE_DUP: {
5309                         MonoInst *temp, *store;
5310                         CHECK_STACK (1);
5311                         CHECK_STACK_OVF (1);
5312                         sp--;
5313                         ins = *sp;
5314                 
5315                         /* 
5316                          * small optimization: if the loaded value was from a local already,
5317                          * just load it twice.
5318                          */
5319                         if (ins->ssa_op == MONO_SSA_LOAD && 
5320                             (ins->inst_i0->opcode == OP_LOCAL || ins->inst_i0->opcode == OP_ARG)) {
5321                                 sp++;
5322                                 MONO_INST_NEW (cfg, temp, 0);
5323                                 *temp = *ins;
5324                                 temp->cil_code = ip;
5325                                 *sp++ = temp;
5326                         } else {
5327                                 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
5328                                 temp->flags |= MONO_INST_IS_TEMP;
5329                                 temp->cil_code = ip;
5330                                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
5331                                 store->cil_code = ip;
5332                                 /* FIXME: handle CEE_STIND_R4 */
5333                                 if (store->opcode == CEE_STOBJ) {
5334                                         NEW_TEMPLOADA (cfg, store, temp->inst_c0);
5335                                         handle_stobj (cfg, bblock, store, sp [0], sp [0]->cil_code, store->klass, TRUE, FALSE, FALSE);
5336                                 } else {
5337                                         MONO_ADD_INS (bblock, store);
5338                                 }
5339                                 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
5340                                 *sp++ = ins;
5341                                 ins->cil_code = ip;
5342                                 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
5343                                 *sp++ = ins;
5344                                 ins->cil_code = ip;
5345                         }
5346                         ++ip;
5347                         inline_costs += 2;
5348                         break;
5349                 }
5350                 case CEE_POP:
5351                         CHECK_STACK (1);
5352                         MONO_INST_NEW (cfg, ins, CEE_POP);
5353                         MONO_ADD_INS (bblock, ins);
5354                         ins->cil_code = ip++;
5355                         --sp;
5356                         ins->inst_i0 = *sp;
5357                         break;
5358                 case CEE_JMP:
5359                         CHECK_OPSIZE (5);
5360                         if (stack_start != sp)
5361                                 UNVERIFIED;
5362                         MONO_INST_NEW (cfg, ins, OP_JMP);
5363                         token = read32 (ip + 1);
5364                         /* FIXME: check the signature matches */
5365                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
5366
5367                         if (!cmethod)
5368                                 goto load_error;
5369
5370                         if (cfg->generic_sharing_context && mono_method_check_context_used (cmethod))
5371                                 GENERIC_SHARING_FAILURE (CEE_JMP);
5372
5373                         if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
5374                                 if (check_linkdemand (cfg, method, cmethod, bblock, ip))
5375                                         INLINE_FAILURE;
5376                                 CHECK_CFG_EXCEPTION;
5377                         }
5378
5379                         ins->inst_p0 = cmethod;
5380                         MONO_ADD_INS (bblock, ins);
5381                         ip += 5;
5382                         start_new_bblock = 1;
5383                         break;
5384                 case CEE_CALLI:
5385                 case CEE_CALL:
5386                 case CEE_CALLVIRT: {
5387                         MonoInst *addr = NULL;
5388                         MonoMethodSignature *fsig = NULL;
5389                         int temp, array_rank = 0;
5390                         int virtual = *ip == CEE_CALLVIRT;
5391                         gboolean no_spill;
5392                         int context_used = 0;
5393                         gboolean pass_vtable = FALSE;
5394                         MonoInst *vtable_arg = NULL;
5395
5396                         CHECK_OPSIZE (5);
5397                         token = read32 (ip + 1);
5398
5399                         if (*ip == CEE_CALLI) {
5400                                 cmethod = NULL;
5401                                 CHECK_STACK (1);
5402                                 --sp;
5403                                 addr = *sp;
5404                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
5405                                         fsig = (MonoMethodSignature *)mono_method_get_wrapper_data (method, token);
5406                                 else
5407                                         fsig = mono_metadata_parse_signature (image, token);
5408
5409                                 n = fsig->param_count + fsig->hasthis;
5410                         } else {
5411                                 MonoMethod *cil_method;
5412                                 
5413                                 if (method->wrapper_type != MONO_WRAPPER_NONE) {
5414                                         cmethod =  (MonoMethod *)mono_method_get_wrapper_data (method, token);
5415                                         cil_method = cmethod;
5416                                 } else if (constrained_call) {
5417                                         cmethod = mono_get_method_constrained (image, token, constrained_call, generic_context, &cil_method);
5418                                         cil_method = cmethod;
5419                                 } else {
5420                                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
5421                                         cil_method = cmethod;
5422                                 }
5423
5424                                 if (!cmethod)
5425                                         goto load_error;
5426                                 if (!dont_verify && !cfg->skip_visibility) {
5427                                         MonoMethod *target_method = cil_method;
5428                                         if (method->is_inflated) {
5429                                                 target_method = mini_get_method_allow_open (method, token, NULL, &method_definition->generic_container->context);
5430                                         }
5431                                         if (!mono_method_can_access_method (method_definition, target_method) &&
5432                                                 !mono_method_can_access_method (method, cil_method))
5433                                                 METHOD_ACCESS_FAILURE;
5434                                 }
5435
5436                                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
5437                                         ensure_method_is_allowed_to_call_method (cfg, method, cil_method, bblock, ip);
5438
5439                                 if (!virtual && (cmethod->flags & METHOD_ATTRIBUTE_ABSTRACT))
5440                                         /* MS.NET seems to silently convert this to a callvirt */
5441                                         virtual = 1;
5442
5443                                 if (!cmethod->klass->inited){
5444                                         if (!mono_class_init (cmethod->klass))
5445                                                 goto load_error;
5446                                 }
5447
5448                                 if (mono_method_signature (cmethod)->pinvoke) {
5449                                         MonoMethod *wrapper = mono_marshal_get_native_wrapper (cmethod, check_for_pending_exc);
5450                                         fsig = mono_method_signature (wrapper);
5451                                 } else if (constrained_call) {
5452                                         fsig = mono_method_signature (cmethod);
5453                                 } else {
5454                                         fsig = mono_method_get_signature_full (cmethod, image, token, generic_context);
5455                                 }
5456
5457                                 mono_save_token_info (cfg, image, token, cmethod);
5458
5459                                 n = fsig->param_count + fsig->hasthis;
5460
5461                                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
5462                                         if (check_linkdemand (cfg, method, cmethod, bblock, ip))
5463                                                 INLINE_FAILURE;
5464                                         CHECK_CFG_EXCEPTION;
5465                                 }
5466
5467                                 if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL &&
5468                                     mini_class_is_system_array (cmethod->klass)) {
5469                                         array_rank = cmethod->klass->rank;
5470                                 }
5471
5472                                 if (cmethod->string_ctor)
5473                                         g_assert_not_reached ();
5474
5475                         }
5476
5477                         if (!cfg->generic_sharing_context && cmethod && cmethod->klass->generic_container)
5478                                 UNVERIFIED;
5479
5480                         CHECK_STACK (n);
5481
5482                         //g_assert (!virtual || fsig->hasthis);
5483
5484                         sp -= n;
5485
5486                         if (constrained_call) {
5487                                 /*
5488                                  * We have the `constrained.' prefix opcode.
5489                                  */
5490                                 if (constrained_call->valuetype && !cmethod->klass->valuetype) {
5491                                         MonoInst *load;
5492                                         /*
5493                                          * The type parameter is instantiated as a valuetype,
5494                                          * but that type doesn't override the method we're
5495                                          * calling, so we need to box `this'.
5496                                          * sp [0] is a pointer to the data: we need the value
5497                                          * in handle_box (), so load it here.
5498                                          */
5499                                         MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, &constrained_call->byval_arg));
5500                                         type_to_eval_stack_type (cfg, &constrained_call->byval_arg, load);
5501                                         load->cil_code = ip;
5502                                         load->inst_left = sp [0];
5503                                         sp [0] = handle_box (cfg, bblock, load, ip, constrained_call);
5504                                 } else if (!constrained_call->valuetype) {
5505                                         MonoInst *ins;
5506
5507                                         /*
5508                                          * The type parameter is instantiated as a reference
5509                                          * type.  We have a managed pointer on the stack, so
5510                                          * we need to dereference it here.
5511                                          */
5512
5513                                         MONO_INST_NEW (cfg, ins, CEE_LDIND_REF);
5514                                         ins->cil_code = ip;
5515                                         ins->inst_i0 = sp [0];
5516                                         ins->type = STACK_OBJ;
5517                                         ins->klass = mono_class_from_mono_type (&constrained_call->byval_arg);
5518                                         sp [0] = ins;
5519                                 } else if (cmethod->klass->valuetype)
5520                                         virtual = 0;
5521                                 constrained_call = NULL;
5522                         }
5523
5524                         if (*ip != CEE_CALLI && check_call_signature (cfg, fsig, sp))
5525                                 UNVERIFIED;
5526
5527                         if (cmethod && (cmethod->flags & METHOD_ATTRIBUTE_STATIC) &&
5528                                         (cmethod->klass->generic_class || cmethod->klass->generic_container)) {
5529                                 gboolean sharing_enabled = mono_class_generic_sharing_enabled (cmethod->klass);
5530                                 MonoGenericContext *context = mini_class_get_context (cmethod->klass);
5531                                 gboolean context_sharable = mono_generic_context_is_sharable (context, TRUE);
5532
5533                                 /*
5534                                  * Pass vtable iff target method might
5535                                  * be shared, which means that sharing
5536                                  * is enabled for its class and its
5537                                  * context is sharable (and it's not a
5538                                  * generic method).
5539                                  */
5540                                 if (sharing_enabled && context_sharable &&
5541                                                 !mini_method_get_context (cmethod)->method_inst)
5542                                         pass_vtable = TRUE;
5543                         }
5544
5545                         if (cfg->generic_sharing_context && cmethod) {
5546                                 MonoGenericContext *cmethod_context = mono_method_get_context (cmethod);
5547
5548                                 context_used = mono_method_check_context_used (cmethod);
5549
5550                                 if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD)
5551                                         GENERIC_SHARING_FAILURE (*ip);
5552
5553                                 if (context_used &&
5554                                                 ((cmethod->klass->flags & TYPE_ATTRIBUTE_INTERFACE) ||
5555                                                 (cmethod_context && cmethod_context->method_inst && cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL))) {
5556                                         GENERIC_SHARING_FAILURE (*ip);
5557                                 }
5558                         }
5559
5560                         if (pass_vtable) {
5561                                 if (context_used) {
5562                                         MonoInst *rgctx;
5563
5564                                         GET_RGCTX (rgctx);
5565                                         vtable_arg = get_runtime_generic_context_ptr (cfg, method, bblock, cmethod->klass,
5566                                                 token, MINI_TOKEN_SOURCE_METHOD, generic_context,
5567                                                 rgctx, MONO_RGCTX_INFO_VTABLE, ip);
5568                                 } else {
5569                                         MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
5570
5571                                         NEW_VTABLECONST (cfg, vtable_arg, vtable);
5572                                 }
5573                         }
5574
5575                         if (cmethod && virtual && 
5576                             (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) && 
5577                             !((cmethod->flags & METHOD_ATTRIBUTE_FINAL) && 
5578                               cmethod->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK) &&
5579                             mono_method_signature (cmethod)->generic_param_count) {
5580                                 MonoInst *this_temp, *this_arg_temp, *store;
5581                                 MonoInst *iargs [4];
5582
5583                                 g_assert (mono_method_signature (cmethod)->is_inflated);
5584                                 /* Prevent inlining of methods that contain indirect calls */
5585                                 INLINE_FAILURE;
5586
5587                                 this_temp = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
5588                                 this_temp->cil_code = ip;
5589                                 NEW_TEMPSTORE (cfg, store, this_temp->inst_c0, sp [0]);
5590
5591                                 store->cil_code = ip;
5592                                 MONO_ADD_INS (bblock, store);
5593
5594                                 /* FIXME: This should be a managed pointer */
5595                                 this_arg_temp = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
5596                                 this_arg_temp->cil_code = ip;
5597
5598                                 /* Because of the PCONST below */
5599                                 cfg->disable_aot = TRUE;
5600                                 NEW_TEMPLOAD (cfg, iargs [0], this_temp->inst_c0);
5601                                 NEW_METHODCONST (cfg, iargs [1], cmethod);
5602                                 NEW_PCONST (cfg, iargs [2], mono_method_get_context (cmethod));
5603                                 NEW_TEMPLOADA (cfg, iargs [3], this_arg_temp->inst_c0);
5604                                 temp = mono_emit_jit_icall (cfg, bblock, mono_helper_compile_generic_method, iargs, ip);
5605
5606                                 NEW_TEMPLOAD (cfg, addr, temp);
5607                                 NEW_TEMPLOAD (cfg, sp [0], this_arg_temp->inst_c0);
5608
5609                                 if ((temp = mono_emit_calli_spilled (cfg, bblock, fsig, sp, addr, ip)) != -1) {
5610                                         NEW_TEMPLOAD (cfg, *sp, temp);
5611                                         sp++;
5612                                 }
5613
5614                                 ip += 5;
5615                                 ins_flag = 0;
5616                                 break;
5617                         }
5618
5619                         /* FIXME: runtime generic context pointer for jumps? */
5620                         if ((ins_flag & MONO_INST_TAILCALL) && cmethod && (*ip == CEE_CALL) &&
5621                                  (mono_metadata_signature_equal (mono_method_signature (method), mono_method_signature (cmethod)))) {
5622                                 int i;
5623
5624                                 GENERIC_SHARING_FAILURE (*ip);
5625
5626                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
5627                                 INLINE_FAILURE;
5628                                 /* FIXME: This assumes the two methods has the same number and type of arguments */
5629                                 /*
5630                                  * We implement tail calls by storing the actual arguments into the 
5631                                  * argument variables, then emitting a OP_JMP. Since the actual arguments
5632                                  * can refer to the arg variables, we have to spill them.
5633                                  */
5634                                 handle_loaded_temps (cfg, bblock, sp, sp + n);
5635                                 for (i = 0; i < n; ++i) {
5636                                         /* Prevent argument from being register allocated */
5637                                         arg_array [i]->flags |= MONO_INST_VOLATILE;
5638
5639                                         /* Check if argument is the same */
5640                                         /* 
5641                                          * FIXME: This loses liveness info, so it can only be done if the
5642                                          * argument is not register allocated.
5643                                          */
5644                                         NEW_ARGLOAD (cfg, ins, i);
5645                                         if ((ins->opcode == sp [i]->opcode) && (ins->inst_i0 == sp [i]->inst_i0))
5646                                                 continue;
5647
5648                                         NEW_ARGSTORE (cfg, ins, i, sp [i]);
5649                                         ins->cil_code = ip;
5650                                         /* FIXME: handle CEE_STIND_R4 */
5651                                         if (ins->opcode == CEE_STOBJ) {
5652                                                 NEW_ARGLOADA (cfg, ins, i);
5653                                                 handle_stobj (cfg, bblock, ins, sp [i], sp [i]->cil_code, ins->klass, FALSE, FALSE, FALSE);
5654                                         }
5655                                         else
5656                                                 MONO_ADD_INS (bblock, ins);
5657                                 }
5658                                 MONO_INST_NEW (cfg, ins, OP_JMP);
5659                                 ins->cil_code = ip;
5660                                 ins->inst_p0 = cmethod;
5661                                 ins->inst_p1 = arg_array [0];
5662                                 MONO_ADD_INS (bblock, ins);
5663                                 link_bblock (cfg, bblock, end_bblock);                  
5664                                 start_new_bblock = 1;
5665                                 /* skip CEE_RET as well */
5666                                 ip += 6;
5667                                 ins_flag = 0;
5668                                 break;
5669                         }
5670                         if (cmethod && (cfg->opt & MONO_OPT_INTRINS) && (ins = mini_get_inst_for_method (cfg, cmethod, fsig, sp))) {
5671                                 ins->cil_code = ip;
5672
5673                                 if (MONO_TYPE_IS_VOID (fsig->ret)) {
5674                                         MONO_ADD_INS (bblock, ins);
5675                                 } else {
5676                                         type_to_eval_stack_type (cfg, fsig->ret, ins);
5677                                         *sp = ins;
5678                                         sp++;
5679                                 }
5680
5681                                 ip += 5;
5682                                 ins_flag = 0;
5683                                 break;
5684                         }
5685
5686                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5687
5688                         if ((cfg->opt & MONO_OPT_INLINE) && cmethod &&
5689                             (!virtual || !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) || (cmethod->flags & METHOD_ATTRIBUTE_FINAL)) && 
5690                             mono_method_check_inlining (cfg, cmethod) &&
5691                                  !g_list_find (dont_inline, cmethod)) {
5692                                 int costs;
5693                                 MonoBasicBlock *ebblock;
5694                                 gboolean allways = FALSE;
5695
5696                                 if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
5697                                         (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5698                                         /* Prevent inlining of methods that call wrappers */
5699                                         INLINE_FAILURE;
5700                                         cmethod = mono_marshal_get_native_wrapper (cmethod, check_for_pending_exc);
5701                                         allways = TRUE;
5702                                 }
5703
5704                                 if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock, allways))) {
5705                                         ip += 5;
5706                                         real_offset += 5;
5707
5708                                         GET_BBLOCK (cfg, bblock, ip);
5709                                         ebblock->next_bb = bblock;
5710                                         link_bblock (cfg, ebblock, bblock);
5711
5712                                         if (!MONO_TYPE_IS_VOID (fsig->ret))
5713                                                 sp++;
5714
5715                                         /* indicates start of a new block, and triggers a load of all 
5716                                            stack arguments at bb boundarie */
5717                                         bblock = ebblock;
5718
5719                                         inline_costs += costs;
5720                                         ins_flag = 0;
5721                                         break;
5722                                 }
5723                         }
5724                         
5725                         inline_costs += 10 * num_calls++;
5726
5727                         /* tail recursion elimination */
5728                         if ((cfg->opt & MONO_OPT_TAILC) && *ip == CEE_CALL && cmethod == method && ip [5] == CEE_RET &&
5729                                         !vtable_arg) {
5730                                 gboolean has_vtargs = FALSE;
5731                                 int i;
5732                                 
5733                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
5734                                 INLINE_FAILURE;
5735                                 /* keep it simple */
5736                                 for (i =  fsig->param_count - 1; i >= 0; i--) {
5737                                         if (MONO_TYPE_ISSTRUCT (mono_method_signature (cmethod)->params [i])) 
5738                                                 has_vtargs = TRUE;
5739                                 }
5740
5741                                 if (!has_vtargs) {
5742                                         for (i = 0; i < n; ++i) {
5743                                                 /* FIXME: handle CEE_STIND_R4 */
5744                                                 NEW_ARGSTORE (cfg, ins, i, sp [i]);
5745                                                 ins->cil_code = ip;
5746                                                 MONO_ADD_INS (bblock, ins);
5747                                         }
5748                                         MONO_INST_NEW (cfg, ins, OP_BR);
5749                                         ins->cil_code = ip;
5750                                         MONO_ADD_INS (bblock, ins);
5751                                         tblock = start_bblock->out_bb [0];
5752                                         link_bblock (cfg, bblock, tblock);
5753                                         ins->inst_target_bb = tblock;
5754                                         start_new_bblock = 1;
5755
5756                                         /* skip the CEE_RET, too */
5757                                         if (ip_in_bb (cfg, bblock, ip + 5))
5758                                                 ip += 6;
5759                                         else
5760                                                 ip += 5;
5761                                         ins_flag = 0;
5762                                         break;
5763                                 }
5764                         }
5765
5766                         if (ip_in_bb (cfg, bblock, ip + 5) 
5767                                 && (!MONO_TYPE_ISSTRUCT (fsig->ret))
5768                                 && (!MONO_TYPE_IS_VOID (fsig->ret) || (cmethod && cmethod->string_ctor))
5769                                 && (CODE_IS_STLOC (ip + 5) || ip [5] == CEE_POP || ip [5] == CEE_RET))
5770                                 /* No need to spill */
5771                                 no_spill = TRUE;
5772                         else
5773                                 no_spill = FALSE;
5774
5775                         if (context_used &&
5776                                         (cmethod->klass->valuetype ||
5777                                         (cmethod->is_inflated && mono_method_get_context (cmethod)->method_inst) ||
5778                                         ((cmethod->flags & METHOD_ATTRIBUTE_STATIC) &&
5779                                                 mono_class_generic_sharing_enabled (cmethod->klass)))) {
5780                                 MonoInst *this = NULL, *rgctx;
5781
5782                                 INLINE_FAILURE;
5783
5784                                 g_assert (cfg->generic_sharing_context && cmethod);
5785                                 g_assert (addr == NULL);
5786
5787                                 /*
5788                                  * We are compiling a call to a
5789                                  * generic method from shared code,
5790                                  * which means that we have to look up
5791                                  * the method in the rgctx and do an
5792                                  * indirect call.
5793                                  */
5794
5795                                 GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD (*ip);
5796
5797                                 if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
5798                                         NEW_ARGLOAD (cfg, this, 0);
5799                                 rgctx = get_runtime_generic_context (cfg, method, this, ip);
5800                                 addr = get_runtime_generic_context_method (cfg, method, bblock, cmethod,
5801                                                 generic_context, rgctx, MONO_RGCTX_INFO_GENERIC_METHOD_CODE, ip);
5802                         }
5803
5804                         if (addr) {
5805                                 if (*ip == CEE_CALL)
5806                                         g_assert (context_used);
5807                                 else if (*ip == CEE_CALLI)
5808                                         g_assert (!vtable_arg);
5809                                 else
5810                                         g_assert_not_reached ();
5811
5812                                 /* Prevent inlining of methods with indirect calls */
5813                                 INLINE_FAILURE;
5814                                 if (no_spill) {
5815                                         ins = (MonoInst*)mono_emit_rgctx_calli (cfg, bblock, fsig, sp, addr, vtable_arg, ip);
5816                                         *sp++ = ins;                                    
5817                                 } else {
5818                                         temp = mono_emit_rgctx_calli_spilled (cfg, bblock, fsig, sp, addr, vtable_arg, ip);
5819                                         if (temp != -1) {
5820                                                 NEW_TEMPLOAD (cfg, *sp, temp);
5821                                                 sp++;
5822                                         }
5823                                 }                       
5824                         } else if (array_rank) {
5825                                 MonoInst *addr;
5826
5827                                 if (strcmp (cmethod->name, "Set") == 0) { /* array Set */ 
5828                                         if (sp [fsig->param_count]->type == STACK_OBJ) {
5829                                                 MonoInst *iargs [2];
5830                                                 MonoInst *array, *to_store, *store;
5831
5832                                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
5833                                                 
5834                                                 array = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
5835                                                 NEW_TEMPSTORE (cfg, store, array->inst_c0, sp [0]);
5836                                                 store->cil_code = ip;
5837                                                 MONO_ADD_INS (bblock, store);
5838                                                 NEW_TEMPLOAD (cfg, iargs [0], array->inst_c0);
5839
5840                                                 to_store = mono_compile_create_var (cfg, type_from_stack_type (sp [fsig->param_count]), OP_LOCAL);
5841                                                 NEW_TEMPSTORE (cfg, store, to_store->inst_c0, sp [fsig->param_count]);
5842                                                 /* FIXME: handle CEE_STIND_R4 */
5843                                                 store->cil_code = ip;
5844                                                 MONO_ADD_INS (bblock, store);
5845                                                 NEW_TEMPLOAD (cfg, iargs [1], to_store->inst_c0);
5846
5847                                                 /*
5848                                                  * We first save the args for the call so that the args are copied to the stack
5849                                                  * and a new instruction tree for them is created. If we don't do this,
5850                                                  * the same MonoInst is added to two different trees and this is not 
5851                                                  * allowed by burg.
5852                                                  */
5853                                                 mono_emit_jit_icall (cfg, bblock, mono_helper_stelem_ref_check, iargs, ip);
5854
5855                                                 NEW_TEMPLOAD (cfg, sp [0], array->inst_c0);
5856                                                 NEW_TEMPLOAD (cfg, sp [fsig->param_count], to_store->inst_c0);
5857                                         }
5858
5859                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, TRUE);
5860                                         NEW_INDSTORE (cfg, ins, addr, sp [fsig->param_count], fsig->params [fsig->param_count - 1]);
5861                                         ins->cil_code = ip;
5862                                         /* FIXME: handle CEE_STIND_R4 */
5863                                         if (ins->opcode == CEE_STOBJ) {
5864                                                 handle_stobj (cfg, bblock, addr, sp [fsig->param_count], ip, mono_class_from_mono_type (fsig->params [fsig->param_count-1]), FALSE, FALSE, TRUE);
5865                                         } else {
5866                                                 MONO_ADD_INS (bblock, ins);
5867                                         }
5868
5869                                 } else if (strcmp (cmethod->name, "Get") == 0) { /* array Get */
5870                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
5871                                         NEW_INDLOAD (cfg, ins, addr, fsig->ret);
5872                                         ins->cil_code = ip;
5873
5874                                         *sp++ = ins;
5875                                 } else if (strcmp (cmethod->name, "Address") == 0) { /* array Address */
5876                                         if (!cmethod->klass->element_class->valuetype && !readonly) {
5877                                                 MonoInst* check;
5878                                                 //* Needed by the code generated in inssel.brg * /
5879                                                 mono_get_got_var (cfg);
5880
5881                                                 MONO_INST_NEW (cfg, check, OP_CHECK_ARRAY_TYPE);
5882                                                 check->cil_code = ip;
5883                                                 check->klass = cmethod->klass;
5884                                                 check->inst_left = sp [0];
5885                                                 check->type = STACK_OBJ;
5886                                                 sp [0] = check;
5887                                         }
5888
5889                                         readonly = FALSE;
5890                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
5891                                         *sp++ = addr;
5892                                 } else {
5893                                         g_assert_not_reached ();
5894                                 }
5895
5896                         } else {
5897                                 /* Prevent inlining of methods which call other methods */
5898                                 INLINE_FAILURE;
5899                                 if (mini_redirect_call (&temp, cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL)) {
5900                                         if (temp != -1) {
5901                                                 NEW_TEMPLOAD (cfg, *sp, temp);
5902                                                 sp++;
5903                                         }
5904                                 } else if (no_spill) {
5905                                         ins = (MonoInst*)mono_emit_rgctx_method_call (cfg, bblock, cmethod, fsig, sp,
5906                                                         vtable_arg, ip, virtual ? sp [0] : NULL);
5907                                         *sp++ = ins;
5908                                 } else {
5909                                         if ((temp = mono_emit_rgctx_method_call_spilled (cfg, bblock, cmethod, fsig, sp,
5910                                                         vtable_arg, ip, virtual ? sp [0] : NULL)) != -1) {
5911                                                 MonoInst *load;
5912                                                 NEW_TEMPLOAD (cfg, load, temp);
5913
5914 #ifdef MONO_ARCH_SOFT_FLOAT
5915                                                 if (load->opcode == CEE_LDIND_R4) {
5916                                                         NEW_TEMPLOADA (cfg, load, temp);
5917                                                         temp = handle_load_float (cfg, bblock, load, ip);
5918                                                         NEW_TEMPLOAD (cfg, load, temp);
5919                                                 }
5920 #endif
5921                                                 *sp++ = load;
5922                                         }
5923                                 }
5924                         }
5925
5926                         ip += 5;
5927                         ins_flag = 0;
5928                         break;
5929                 }
5930                 case CEE_RET:
5931                         if (cfg->method != method) {
5932                                 /* return from inlined method */
5933                                 if (return_var) {
5934                                         MonoInst *store;
5935                                         CHECK_STACK (1);
5936                                         --sp;
5937                                         //g_assert (returnvar != -1);
5938                                         NEW_TEMPSTORE (cfg, store, return_var->inst_c0, *sp);
5939                                         store->cil_code = sp [0]->cil_code;
5940                                         /* FIXME: handle CEE_STIND_R4 */
5941                                         if (store->opcode == CEE_STOBJ) {
5942                                                 g_assert_not_reached ();
5943                                                 NEW_TEMPLOADA (cfg, store, return_var->inst_c0);
5944                                                 /* FIXME: it is possible some optimization will pass the a heap pointer for the struct address, so we'll need the write barrier */
5945                                                 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, return_var->klass, FALSE, FALSE, FALSE);
5946 #ifdef MONO_ARCH_SOFT_FLOAT
5947                                         } else if (store->opcode == CEE_STIND_R4) {
5948                                                 NEW_TEMPLOADA (cfg, store, return_var->inst_c0);
5949                                                 handle_store_float (cfg, bblock, store, *sp, sp [0]->cil_code);
5950 #endif
5951                                         } else
5952                                                 MONO_ADD_INS (bblock, store);
5953                                 } 
5954                         } else {
5955                                 if (cfg->ret) {
5956                                         g_assert (!return_var);
5957                                         CHECK_STACK (1);
5958                                         --sp;
5959                                         MONO_INST_NEW (cfg, ins, OP_NOP);
5960                                         ins->opcode = mini_type_to_stind (cfg, mono_method_signature (method)->ret);
5961                                         if (ins->opcode == CEE_STOBJ) {
5962                                                 NEW_RETLOADA (cfg, ins);
5963                                                 /* FIXME: it is possible some optimization will pass the a heap pointer for the struct address, so we'll need the write barrier */
5964                                                 handle_stobj (cfg, bblock, ins, *sp, ip, cfg->ret->klass, FALSE, FALSE, FALSE);
5965                                         } else {
5966                                                 ins->opcode = OP_SETRET;
5967                                                 ins->cil_code = ip;
5968                                                 ins->inst_i0 = *sp;;
5969                                                 ins->inst_i1 = NULL;
5970                                                 MONO_ADD_INS (bblock, ins);
5971                                         }
5972                                 }
5973                         }
5974                         if (sp != stack_start)
5975                                 UNVERIFIED;
5976                         MONO_INST_NEW (cfg, ins, OP_BR);
5977                         ins->cil_code = ip++;
5978                         ins->inst_target_bb = end_bblock;
5979                         MONO_ADD_INS (bblock, ins);
5980                         link_bblock (cfg, bblock, end_bblock);
5981                         start_new_bblock = 1;
5982                         break;
5983                 case CEE_BR_S:
5984                         CHECK_OPSIZE (2);
5985                         MONO_INST_NEW (cfg, ins, OP_BR);
5986                         ins->cil_code = ip++;
5987                         MONO_ADD_INS (bblock, ins);
5988                         target = ip + 1 + (signed char)(*ip);
5989                         ++ip;
5990                         GET_BBLOCK (cfg, tblock, target);
5991                         link_bblock (cfg, bblock, tblock);
5992                         CHECK_BBLOCK (target, ip, tblock);
5993                         ins->inst_target_bb = tblock;
5994                         if (sp != stack_start) {
5995                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5996                                 sp = stack_start;
5997                                 CHECK_UNVERIFIABLE (cfg);
5998                         }
5999                         start_new_bblock = 1;
6000                         inline_costs += BRANCH_COST;
6001                         break;
6002                 case CEE_BRFALSE_S:
6003                 case CEE_BRTRUE_S:
6004                         CHECK_OPSIZE (2);
6005                         CHECK_STACK (1);
6006                         if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
6007                                 UNVERIFIED;
6008                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
6009                         ins->cil_code = ip++;
6010                         target = ip + 1 + *(signed char*)ip;
6011                         ip++;
6012                         ADD_UNCOND (ins->opcode == CEE_BRTRUE);
6013                         if (sp != stack_start) {
6014                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6015                                 sp = stack_start;
6016                                 CHECK_UNVERIFIABLE (cfg);
6017                         }
6018                         inline_costs += BRANCH_COST;
6019                         break;
6020                 case CEE_BEQ_S:
6021                 case CEE_BGE_S:
6022                 case CEE_BGT_S:
6023                 case CEE_BLE_S:
6024                 case CEE_BLT_S:
6025                 case CEE_BNE_UN_S:
6026                 case CEE_BGE_UN_S:
6027                 case CEE_BGT_UN_S:
6028                 case CEE_BLE_UN_S:
6029                 case CEE_BLT_UN_S:
6030                         CHECK_OPSIZE (2);
6031                         CHECK_STACK (2);
6032                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
6033                         ins->cil_code = ip++;
6034                         target = ip + 1 + *(signed char*)ip;
6035                         ip++;
6036 #ifdef MONO_ARCH_SOFT_FLOAT
6037                         if (sp [-1]->type == STACK_R8 || sp [-2]->type == STACK_R8) {
6038                                 ins->opcode = condbr_to_fp_br (ins->opcode);
6039                                 sp -= 2;
6040                                 ins->inst_left = sp [0];
6041                                 ins->inst_right = sp [1];
6042                                 ins->type = STACK_I4;
6043                                 *sp++ = emit_tree (cfg, bblock, ins, ins->cil_code);
6044                                 MONO_INST_NEW (cfg, ins, CEE_BRTRUE);
6045                                 ADD_UNCOND (TRUE);
6046                         } else {
6047                                 ADD_BINCOND (NULL);
6048                         }
6049 #else
6050                         ADD_BINCOND (NULL);
6051 #endif
6052                         if (sp != stack_start) {
6053                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6054                                 sp = stack_start;
6055                                 CHECK_UNVERIFIABLE (cfg);
6056                         }
6057                         inline_costs += BRANCH_COST;
6058                         break;
6059                 case CEE_BR:
6060                         CHECK_OPSIZE (5);
6061                         MONO_INST_NEW (cfg, ins, OP_BR);
6062                         ins->cil_code = ip++;
6063                         MONO_ADD_INS (bblock, ins);
6064                         target = ip + 4 + (gint32)read32(ip);
6065                         ip += 4;
6066                         GET_BBLOCK (cfg, tblock, target);
6067                         link_bblock (cfg, bblock, tblock);
6068                         CHECK_BBLOCK (target, ip, tblock);
6069                         ins->inst_target_bb = tblock;
6070                         if (sp != stack_start) {
6071                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6072                                 sp = stack_start;
6073                                 CHECK_UNVERIFIABLE (cfg);
6074                         }
6075                         start_new_bblock = 1;
6076                         inline_costs += BRANCH_COST;
6077                         break;
6078                 case CEE_BRFALSE:
6079                 case CEE_BRTRUE:
6080                         CHECK_OPSIZE (5);
6081                         CHECK_STACK (1);
6082                         if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
6083                                 UNVERIFIED;
6084                         MONO_INST_NEW (cfg, ins, *ip);
6085                         ins->cil_code = ip++;
6086                         target = ip + 4 + (gint32)read32(ip);
6087                         ip += 4;
6088                         ADD_UNCOND(ins->opcode == CEE_BRTRUE);
6089                         if (sp != stack_start) {
6090                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6091                                 sp = stack_start;
6092                                 CHECK_UNVERIFIABLE (cfg);
6093                         }
6094                         inline_costs += BRANCH_COST;
6095                         break;
6096                 case CEE_BEQ:
6097                 case CEE_BGE:
6098                 case CEE_BGT:
6099                 case CEE_BLE:
6100                 case CEE_BLT:
6101                 case CEE_BNE_UN:
6102                 case CEE_BGE_UN:
6103                 case CEE_BGT_UN:
6104                 case CEE_BLE_UN:
6105                 case CEE_BLT_UN:
6106                         CHECK_OPSIZE (5);
6107                         CHECK_STACK (2);
6108                         MONO_INST_NEW (cfg, ins, *ip);
6109                         ins->cil_code = ip++;
6110                         target = ip + 4 + (gint32)read32(ip);
6111                         ip += 4;
6112 #ifdef MONO_ARCH_SOFT_FLOAT
6113                         if (sp [-1]->type == STACK_R8 || sp [-2]->type == STACK_R8) {
6114                                 ins->opcode = condbr_to_fp_br (ins->opcode);
6115                                 sp -= 2;
6116                                 ins->inst_left = sp [0];
6117                                 ins->inst_right = sp [1];
6118                                 ins->type = STACK_I4;
6119                                 *sp++ = emit_tree (cfg, bblock, ins, ins->cil_code);
6120                                 MONO_INST_NEW (cfg, ins, CEE_BRTRUE);
6121                                 ADD_UNCOND (TRUE);
6122                         } else {
6123                                 ADD_BINCOND (NULL);
6124                         }
6125 #else
6126                         ADD_BINCOND (NULL);
6127 #endif
6128                         if (sp != stack_start) {
6129                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6130                                 sp = stack_start;
6131                                 CHECK_UNVERIFIABLE (cfg);
6132                         }
6133                         inline_costs += BRANCH_COST;
6134                         break;
6135                 case CEE_SWITCH:
6136                         CHECK_OPSIZE (5);
6137                         CHECK_STACK (1);
6138                         n = read32 (ip + 1);
6139                         MONO_INST_NEW (cfg, ins, OP_SWITCH);
6140                         --sp;
6141                         ins->inst_left = *sp;
6142                         if ((ins->inst_left->type != STACK_I4) && (ins->inst_left->type != STACK_PTR)) 
6143                                 UNVERIFIED;
6144                         ins->cil_code = ip;
6145                         ip += 5;
6146                         CHECK_OPSIZE (n * sizeof (guint32));
6147                         target = ip + n * sizeof (guint32);
6148                         MONO_ADD_INS (bblock, ins);
6149                         GET_BBLOCK (cfg, tblock, target);
6150                         link_bblock (cfg, bblock, tblock);
6151                         ins->klass = GUINT_TO_POINTER (n);
6152                         ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (n + 1));
6153                         ins->inst_many_bb [n] = tblock;
6154
6155                         for (i = 0; i < n; ++i) {
6156                                 GET_BBLOCK (cfg, tblock, target + (gint32)read32(ip));
6157                                 link_bblock (cfg, bblock, tblock);
6158                                 ins->inst_many_bb [i] = tblock;
6159                                 ip += 4;
6160                         }
6161                         if (sp != stack_start) {
6162                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6163                                 sp = stack_start;
6164                                 CHECK_UNVERIFIABLE (cfg);
6165                         }
6166                         /* Needed by the code generated in inssel.brg */
6167                         mono_get_got_var (cfg);
6168                         inline_costs += (BRANCH_COST * 2);
6169                         break;
6170                 case CEE_LDIND_I1:
6171                 case CEE_LDIND_U1:
6172                 case CEE_LDIND_I2:
6173                 case CEE_LDIND_U2:
6174                 case CEE_LDIND_I4:
6175                 case CEE_LDIND_U4:
6176                 case CEE_LDIND_I8:
6177                 case CEE_LDIND_I:
6178                 case CEE_LDIND_R4:
6179                 case CEE_LDIND_R8:
6180                 case CEE_LDIND_REF:
6181                         CHECK_STACK (1);
6182                         MONO_INST_NEW (cfg, ins, *ip);
6183                         ins->cil_code = ip;
6184                         --sp;
6185                         ins->inst_i0 = *sp;
6186                         *sp++ = ins;
6187                         ins->type = ldind_type [*ip - CEE_LDIND_I1];
6188                         ins->flags |= ins_flag;
6189                         ins_flag = 0;
6190                         if (ins->type == STACK_OBJ)
6191                                 ins->klass = mono_defaults.object_class;
6192 #ifdef MONO_ARCH_SOFT_FLOAT
6193                         if (*ip == CEE_LDIND_R4) {
6194                                 int temp;
6195                                 --sp;
6196                                 temp = handle_load_float (cfg, bblock, ins->inst_i0, ip);
6197                                 NEW_TEMPLOAD (cfg, *sp, temp);
6198                                 sp++;
6199                         }
6200 #endif
6201                         ++ip;
6202                         break;
6203                 case CEE_STIND_REF:
6204                 case CEE_STIND_I1:
6205                 case CEE_STIND_I2:
6206                 case CEE_STIND_I4:
6207                 case CEE_STIND_I8:
6208                 case CEE_STIND_R4:
6209                 case CEE_STIND_R8:
6210                         CHECK_STACK (2);
6211 #ifdef MONO_ARCH_SOFT_FLOAT
6212                         if (*ip == CEE_STIND_R4) {
6213                                 sp -= 2;
6214                                 handle_store_float (cfg, bblock, sp [0], sp [1], ip);
6215                                 ip++;
6216                                 break;
6217                         }
6218 #endif
6219 #if HAVE_WRITE_BARRIERS
6220                         if (*ip == CEE_STIND_REF && method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER && !((sp [-1]->opcode == OP_PCONST) && (sp [-1]->inst_p0 == 0))) {
6221                                 /* insert call to write barrier */
6222                                 MonoMethod *write_barrier = mono_marshal_get_write_barrier ();
6223                                 sp -= 2;
6224                                 mono_emit_method_call_spilled (cfg, bblock, write_barrier, mono_method_signature (write_barrier), sp, ip, NULL);
6225                                 ip++;
6226                                 break;
6227                         }
6228 #endif
6229                         MONO_INST_NEW (cfg, ins, *ip);
6230                         ins->cil_code = ip++;
6231                         sp -= 2;
6232                         handle_loaded_temps (cfg, bblock, stack_start, sp);
6233                         MONO_ADD_INS (bblock, ins);
6234                         ins->inst_i0 = sp [0];
6235                         ins->inst_i1 = sp [1];
6236                         ins->flags |= ins_flag;
6237                         ins_flag = 0;
6238                         inline_costs += 1;
6239                         break;
6240                 case CEE_MUL:
6241                         CHECK_STACK (2);
6242                         ADD_BINOP (*ip);
6243
6244 #ifdef MONO_ARCH_NO_EMULATE_MUL_IMM
6245                         /* FIXME: This breaks with ssapre (mono -O=ssapre loader.exe) */
6246                         if ((ins->inst_right->opcode == OP_ICONST) && !(cfg->opt & MONO_OPT_SSAPRE)) {
6247                                 switch (ins->opcode) {
6248                                 case CEE_MUL:
6249                                         ins->opcode = OP_IMUL_IMM;
6250                                         ins->inst_imm = ins->inst_right->inst_c0;
6251                                         break;
6252                                 case OP_LMUL:
6253                                         ins->opcode = OP_LMUL_IMM;
6254                                         ins->inst_imm = ins->inst_right->inst_c0;
6255                                         break;
6256                                 default:
6257                                         g_assert_not_reached ();
6258                                 }
6259                         }
6260 #endif
6261
6262                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
6263                                 --sp;
6264                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
6265                         }
6266                         ip++;
6267                         break;
6268                 case CEE_ADD:
6269                 case CEE_SUB:
6270                 case CEE_DIV:
6271                 case CEE_DIV_UN:
6272                 case CEE_REM:
6273                 case CEE_REM_UN:
6274                 case CEE_AND:
6275                 case CEE_OR:
6276                 case CEE_XOR:
6277                 case CEE_SHL:
6278                 case CEE_SHR:
6279                 case CEE_SHR_UN:
6280                         CHECK_STACK (2);
6281                         ADD_BINOP (*ip);
6282                         /* special case that gives a nice speedup and happens to workaorund a ppc jit but (for the release)
6283                          * later apply the speedup to the left shift as well
6284                          * See BUG# 57957.
6285                          */
6286                         if ((ins->opcode == OP_LSHR_UN) && (ins->type == STACK_I8) 
6287                                         && (ins->inst_right->opcode == OP_ICONST) && (ins->inst_right->inst_c0 == 32)) {
6288                                 ins->opcode = OP_LONG_SHRUN_32;
6289                                 /*g_print ("applied long shr speedup to %s\n", cfg->method->name);*/
6290                                 ip++;
6291                                 break;
6292                         }
6293                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
6294                                 --sp;
6295                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
6296                         }
6297                         ip++;
6298                         break;
6299                 case CEE_NEG:
6300                 case CEE_NOT:
6301                 case CEE_CONV_I1:
6302                 case CEE_CONV_I2:
6303                 case CEE_CONV_I4:
6304                 case CEE_CONV_R4:
6305                 case CEE_CONV_R8:
6306                 case CEE_CONV_U4:
6307                 case CEE_CONV_I8:
6308                 case CEE_CONV_U8:
6309                 case CEE_CONV_OVF_I8:
6310                 case CEE_CONV_OVF_U8:
6311                 case CEE_CONV_R_UN:
6312                         CHECK_STACK (1);
6313                         ADD_UNOP (*ip);
6314                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
6315                                 --sp;
6316                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
6317                         }
6318                         ip++;                   
6319                         break;
6320                 case CEE_CONV_OVF_I4:
6321                 case CEE_CONV_OVF_I1:
6322                 case CEE_CONV_OVF_I2:
6323                 case CEE_CONV_OVF_I:
6324                 case CEE_CONV_OVF_U:
6325                         CHECK_STACK (1);
6326
6327                         if (sp [-1]->type == STACK_R8) {
6328                                 ADD_UNOP (CEE_CONV_OVF_I8);
6329                                 ADD_UNOP (*ip);
6330                         } else {
6331                                 ADD_UNOP (*ip);
6332                         }
6333
6334                         ip++;
6335                         break;
6336                 case CEE_CONV_OVF_U1:
6337                 case CEE_CONV_OVF_U2:
6338                 case CEE_CONV_OVF_U4:
6339                         CHECK_STACK (1);
6340
6341                         if (sp [-1]->type == STACK_R8) {
6342                                 ADD_UNOP (CEE_CONV_OVF_U8);
6343                                 ADD_UNOP (*ip);
6344                         } else {
6345                                 ADD_UNOP (*ip);
6346                         }
6347
6348                         ip++;
6349                         break;
6350                 case CEE_CONV_OVF_I1_UN:
6351                 case CEE_CONV_OVF_I2_UN:
6352                 case CEE_CONV_OVF_I4_UN:
6353                 case CEE_CONV_OVF_I8_UN:
6354                 case CEE_CONV_OVF_U1_UN:
6355                 case CEE_CONV_OVF_U2_UN:
6356                 case CEE_CONV_OVF_U4_UN:
6357                 case CEE_CONV_OVF_U8_UN:
6358                 case CEE_CONV_OVF_I_UN:
6359                 case CEE_CONV_OVF_U_UN:
6360                         CHECK_STACK (1);
6361                         ADD_UNOP (*ip);
6362                         ip++;
6363                         break;
6364                 case CEE_CPOBJ:
6365                         CHECK_OPSIZE (5);
6366                         CHECK_STACK (2);
6367                         token = read32 (ip + 1);
6368                         klass = mini_get_class (method, token, generic_context);
6369                         CHECK_TYPELOAD (klass);
6370                         sp -= 2;
6371                         if (generic_class_is_reference_type (cfg, klass)) {
6372                                 MonoInst *store, *load;
6373                                 MONO_INST_NEW (cfg, load, CEE_LDIND_REF);
6374                                 load->cil_code = ip;
6375                                 load->inst_i0 = sp [1];
6376                                 load->type = STACK_OBJ;
6377                                 load->klass = klass;
6378                                 load->flags |= ins_flag;
6379                                 MONO_INST_NEW (cfg, store, CEE_STIND_REF);
6380                                 store->cil_code = ip;
6381                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
6382                                 MONO_ADD_INS (bblock, store);
6383                                 store->inst_i0 = sp [0];
6384                                 store->inst_i1 = load;
6385                                 store->flags |= ins_flag;
6386                         } else {
6387                                 guint32 align;
6388
6389                                 n = mono_class_value_size (klass, &align);
6390                                 if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
6391                                         MonoInst *copy;
6392                                         NEW_MEMCPY (cfg, copy, sp [0], sp [1], n, align);
6393                                         MONO_ADD_INS (bblock, copy);
6394                                 } else {
6395                                         MonoMethod *memcpy_method = get_memcpy_method ();
6396                                         MonoInst *iargs [3];
6397                                         iargs [0] = sp [0];
6398                                         iargs [1] = sp [1];
6399                                         NEW_ICONST (cfg, iargs [2], n);
6400                                         iargs [2]->cil_code = ip;
6401
6402                                         mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
6403                                 }
6404                         }
6405                         ins_flag = 0;
6406                         ip += 5;
6407                         break;
6408                 case CEE_LDOBJ: {
6409                         MonoInst *iargs [3];
6410                         int loc_index = -1;
6411                         int stloc_len = 0;
6412                         guint32 align;
6413
6414                         CHECK_OPSIZE (5);
6415                         CHECK_STACK (1);
6416                         --sp;
6417                         token = read32 (ip + 1);
6418                         klass = mini_get_class (method, token, generic_context);
6419                         CHECK_TYPELOAD (klass);
6420                         if (generic_class_is_reference_type (cfg, klass)) {
6421                                 MONO_INST_NEW (cfg, ins, CEE_LDIND_REF);
6422                                 ins->cil_code = ip;
6423                                 ins->inst_i0 = sp [0];
6424                                 ins->type = STACK_OBJ;
6425                                 ins->klass = klass;
6426                                 ins->flags |= ins_flag;
6427                                 ins_flag = 0;
6428                                 *sp++ = ins;
6429                                 ip += 5;
6430                                 break;
6431                         }
6432
6433                         /* Optimize the common ldobj+stloc combination */
6434                         switch (ip [5]) {
6435                         case CEE_STLOC_S:
6436                                 loc_index = ip [6];
6437                                 stloc_len = 2;
6438                                 break;
6439                         case CEE_STLOC_0:
6440                         case CEE_STLOC_1:
6441                         case CEE_STLOC_2:
6442                         case CEE_STLOC_3:
6443                                 loc_index = ip [5] - CEE_STLOC_0;
6444                                 stloc_len = 1;
6445                                 break;
6446                         default:
6447                                 break;
6448                         }
6449
6450                         if ((loc_index != -1) && ip_in_bb (cfg, bblock, ip + 5)) {
6451                                 CHECK_LOCAL (loc_index);
6452                                 NEW_LOCSTORE (cfg, ins, loc_index, *sp);
6453
6454                                 /* FIXME: handle CEE_STIND_R4 */
6455                                 if (ins->opcode == CEE_STOBJ) {
6456                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
6457                                         ins->cil_code = ip;
6458                                         g_assert (ins->opcode == CEE_STOBJ);
6459                                         NEW_LOCLOADA (cfg, ins, loc_index);
6460                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
6461                                         ip += 5;
6462                                         ip += stloc_len;
6463                                         break;
6464                                 }
6465                         }
6466
6467                         n = mono_class_value_size (klass, &align);
6468                         ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
6469                         NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
6470                         if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
6471                                 MonoInst *copy;
6472                                 NEW_MEMCPY (cfg, copy, iargs [0], *sp, n, align);
6473                                 MONO_ADD_INS (bblock, copy);
6474                         } else {
6475                                 MonoMethod *memcpy_method = get_memcpy_method ();
6476                                 iargs [1] = *sp;
6477                                 NEW_ICONST (cfg, iargs [2], n);
6478                                 iargs [2]->cil_code = ip;
6479
6480                                 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
6481                         }
6482                         NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
6483                         ++sp;
6484                         ip += 5;
6485                         ins_flag = 0;
6486                         inline_costs += 1;
6487                         break;
6488                 }
6489                 case CEE_LDSTR:
6490                         CHECK_STACK_OVF (1);
6491                         CHECK_OPSIZE (5);
6492                         n = read32 (ip + 1);
6493
6494                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
6495                                 /* FIXME: moving GC */
6496                                 NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, n));
6497                                 ins->cil_code = ip;
6498                                 ins->type = STACK_OBJ;
6499                                 ins->klass = mono_defaults.string_class;
6500                                 *sp = ins;
6501                         }
6502                         else if (method->wrapper_type != MONO_WRAPPER_NONE) {
6503                                 int temp;
6504                                 MonoInst *iargs [1];
6505
6506                                 NEW_PCONST (cfg, iargs [0], mono_method_get_wrapper_data (method, n));                          
6507                                 temp = mono_emit_jit_icall (cfg, bblock, mono_string_new_wrapper, iargs, ip);
6508                                 NEW_TEMPLOAD (cfg, *sp, temp);
6509
6510                         } else {
6511
6512                                 if (cfg->opt & MONO_OPT_SHARED) {
6513                                         int temp;
6514                                         MonoInst *iargs [3];
6515                                         MonoInst* domain_var;
6516                                         
6517                                         if (cfg->compile_aot) {
6518                                                 /* FIXME: bug when inlining methods from different assemblies (n is a token valid just in one). */
6519                                                 cfg->ldstr_list = g_list_prepend (cfg->ldstr_list, GINT_TO_POINTER (n));
6520                                         }
6521                                         /* avoid depending on undefined C behavior in sequence points */
6522                                         domain_var = mono_get_domainvar (cfg);
6523                                         NEW_TEMPLOAD (cfg, iargs [0], domain_var->inst_c0);
6524                                         NEW_IMAGECONST (cfg, iargs [1], image);
6525                                         NEW_ICONST (cfg, iargs [2], mono_metadata_token_index (n));
6526                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldstr, iargs, ip);
6527                                         NEW_TEMPLOAD (cfg, *sp, temp);
6528                                         mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
6529                                 } else {
6530                                         if (bblock->out_of_line) {
6531                                                 MonoInst *iargs [2];
6532                                                 int temp;
6533
6534                                                 if (cfg->method->klass->image == mono_defaults.corlib) {
6535                                                         /* 
6536                                                          * Avoid relocations and save some code size by using a 
6537                                                          * version of helper_ldstr specialized to mscorlib.
6538                                                          */
6539                                                         NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (n));
6540                                                         temp = mono_emit_jit_icall (cfg, bblock, mono_helper_ldstr_mscorlib, iargs, ip);
6541                                                 } else {
6542                                                         /* Avoid creating the string object */
6543                                                         NEW_IMAGECONST (cfg, iargs [0], image);
6544                                                         NEW_ICONST (cfg, iargs [1], mono_metadata_token_index (n));
6545                                                         temp = mono_emit_jit_icall (cfg, bblock, mono_helper_ldstr, iargs, ip);
6546                                                 }
6547                                                 NEW_TEMPLOAD (cfg, *sp, temp);
6548                                         } 
6549                                         else
6550                                         if (cfg->compile_aot) {
6551                                                 NEW_LDSTRCONST (cfg, ins, image, n);
6552                                                 *sp = ins;
6553                                         } 
6554                                         else {
6555                                                 NEW_PCONST (cfg, ins, NULL);
6556                                                 ins->cil_code = ip;
6557                                                 ins->type = STACK_OBJ;
6558                                                 ins->inst_p0 = mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
6559                                                 ins->klass = mono_defaults.string_class;
6560                                                 *sp = ins;
6561                                         }
6562                                 }
6563                         }
6564
6565                         sp++;
6566                         ip += 5;
6567                         break;
6568                 case CEE_NEWOBJ: {
6569                         MonoInst *iargs [2];
6570                         MonoMethodSignature *fsig;
6571                         int temp;
6572                         gboolean generic_shared = FALSE;
6573
6574                         CHECK_OPSIZE (5);
6575                         token = read32 (ip + 1);
6576                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
6577                         if (!cmethod)
6578                                 goto load_error;
6579                         fsig = mono_method_get_signature (cmethod, image, token);
6580
6581                         mono_save_token_info (cfg, image, token, cmethod);
6582
6583                         if (!mono_class_init (cmethod->klass))
6584                                 goto load_error;
6585
6586                         if (cfg->generic_sharing_context) {
6587                                 int context_used = mono_method_check_context_used (cmethod);
6588
6589                                 if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD)
6590                                         GENERIC_SHARING_FAILURE (CEE_NEWOBJ);
6591
6592                                 if (context_used)
6593                                         generic_shared = TRUE;
6594                         }
6595
6596                         if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
6597                                 if (check_linkdemand (cfg, method, cmethod, bblock, ip))
6598                                         INLINE_FAILURE;
6599                                 CHECK_CFG_EXCEPTION;
6600                         } else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
6601                                 ensure_method_is_allowed_to_call_method (cfg, method, cmethod, bblock, ip);
6602                         }
6603
6604                         n = fsig->param_count;
6605                         CHECK_STACK (n);
6606  
6607                         /* 
6608                          * Generate smaller code for the common newobj <exception> instruction in
6609                          * argument checking code.
6610                          */
6611                         if (bblock->out_of_line && cmethod->klass->image == mono_defaults.corlib && n <= 2 && 
6612                                 ((n < 1) || (!fsig->params [0]->byref && fsig->params [0]->type == MONO_TYPE_STRING)) && 
6613                                 ((n < 2) || (!fsig->params [1]->byref && fsig->params [1]->type == MONO_TYPE_STRING))) {
6614                                 MonoInst *iargs [3];
6615                                 int temp;
6616                                 
6617                                 sp -= n;
6618
6619                                 NEW_ICONST (cfg, iargs [0], cmethod->klass->type_token);
6620                                 switch (n) {
6621                                 case 0:
6622                                         temp = mono_emit_jit_icall (cfg, bblock, mono_create_corlib_exception_0, iargs, ip);
6623                                         break;
6624                                 case 1:
6625                                         iargs [1] = sp [0];
6626                                         temp = mono_emit_jit_icall (cfg, bblock, mono_create_corlib_exception_1, iargs, ip);
6627                                         break;
6628                                 case 2:
6629                                         iargs [1] = sp [0];
6630                                         iargs [2] = sp [1];
6631                                         temp = mono_emit_jit_icall (cfg, bblock, mono_create_corlib_exception_2, iargs, ip);
6632                                         break;
6633                                 default:
6634                                         g_assert_not_reached ();
6635                                 }
6636                                 NEW_TEMPLOAD (cfg, ins, temp);
6637                                 *sp ++ = ins;
6638
6639                                 ip += 5;
6640                                 inline_costs += 5;
6641                                 break;
6642                         }
6643
6644                         /* move the args to allow room for 'this' in the first position */
6645                         while (n--) {
6646                                 --sp;
6647                                 sp [1] = sp [0];
6648                         }
6649
6650                         handle_loaded_temps (cfg, bblock, stack_start, sp);
6651
6652                         if (mini_class_is_system_array (cmethod->klass)) {
6653                                 g_assert (!generic_shared);
6654
6655                                 NEW_METHODCONST (cfg, *sp, cmethod);
6656                                 temp = handle_array_new (cfg, bblock, fsig->param_count, sp, ip);
6657                         } else if (cmethod->string_ctor) {
6658                                 g_assert (!generic_shared);
6659
6660                                 /* we simply pass a null pointer */
6661                                 NEW_PCONST (cfg, *sp, NULL); 
6662                                 /* now call the string ctor */
6663                                 temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, NULL);
6664                         } else {
6665                                 MonoInst* callvirt_this_arg = NULL;
6666                                 
6667                                 if (cmethod->klass->valuetype) {
6668                                         iargs [0] = mono_compile_create_var (cfg, &cmethod->klass->byval_arg, OP_LOCAL);
6669                                         temp = iargs [0]->inst_c0;
6670
6671                                         NEW_TEMPLOADA (cfg, *sp, temp);
6672
6673                                         handle_initobj (cfg, bblock, *sp, NULL, cmethod->klass, stack_start, sp);
6674
6675                                         NEW_TEMPLOADA (cfg, *sp, temp);
6676
6677                                         /* 
6678                                          * The code generated by mini_emit_virtual_call () expects
6679                                          * iargs [0] to be a boxed instance, but luckily the vcall
6680                                          * will be transformed into a normal call there.
6681                                          */
6682                                 } else if (generic_shared) {
6683                                         MonoInst *this = NULL, *rgctx, *vtable;
6684
6685                                         GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD (*ip);
6686
6687                                         if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
6688                                                 NEW_ARGLOAD (cfg, this, 0);
6689                                         rgctx = get_runtime_generic_context (cfg, method, this, ip);
6690                                         vtable = get_runtime_generic_context_ptr (cfg, method, bblock, cmethod->klass,
6691                                                 token, MINI_TOKEN_SOURCE_METHOD, generic_context,
6692                                                 rgctx, MONO_RGCTX_INFO_VTABLE, ip);
6693
6694                                         temp = handle_alloc_from_inst (cfg, bblock, cmethod->klass, vtable, FALSE, ip);
6695                                         NEW_TEMPLOAD (cfg, *sp, temp);
6696                                 } else {
6697                                         MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
6698                                         if (mini_field_access_needs_cctor_run (cfg, method, vtable) && !(g_slist_find (class_inits, vtable))) {
6699                                                 guint8 *tramp = mono_create_class_init_trampoline (vtable);
6700                                                 mono_emit_native_call (cfg, bblock, tramp, 
6701                                                                                            helper_sig_class_init_trampoline,
6702                                                                                            NULL, ip, FALSE, FALSE);
6703                                                 if (cfg->verbose_level > 2)
6704                                                         g_print ("class %s.%s needs init call for ctor\n", cmethod->klass->name_space, cmethod->klass->name);
6705                                                 class_inits = g_slist_prepend (class_inits, vtable);
6706                                         }
6707                                         temp = handle_alloc (cfg, bblock, cmethod->klass, FALSE, ip);
6708                                         NEW_TEMPLOAD (cfg, *sp, temp);
6709                                 }
6710
6711                                 /* Avoid virtual calls to ctors if possible */
6712                                 if (cmethod->klass->marshalbyref)
6713                                         callvirt_this_arg = sp [0];
6714                                 
6715                                 if ((cfg->opt & MONO_OPT_INLINE) && cmethod && !generic_shared &&
6716                                     mono_method_check_inlining (cfg, cmethod) &&
6717                                     !mono_class_is_subclass_of (cmethod->klass, mono_defaults.exception_class, FALSE) &&
6718                                     !g_list_find (dont_inline, cmethod)) {
6719                                         int costs;
6720                                         MonoBasicBlock *ebblock;
6721                                         if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock, FALSE))) {
6722
6723                                                 ip += 5;
6724                                                 real_offset += 5;
6725                                                 
6726                                                 GET_BBLOCK (cfg, bblock, ip);
6727                                                 ebblock->next_bb = bblock;
6728                                                 link_bblock (cfg, ebblock, bblock);
6729
6730                                                 NEW_TEMPLOAD (cfg, *sp, temp);
6731                                                 sp++;
6732
6733                                                 /* indicates start of a new block, and triggers a load 
6734                                                    of all stack arguments at bb boundarie */
6735                                                 bblock = ebblock;
6736
6737                                                 inline_costs += costs;
6738                                                 break;
6739                                                 
6740                                         } else {
6741                                                 /* Prevent inlining of methods which call other methods */
6742                                                 INLINE_FAILURE;
6743                                                 mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, callvirt_this_arg);
6744                                         }
6745                                 } else if (generic_shared && cmethod->klass->valuetype) {
6746                                         MonoInst *this = NULL, *rgctx, *cmethod_addr;
6747
6748                                         g_assert (!callvirt_this_arg);
6749
6750                                         GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD (*ip);
6751
6752                                         if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
6753                                                 NEW_ARGLOAD (cfg, this, 0);
6754                                         rgctx = get_runtime_generic_context (cfg, method, this, ip);
6755                                         cmethod_addr = get_runtime_generic_context_method (cfg, method, bblock, cmethod,
6756                                                         generic_context, rgctx, MONO_RGCTX_INFO_GENERIC_METHOD_CODE, ip);
6757
6758                                         mono_emit_calli_spilled (cfg, bblock, fsig, sp, cmethod_addr, ip);
6759                                 } else {
6760                                         /* Prevent inlining of methods which call other methods */
6761                                         INLINE_FAILURE;
6762                                         /* now call the actual ctor */
6763                                         mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, callvirt_this_arg);
6764                                 }
6765                         }
6766
6767                         NEW_TEMPLOAD (cfg, *sp, temp);
6768                         sp++;
6769                         
6770                         ip += 5;
6771                         inline_costs += 5;
6772                         break;
6773                 }
6774                 case CEE_ISINST: {
6775                         gboolean shared_access = FALSE;
6776
6777                         CHECK_STACK (1);
6778                         --sp;
6779                         CHECK_OPSIZE (5);
6780                         token = read32 (ip + 1);
6781                         klass = mini_get_class (method, token, generic_context);
6782                         CHECK_TYPELOAD (klass);
6783                         if (sp [0]->type != STACK_OBJ)
6784                                 UNVERIFIED;
6785
6786                         if (cfg->generic_sharing_context) {
6787                                 int context_used = mono_class_check_context_used (klass);
6788
6789                                 if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD)
6790                                         GENERIC_SHARING_FAILURE (CEE_ISINST);
6791
6792                                 if (context_used)
6793                                         shared_access = TRUE;
6794                         }
6795
6796                         /* Needed by the code generated in inssel.brg */
6797                         if (!shared_access)
6798                                 mono_get_got_var (cfg);
6799
6800                         if (shared_access) {
6801                                 MonoInst *this = NULL, *rgctx;
6802                                 MonoInst *args [2];
6803                                 int temp;
6804
6805                                 GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD (*ip);
6806
6807                                 /* obj */
6808                                 args [0] = *sp;
6809
6810                                 /* klass */
6811                                 if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
6812                                         NEW_ARGLOAD (cfg, this, 0);
6813                                 rgctx = get_runtime_generic_context (cfg, method, this, ip);
6814                                 args [1] = get_runtime_generic_context_ptr (cfg, method, bblock, klass,
6815                                         token, MINI_TOKEN_SOURCE_CLASS, generic_context, rgctx, MONO_RGCTX_INFO_KLASS, ip);
6816
6817                                 temp = mono_emit_jit_icall (cfg, bblock, mono_object_isinst, args, ip);
6818                                 NEW_TEMPLOAD (cfg, *sp, temp);
6819
6820                                 sp++;
6821                                 ip += 5;
6822                                 inline_costs += 2;
6823                         } else if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
6824                         
6825                                 MonoMethod *mono_isinst;
6826                                 MonoInst *iargs [1];
6827                                 MonoBasicBlock *ebblock;
6828                                 int costs;
6829                                 int temp;
6830                                 
6831                                 mono_isinst = mono_marshal_get_isinst (klass); 
6832                                 iargs [0] = sp [0];
6833                                 
6834                                 costs = inline_method (cfg, mono_isinst, mono_method_signature (mono_isinst), bblock, 
6835                                                        iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
6836                         
6837                                 g_assert (costs > 0);
6838                                 
6839                                 ip += 5;
6840                                 real_offset += 5;
6841                         
6842                                 GET_BBLOCK (cfg, bblock, ip);
6843                                 ebblock->next_bb = bblock;
6844                                 link_bblock (cfg, ebblock, bblock);
6845
6846                                 temp = iargs [0]->inst_i0->inst_c0;
6847                                 NEW_TEMPLOAD (cfg, *sp, temp);
6848                                 
6849                                 sp++;
6850                                 bblock = ebblock;
6851                                 inline_costs += costs;
6852                         } else {
6853                                 MONO_INST_NEW (cfg, ins, *ip);
6854                                 ins->type = STACK_OBJ;
6855                                 ins->inst_left = *sp;
6856                                 ins->inst_newa_class = klass;
6857                                 ins->klass = klass;
6858                                 ins->cil_code = ip;
6859                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 5);
6860                                 ip += 5;
6861                         }
6862                         break;
6863                 }
6864                 case CEE_UNBOX_ANY: {
6865                         MonoInst *add, *vtoffset;
6866                         MonoInst *iargs [3];
6867                         guint32 align;
6868
6869                         CHECK_STACK (1);
6870                         --sp;
6871                         CHECK_OPSIZE (5);
6872                         token = read32 (ip + 1);
6873                         klass = mini_get_class (method, token, generic_context);
6874                         CHECK_TYPELOAD (klass);
6875
6876                         if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
6877                                 GENERIC_SHARING_FAILURE (CEE_UNBOX_ANY);
6878
6879                         if (generic_class_is_reference_type (cfg, klass)) {
6880                                 /* CASTCLASS */
6881                                 if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
6882                                         MonoMethod *mono_castclass;
6883                                         MonoInst *iargs [1];
6884                                         MonoBasicBlock *ebblock;
6885                                         int costs;
6886                                         int temp;
6887                                         
6888                                         mono_castclass = mono_marshal_get_castclass (klass); 
6889                                         iargs [0] = sp [0];
6890                                         
6891                                         costs = inline_method (cfg, mono_castclass, mono_method_signature (mono_castclass), bblock, 
6892                                                         iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
6893                                 
6894                                         g_assert (costs > 0);
6895                                         
6896                                         ip += 5;
6897                                         real_offset += 5;
6898                                 
6899                                         GET_BBLOCK (cfg, bblock, ip);
6900                                         ebblock->next_bb = bblock;
6901                                         link_bblock (cfg, ebblock, bblock);
6902         
6903                                         temp = iargs [0]->inst_i0->inst_c0;
6904                                         NEW_TEMPLOAD (cfg, *sp, temp);
6905                                         
6906                                         sp++;
6907                                         bblock = ebblock;
6908                                         inline_costs += costs;                          
6909                                 } else {
6910                                         /* Needed by the code generated in inssel.brg */
6911                                         mono_get_got_var (cfg);
6912                 
6913                                         MONO_INST_NEW (cfg, ins, CEE_CASTCLASS);
6914                                         ins->type = STACK_OBJ;
6915                                         ins->inst_left = *sp;
6916                                         ins->klass = klass;
6917                                         ins->inst_newa_class = klass;
6918                                         ins->cil_code = ip;
6919                                         *sp++ = ins;
6920                                         ip += 5;
6921                                 }
6922                                 break;
6923                         }
6924
6925                         if (mono_class_is_nullable (klass)) {
6926                                 int v = handle_unbox_nullable (cfg, bblock, *sp, ip, klass);
6927                                 NEW_TEMPLOAD (cfg, *sp, v);
6928                                 sp ++;
6929                                 ip += 5;
6930                                 break;
6931                         }
6932
6933                         /* Needed by the code generated in inssel.brg */
6934                         mono_get_got_var (cfg);
6935
6936                         MONO_INST_NEW (cfg, ins, OP_UNBOXCAST);
6937                         ins->type = STACK_OBJ;
6938                         ins->inst_left = *sp;
6939                         ins->klass = klass;
6940                         ins->inst_newa_class = klass;
6941                         ins->cil_code = ip;
6942
6943                         MONO_INST_NEW (cfg, add, OP_PADD);
6944                         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
6945                         add->inst_left = ins;
6946                         add->inst_right = vtoffset;
6947                         add->type = STACK_MP;
6948                         add->klass = mono_defaults.object_class;
6949                         *sp = add;
6950                         ip += 5;
6951                         /* LDOBJ impl */
6952                         n = mono_class_value_size (klass, &align);
6953                         ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
6954                         NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
6955                         if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
6956                                 MonoInst *copy;
6957                                 NEW_MEMCPY (cfg, copy, iargs [0], *sp, n, align);
6958                                 MONO_ADD_INS (bblock, copy);
6959                         } else {
6960                                 MonoMethod *memcpy_method = get_memcpy_method ();
6961                                 iargs [1] = *sp;
6962                                 NEW_ICONST (cfg, iargs [2], n);
6963                                 iargs [2]->cil_code = ip;
6964
6965                                 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
6966                         }
6967                         NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
6968                         ++sp;
6969                         inline_costs += 2;
6970                         break;
6971                 }
6972                 case CEE_UNBOX: {
6973                         MonoInst *add, *vtoffset;
6974
6975                         CHECK_STACK (1);
6976                         --sp;
6977                         CHECK_OPSIZE (5);
6978                         token = read32 (ip + 1);
6979                         klass = mini_get_class (method, token, generic_context);
6980                         CHECK_TYPELOAD (klass);
6981
6982                         if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
6983                                 GENERIC_SHARING_FAILURE (CEE_UNBOX);
6984
6985                         if (mono_class_is_nullable (klass)) {
6986                                 int v = handle_unbox_nullable (cfg, bblock, *sp, ip, klass);
6987                                 NEW_TEMPLOAD (cfg, *sp, v);
6988                                 sp ++;
6989                                 ip += 5;
6990                                 break;
6991                         }
6992
6993                         /* Needed by the code generated in inssel.brg */
6994                         mono_get_got_var (cfg);
6995
6996                         MONO_INST_NEW (cfg, ins, OP_UNBOXCAST);
6997                         ins->type = STACK_OBJ;
6998                         ins->inst_left = *sp;
6999                         ins->klass = klass;
7000                         ins->inst_newa_class = klass;
7001                         ins->cil_code = ip;
7002
7003                         MONO_INST_NEW (cfg, add, OP_PADD);
7004                         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
7005                         add->inst_left = ins;
7006                         add->inst_right = vtoffset;
7007                         add->type = STACK_MP;
7008                         add->klass = klass;
7009                         *sp++ = add;
7010                         ip += 5;
7011                         inline_costs += 2;
7012                         break;
7013                 }
7014                 case CEE_CASTCLASS:
7015                         CHECK_STACK (1);
7016                         --sp;
7017                         CHECK_OPSIZE (5);
7018                         token = read32 (ip + 1);
7019                         klass = mini_get_class (method, token, generic_context);
7020                         CHECK_TYPELOAD (klass);
7021                         if (sp [0]->type != STACK_OBJ)
7022                                 UNVERIFIED;
7023
7024                         if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
7025                                 GENERIC_SHARING_FAILURE (CEE_CASTCLASS);
7026
7027                         /* Needed by the code generated in inssel.brg */
7028                         mono_get_got_var (cfg);
7029                 
7030                         if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
7031                                 
7032                                 MonoMethod *mono_castclass;
7033                                 MonoInst *iargs [1];
7034                                 MonoBasicBlock *ebblock;
7035                                 int costs;
7036                                 int temp;
7037                                 
7038                                 mono_castclass = mono_marshal_get_castclass (klass); 
7039                                 iargs [0] = sp [0];
7040                                 
7041                                 costs = inline_method (cfg, mono_castclass, mono_method_signature (mono_castclass), bblock, 
7042                                                 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
7043                         
7044                                 g_assert (costs > 0);
7045                                 
7046                                 ip += 5;
7047                                 real_offset += 5;
7048                         
7049                                 GET_BBLOCK (cfg, bblock, ip);
7050                                 ebblock->next_bb = bblock;
7051                                 link_bblock (cfg, ebblock, bblock);
7052
7053                                 temp = iargs [0]->inst_i0->inst_c0;
7054                                 NEW_TEMPLOAD (cfg, *sp, temp);
7055                                 
7056                                 sp++;
7057                                 bblock = ebblock;
7058                                 inline_costs += costs;
7059                         } else {
7060                                 MONO_INST_NEW (cfg, ins, *ip);
7061                                 ins->type = STACK_OBJ;
7062                                 ins->inst_left = *sp;
7063                                 ins->klass = klass;
7064                                 ins->inst_newa_class = klass;
7065                                 ins->backend.record_cast_details = debug_options.better_cast_details;
7066                                 ins->cil_code = ip;
7067                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 5);
7068                                 ip += 5;
7069                         }
7070                         break;
7071                 case CEE_THROW:
7072                         CHECK_STACK (1);
7073                         MONO_INST_NEW (cfg, ins, OP_THROW);
7074                         --sp;
7075                         ins->inst_left = *sp;
7076                         ins->cil_code = ip++;
7077                         bblock->out_of_line = TRUE;
7078                         MONO_ADD_INS (bblock, ins);
7079                         MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
7080                         ins->cil_code = ip - 1;
7081                         MONO_ADD_INS (bblock, ins);
7082                         sp = stack_start;
7083                         
7084                         link_bblock (cfg, bblock, end_bblock);
7085                         start_new_bblock = 1;
7086                         break;
7087                 case CEE_LDFLD:
7088                 case CEE_LDFLDA:
7089                 case CEE_STFLD: {
7090                         MonoInst *offset_ins;
7091                         MonoClassField *field;
7092                         MonoBasicBlock *ebblock;
7093                         int costs;
7094                         guint foffset;
7095
7096                         if (*ip == CEE_STFLD) {
7097                                 CHECK_STACK (2);
7098                                 sp -= 2;
7099                         } else {
7100                                 CHECK_STACK (1);
7101                                 --sp;
7102                         }
7103                         if (sp [0]->type == STACK_I4 || sp [0]->type == STACK_I8 || sp [0]->type == STACK_R8)
7104                                 UNVERIFIED;
7105                         if (*ip != CEE_LDFLD && sp [0]->type == STACK_VTYPE)
7106                                 UNVERIFIED;
7107                         CHECK_OPSIZE (5);
7108                         token = read32 (ip + 1);
7109                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
7110                                 field = mono_method_get_wrapper_data (method, token);
7111                                 klass = field->parent;
7112                         } else {
7113                                 field = mono_field_from_token (image, token, &klass, generic_context);
7114                         }
7115                         if (!field)
7116                                 goto load_error;
7117                         mono_class_init (klass);
7118                         if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_field (method, field))
7119                                 FIELD_ACCESS_FAILURE;
7120
7121                         foffset = klass->valuetype? field->offset - sizeof (MonoObject): field->offset;
7122                         /* FIXME: mark instructions for use in SSA */
7123                         if (*ip == CEE_STFLD) {
7124                                 if (target_type_is_incompatible (cfg, field->type, sp [1]))
7125                                         UNVERIFIED;
7126                                 if ((klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) || klass->contextbound || klass == mono_defaults.marshalbyrefobject_class) {
7127                                         MonoMethod *stfld_wrapper = mono_marshal_get_stfld_wrapper (field->type); 
7128                                         MonoInst *iargs [5];
7129
7130                                         iargs [0] = sp [0];
7131                                         NEW_CLASSCONST (cfg, iargs [1], klass);
7132                                         NEW_FIELDCONST (cfg, iargs [2], field);
7133                                         NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : 
7134                                                     field->offset);
7135                                         iargs [4] = sp [1];
7136
7137                                         if (cfg->opt & MONO_OPT_INLINE) {
7138                                                 costs = inline_method (cfg, stfld_wrapper, mono_method_signature (stfld_wrapper), bblock, 
7139                                                                 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
7140                                                 g_assert (costs > 0);
7141                                                       
7142                                                 ip += 5;
7143                                                 real_offset += 5;
7144
7145                                                 GET_BBLOCK (cfg, bblock, ip);
7146                                                 ebblock->next_bb = bblock;
7147                                                 link_bblock (cfg, ebblock, bblock);
7148
7149                                                 /* indicates start of a new block, and triggers a load 
7150                                                    of all stack arguments at bb boundarie */
7151                                                 bblock = ebblock;
7152
7153                                                 inline_costs += costs;
7154                                                 break;
7155                                         } else {
7156                                                 mono_emit_method_call_spilled (cfg, bblock, stfld_wrapper, mono_method_signature (stfld_wrapper), iargs, ip, NULL);
7157                                         }
7158 #if HAVE_WRITE_BARRIERS
7159                                 } else if (mini_type_to_stind (cfg, field->type) == CEE_STIND_REF && !(sp [1]->opcode == OP_PCONST && sp [1]->inst_c0 == 0)) {
7160                                         /* insert call to write barrier */
7161                                         MonoMethod *write_barrier = mono_marshal_get_write_barrier ();
7162                                         MonoInst *iargs [2];
7163                                         NEW_ICONST (cfg, offset_ins, foffset);
7164                                         MONO_INST_NEW (cfg, ins, OP_PADD);
7165                                         ins->cil_code = ip;
7166                                         ins->inst_left = *sp;
7167                                         ins->inst_right = offset_ins;
7168                                         ins->type = STACK_MP;
7169                                         ins->klass = mono_defaults.object_class;
7170                                         iargs [0] = ins;
7171                                         iargs [1] = sp [1];
7172                                         mono_emit_method_call_spilled (cfg, bblock, write_barrier, mono_method_signature (write_barrier), iargs, ip, NULL);
7173 #endif
7174 #ifdef MONO_ARCH_SOFT_FLOAT
7175                                 } else if (mini_type_to_stind (cfg, field->type) == CEE_STIND_R4) {
7176                                         NEW_ICONST (cfg, offset_ins, foffset);
7177                                         MONO_INST_NEW (cfg, ins, OP_PADD);
7178                                         ins->cil_code = ip;
7179                                         ins->inst_left = *sp;
7180                                         ins->inst_right = offset_ins;
7181                                         ins->type = STACK_MP;
7182                                         ins->klass = mono_defaults.object_class;
7183                                         handle_store_float (cfg, bblock, ins, sp [1], ip);
7184 #endif
7185                                 } else {
7186                                         MonoInst *store;
7187                                         NEW_ICONST (cfg, offset_ins, foffset);
7188                                         MONO_INST_NEW (cfg, ins, OP_PADD);
7189                                         ins->cil_code = ip;
7190                                         ins->inst_left = *sp;
7191                                         ins->inst_right = offset_ins;
7192                                         ins->type = STACK_MP;
7193
7194                                         MONO_INST_NEW (cfg, store, mini_type_to_stind (cfg, field->type));
7195                                         store->cil_code = ip;
7196                                         store->inst_left = ins;
7197                                         store->inst_right = sp [1];
7198                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
7199                                         store->flags |= ins_flag;
7200                                         ins_flag = 0;
7201                                         if (store->opcode == CEE_STOBJ) {
7202                                                 handle_stobj (cfg, bblock, ins, sp [1], ip, 
7203                                                               mono_class_from_mono_type (field->type), FALSE, FALSE, TRUE);
7204                                         } else
7205                                                 MONO_ADD_INS (bblock, store);
7206                                 }
7207                         } else {
7208                                 if ((klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) || klass->contextbound || klass == mono_defaults.marshalbyrefobject_class) {
7209                                         MonoMethod *wrapper = (*ip == CEE_LDFLDA) ? mono_marshal_get_ldflda_wrapper (field->type) : mono_marshal_get_ldfld_wrapper (field->type); 
7210                                         MonoInst *iargs [4];
7211                                         int temp;
7212                                         
7213                                         iargs [0] = sp [0];
7214                                         NEW_CLASSCONST (cfg, iargs [1], klass);
7215                                         NEW_FIELDCONST (cfg, iargs [2], field);
7216                                         NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
7217                                         if ((cfg->opt & MONO_OPT_INLINE) && !MONO_TYPE_ISSTRUCT (mono_method_signature (wrapper)->ret)) {
7218                                                 costs = inline_method (cfg, wrapper, mono_method_signature (wrapper), bblock, 
7219                                                                 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
7220                                                 g_assert (costs > 0);
7221                                                       
7222                                                 ip += 5;
7223                                                 real_offset += 5;
7224
7225                                                 GET_BBLOCK (cfg, bblock, ip);
7226                                                 ebblock->next_bb = bblock;
7227                                                 link_bblock (cfg, ebblock, bblock);
7228
7229                                                 temp = iargs [0]->inst_i0->inst_c0;
7230
7231                                                 NEW_TEMPLOAD (cfg, *sp, temp);
7232                                                 sp++;
7233
7234                                                 /* indicates start of a new block, and triggers a load of
7235                                                    all stack arguments at bb boundarie */
7236                                                 bblock = ebblock;
7237                                                 
7238                                                 inline_costs += costs;
7239                                                 break;
7240                                         } else {
7241                                                 temp = mono_emit_method_call_spilled (cfg, bblock, wrapper, mono_method_signature (wrapper), iargs, ip, NULL);
7242                                                 NEW_TEMPLOAD (cfg, *sp, temp);
7243                                                 sp++;
7244                                         }
7245                                 } else {
7246                                         NEW_ICONST (cfg, offset_ins, foffset);
7247                                         MONO_INST_NEW (cfg, ins, OP_PADD);
7248                                         ins->cil_code = ip;
7249                                         ins->inst_left = *sp;
7250                                         ins->inst_right = offset_ins;
7251                                         ins->type = STACK_MP;
7252
7253                                         if (*ip == CEE_LDFLDA) {
7254                                                 ins->klass = mono_class_from_mono_type (field->type);
7255                                                 *sp++ = ins;
7256                                         } else {
7257                                                 MonoInst *load;
7258                                                 MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, field->type));
7259                                                 type_to_eval_stack_type (cfg, field->type, load);
7260                                                 load->cil_code = ip;
7261                                                 load->inst_left = ins;
7262                                                 load->flags |= ins_flag;
7263                                                 ins_flag = 0;
7264 #ifdef MONO_ARCH_SOFT_FLOAT
7265                                                 if (mini_type_to_ldind (cfg, field->type) == CEE_LDIND_R4) {
7266                                                         int temp;
7267                                                         temp = handle_load_float (cfg, bblock, ins, ip);
7268                                                         NEW_TEMPLOAD (cfg, *sp, temp);
7269                                                         sp++;
7270                                                 } else
7271 #endif
7272                                                 *sp++ = load;
7273                                         }
7274                                 }
7275                         }
7276                         ip += 5;
7277                         break;
7278                 }
7279                 case CEE_LDSFLD:
7280                 case CEE_LDSFLDA:
7281                 case CEE_STSFLD: {
7282                         MonoClassField *field;
7283                         gpointer addr = NULL;
7284                         gboolean shared_access = FALSE;
7285                         int relation = 0;
7286
7287                         CHECK_OPSIZE (5);
7288                         token = read32 (ip + 1);
7289                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
7290                                 field = mono_method_get_wrapper_data (method, token);
7291                                 klass = field->parent;
7292                         }
7293                         else
7294                                 field = mono_field_from_token (image, token, &klass, generic_context);
7295                         if (!field)
7296                                 goto load_error;
7297                         mono_class_init (klass);
7298                         if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_field (method, field))
7299                                 FIELD_ACCESS_FAILURE;
7300
7301                         /*
7302                          * We can only support shared generic static
7303                          * field access on architectures where the
7304                          * trampoline code has been extended to handle
7305                          * the generic class init.
7306                          */
7307 #ifndef MONO_ARCH_VTABLE_REG
7308                         GENERIC_SHARING_FAILURE (*ip);
7309 #endif
7310
7311                         if (cfg->generic_sharing_context) {
7312                                 int context_used = mono_class_check_context_used (klass);
7313
7314                                 if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD ||
7315                                                 klass->valuetype)
7316                                         GENERIC_SHARING_FAILURE (*ip);
7317
7318                                 if (context_used) {
7319                                         relation = mono_class_generic_class_relation (klass, MONO_RGCTX_INFO_VTABLE,
7320                                                 method->klass, generic_context, NULL);
7321                                         shared_access = TRUE;
7322                                 }
7323                         }
7324
7325                         g_assert (!(field->type->attrs & FIELD_ATTRIBUTE_LITERAL));
7326
7327                         if ((*ip) == CEE_STSFLD)
7328                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
7329
7330                         /* The special_static_fields field is init'd in mono_class_vtable, so it needs
7331                          * to be called here.
7332                          */
7333                         if (!(cfg->opt & MONO_OPT_SHARED))
7334                                 mono_class_vtable (cfg->domain, klass);
7335                         mono_domain_lock (cfg->domain);
7336                         if (cfg->domain->special_static_fields)
7337                                 addr = g_hash_table_lookup (cfg->domain->special_static_fields, field);
7338                         mono_domain_unlock (cfg->domain);
7339
7340                         if (shared_access) {
7341                                 MonoInst *this, *rgctx, *static_data;
7342
7343                                 GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD (*ip);
7344
7345                                 /*
7346                                 g_print ("sharing static field access in %s.%s.%s - depth %d offset %d\n",
7347                                         method->klass->name_space, method->klass->name, method->name,
7348                                         depth, field->offset);
7349                                 */
7350
7351                                 if (mono_class_needs_cctor_run (klass, method)) {
7352                                         MonoMethodSignature *sig = helper_sig_generic_class_init_trampoline;
7353                                         MonoCallInst *call;
7354                                         MonoInst *vtable, *rgctx;
7355
7356                                         if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
7357                                                 NEW_ARGLOAD (cfg, this, 0);
7358                                         else
7359                                                 this = NULL;
7360
7361                                         rgctx = get_runtime_generic_context (cfg, method, this, ip);
7362                                         vtable = get_runtime_generic_context_ptr (cfg, method, bblock, klass,
7363                                                         token, MINI_TOKEN_SOURCE_FIELD, generic_context,
7364                                                         rgctx, MONO_RGCTX_INFO_VTABLE, ip);
7365
7366                                         call = mono_emit_call_args (cfg, bblock, sig, NULL, FALSE, FALSE, ip, FALSE);
7367                                         call->inst.opcode = OP_TRAMPCALL_VTABLE;
7368                                         call->fptr = mono_get_trampoline_code (MONO_TRAMPOLINE_GENERIC_CLASS_INIT);
7369
7370                                         call->inst.inst_left = vtable;
7371
7372                                         mono_spill_call (cfg, bblock, call, sig, FALSE, ip, FALSE);
7373                                 }
7374
7375                                 /*
7376                                  * The pointer we're computing here is
7377                                  *
7378                                  *   super_info.static_data + field->offset
7379                                  */
7380
7381                                 if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
7382                                         NEW_ARGLOAD (cfg, this, 0);
7383                                 else
7384                                         this = NULL;
7385                                 rgctx = get_runtime_generic_context (cfg, method, this, ip);
7386                                 static_data = get_runtime_generic_context_ptr (cfg, method, bblock, klass,
7387                                         token, MINI_TOKEN_SOURCE_FIELD, generic_context,
7388                                         rgctx, MONO_RGCTX_INFO_STATIC_DATA, ip);
7389
7390                                 if (field->offset == 0) {
7391                                         ins = static_data;
7392                                 } else {
7393                                         MonoInst *field_offset;
7394
7395                                         NEW_ICONST (cfg, field_offset, field->offset);
7396
7397                                         MONO_INST_NEW (cfg, ins, OP_PADD);
7398                                         ins->cil_code = ip;
7399                                         ins->inst_left = static_data;
7400                                         ins->inst_right = field_offset;
7401                                         ins->type = STACK_PTR;
7402                                         ins->klass = klass;
7403                                 }
7404                         } else if ((cfg->opt & MONO_OPT_SHARED) || (cfg->compile_aot && addr)) {
7405                                 int temp;
7406                                 MonoInst *iargs [2];
7407                                 MonoInst *domain_var;
7408                                 
7409                                 g_assert (field->parent);
7410                                 /* avoid depending on undefined C behavior in sequence points */
7411                                 domain_var = mono_get_domainvar (cfg);
7412                                 NEW_TEMPLOAD (cfg, iargs [0], domain_var->inst_c0);
7413                                 NEW_FIELDCONST (cfg, iargs [1], field);
7414                                 temp = mono_emit_jit_icall (cfg, bblock, mono_class_static_field_address, iargs, ip);
7415                                 NEW_TEMPLOAD (cfg, ins, temp);
7416                         } else {
7417                                 MonoVTable *vtable;
7418                                 vtable = mono_class_vtable (cfg->domain, klass);
7419                                 if (!addr) {
7420                                         if (mini_field_access_needs_cctor_run (cfg, method, vtable) && !(g_slist_find (class_inits, vtable))) {
7421                                                 guint8 *tramp = mono_create_class_init_trampoline (vtable);
7422                                                 mono_emit_native_call (cfg, bblock, tramp, 
7423                                                                                            helper_sig_class_init_trampoline,
7424                                                                                            NULL, ip, FALSE, FALSE);
7425                                                 if (cfg->verbose_level > 2)
7426                                                         g_print ("class %s.%s needs init call for %s\n", klass->name_space, klass->name, field->name);
7427                                                 class_inits = g_slist_prepend (class_inits, vtable);
7428                                         } else {
7429                                                 if (cfg->run_cctors) {
7430                                                         /* This makes so that inline cannot trigger */
7431                                                         /* .cctors: too many apps depend on them */
7432                                                         /* running with a specific order... */
7433                                                         if (! vtable->initialized)
7434                                                                 INLINE_FAILURE;
7435                                                         mono_runtime_class_init (vtable);
7436                                                 }
7437                                         }
7438                                         addr = (char*)vtable->data + field->offset;
7439
7440                                         if (cfg->compile_aot)
7441                                                 NEW_SFLDACONST (cfg, ins, field);
7442                                         else
7443                                                 NEW_PCONST (cfg, ins, addr);
7444                                         ins->cil_code = ip;
7445                                 } else {
7446                                         /* 
7447                                          * insert call to mono_threads_get_static_data (GPOINTER_TO_UINT (addr)) 
7448                                          * This could be later optimized to do just a couple of
7449                                          * memory dereferences with constant offsets.
7450                                          */
7451                                         int temp;
7452                                         MonoInst *iargs [1];
7453                                         NEW_ICONST (cfg, iargs [0], GPOINTER_TO_UINT (addr));
7454                                         temp = mono_emit_jit_icall (cfg, bblock, mono_get_special_static_data, iargs, ip);
7455                                         NEW_TEMPLOAD (cfg, ins, temp);
7456                                 }
7457                         }
7458
7459                         /* FIXME: mark instructions for use in SSA */
7460                         if (*ip == CEE_LDSFLDA) {
7461                                 ins->klass = mono_class_from_mono_type (field->type);
7462                                 *sp++ = ins;
7463                         } else if (*ip == CEE_STSFLD) {
7464                                 MonoInst *store;
7465                                 CHECK_STACK (1);
7466                                 sp--;
7467                                 MONO_INST_NEW (cfg, store, mini_type_to_stind (cfg, field->type));
7468                                 store->cil_code = ip;
7469                                 store->inst_left = ins;
7470                                 store->inst_right = sp [0];
7471                                 store->flags |= ins_flag;
7472                                 ins_flag = 0;
7473
7474 #ifdef MONO_ARCH_SOFT_FLOAT
7475                                 if (store->opcode == CEE_STIND_R4)
7476                                         handle_store_float (cfg, bblock, ins, sp [0], ip);
7477                                 else
7478 #endif
7479                                 if (store->opcode == CEE_STOBJ) {
7480                                         handle_stobj (cfg, bblock, ins, sp [0], ip, mono_class_from_mono_type (field->type), FALSE, FALSE, FALSE);
7481                                 } else
7482                                         MONO_ADD_INS (bblock, store);
7483                         } else {
7484                                 gboolean is_const = FALSE;
7485                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
7486                                 if (!shared_access && !((cfg->opt & MONO_OPT_SHARED) || cfg->compile_aot) && 
7487                                     vtable->initialized && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY)) {
7488                                         gpointer addr = (char*)vtable->data + field->offset;
7489                                         int ro_type = field->type->type;
7490                                         if (ro_type == MONO_TYPE_VALUETYPE && field->type->data.klass->enumtype) {
7491                                                 ro_type = field->type->data.klass->enum_basetype->type;
7492                                         }
7493                                         /* g_print ("RO-FIELD %s.%s:%s\n", klass->name_space, klass->name, field->name);*/
7494                                         is_const = TRUE;
7495                                         switch (ro_type) {
7496                                         case MONO_TYPE_BOOLEAN:
7497                                         case MONO_TYPE_U1:
7498                                                 NEW_ICONST (cfg, *sp, *((guint8 *)addr));
7499                                                 sp++;
7500                                                 break;
7501                                         case MONO_TYPE_I1:
7502                                                 NEW_ICONST (cfg, *sp, *((gint8 *)addr));
7503                                                 sp++;
7504                                                 break;                                          
7505                                         case MONO_TYPE_CHAR:
7506                                         case MONO_TYPE_U2:
7507                                                 NEW_ICONST (cfg, *sp, *((guint16 *)addr));
7508                                                 sp++;
7509                                                 break;
7510                                         case MONO_TYPE_I2:
7511                                                 NEW_ICONST (cfg, *sp, *((gint16 *)addr));
7512                                                 sp++;
7513                                                 break;
7514                                                 break;
7515                                         case MONO_TYPE_I4:
7516                                                 NEW_ICONST (cfg, *sp, *((gint32 *)addr));
7517                                                 sp++;
7518                                                 break;                                          
7519                                         case MONO_TYPE_U4:
7520                                                 NEW_ICONST (cfg, *sp, *((guint32 *)addr));
7521                                                 sp++;
7522                                                 break;
7523 #ifndef HAVE_MOVING_COLLECTOR
7524                                         case MONO_TYPE_I:
7525                                         case MONO_TYPE_U:
7526                                         case MONO_TYPE_STRING:
7527                                         case MONO_TYPE_OBJECT:
7528                                         case MONO_TYPE_CLASS:
7529                                         case MONO_TYPE_SZARRAY:
7530                                         case MONO_TYPE_PTR:
7531                                         case MONO_TYPE_FNPTR:
7532                                         case MONO_TYPE_ARRAY:
7533                                                 NEW_PCONST (cfg, *sp, *((gpointer *)addr));
7534                                                 type_to_eval_stack_type (cfg, field->type, *sp);
7535                                                 sp++;
7536                                                 break;
7537 #endif
7538                                         case MONO_TYPE_I8:
7539                                         case MONO_TYPE_U8:
7540                                                 MONO_INST_NEW (cfg, *sp, OP_I8CONST);
7541                                                 sp [0]->type = STACK_I8;
7542                                                 sp [0]->inst_l = *((gint64 *)addr);
7543                                                 sp++;
7544                                                 break;
7545                                         case MONO_TYPE_R4:
7546                                         case MONO_TYPE_R8:
7547                                         case MONO_TYPE_VALUETYPE:
7548                                         default:
7549                                                 is_const = FALSE;
7550                                                 break;
7551                                         }
7552                                 }
7553
7554                                 if (!is_const) {
7555                                         MonoInst *load;
7556                                         CHECK_STACK_OVF (1);
7557                                         MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, field->type));
7558                                         type_to_eval_stack_type (cfg, field->type, load);
7559                                         load->cil_code = ip;
7560                                         load->inst_left = ins;
7561                                         load->flags |= ins_flag;
7562 #ifdef MONO_ARCH_SOFT_FLOAT
7563                                         if (load->opcode == CEE_LDIND_R4) {
7564                                                 int temp;
7565                                                 temp = handle_load_float (cfg, bblock, ins, ip);
7566                                                 NEW_TEMPLOAD (cfg, load, temp);
7567                                         }
7568 #endif
7569                                         *sp++ = load;
7570                                         ins_flag = 0;
7571                                 }
7572                         }
7573                         ip += 5;
7574                         break;
7575                 }
7576                 case CEE_STOBJ:
7577                         CHECK_STACK (2);
7578                         sp -= 2;
7579                         CHECK_OPSIZE (5);
7580                         token = read32 (ip + 1);
7581                         klass = mini_get_class (method, token, generic_context);
7582                         CHECK_TYPELOAD (klass);
7583                         n = mini_type_to_stind (cfg, &klass->byval_arg);
7584                         /* FIXME: handle CEE_STIND_R4 */
7585                         if (n == CEE_STOBJ) {
7586                                 handle_stobj (cfg, bblock, sp [0], sp [1], ip, klass, FALSE, FALSE, TRUE);
7587                         } else {
7588                                 /* FIXME: should check item at sp [1] is compatible with the type of the store. */
7589                                 MonoInst *store;
7590                                 MONO_INST_NEW (cfg, store, n);
7591                                 store->cil_code = ip;
7592                                 store->inst_left = sp [0];
7593                                 store->inst_right = sp [1];
7594                                 store->flags |= ins_flag;
7595                                 MONO_ADD_INS (bblock, store);
7596                         }
7597                         ins_flag = 0;
7598                         ip += 5;
7599                         inline_costs += 1;
7600                         break;
7601                 case CEE_BOX: {
7602                         MonoInst *val;
7603                         gboolean generic_shared = FALSE;
7604
7605                         CHECK_STACK (1);
7606                         --sp;
7607                         val = *sp;
7608                         CHECK_OPSIZE (5);
7609                         token = read32 (ip + 1);
7610                         klass = mini_get_class (method, token, generic_context);
7611                         CHECK_TYPELOAD (klass);
7612
7613                         if (cfg->generic_sharing_context && mono_class_check_context_used (klass)) {
7614                                 if (mono_class_is_nullable (klass))
7615                                         GENERIC_SHARING_FAILURE (CEE_BOX);
7616                                 else
7617                                         generic_shared = TRUE;
7618                         }
7619
7620                         if (generic_class_is_reference_type (cfg, klass)) {
7621                                 *sp++ = val;
7622                                 ip += 5;
7623                                 break;
7624                         }
7625                         if (klass == mono_defaults.void_class)
7626                                 UNVERIFIED;
7627                         if (target_type_is_incompatible (cfg, &klass->byval_arg, *sp))
7628                                 UNVERIFIED;
7629                         /* frequent check in generic code: box (struct), brtrue */
7630                         if (!mono_class_is_nullable (klass) &&
7631                             ip + 5 < end && ip_in_bb (cfg, bblock, ip + 5) && (ip [5] == CEE_BRTRUE || ip [5] == CEE_BRTRUE_S)) {
7632                                 /*g_print ("box-brtrue opt at 0x%04x in %s\n", real_offset, method->name);*/
7633                                 MONO_INST_NEW (cfg, ins, CEE_POP);
7634                                 MONO_ADD_INS (bblock, ins);
7635                                 ins->cil_code = ip;
7636                                 ins->inst_i0 = *sp;
7637                                 ip += 5;
7638                                 MONO_INST_NEW (cfg, ins, OP_BR);
7639                                 ins->cil_code = ip;
7640                                 MONO_ADD_INS (bblock, ins);
7641                                 if (*ip == CEE_BRTRUE_S) {
7642                                         CHECK_OPSIZE (2);
7643                                         ip++;
7644                                         target = ip + 1 + (signed char)(*ip);
7645                                         ip++;
7646                                 } else {
7647                                         CHECK_OPSIZE (5);
7648                                         ip++;
7649                                         target = ip + 4 + (gint)(read32 (ip));
7650                                         ip += 4;
7651                                 }
7652                                 GET_BBLOCK (cfg, tblock, target);
7653                                 link_bblock (cfg, bblock, tblock);
7654                                 CHECK_BBLOCK (target, ip, tblock);
7655                                 ins->inst_target_bb = tblock;
7656                                 GET_BBLOCK (cfg, tblock, ip);
7657                                 link_bblock (cfg, bblock, tblock);
7658                                 if (sp != stack_start) {
7659                                         handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
7660                                         sp = stack_start;
7661                                         CHECK_UNVERIFIABLE (cfg);
7662                                 }
7663                                 start_new_bblock = 1;
7664                                 break;
7665                         }
7666                         if (generic_shared) {
7667                                 MonoInst *this = NULL, *rgctx, *vtable;
7668
7669                                 GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD (*ip);
7670
7671                                 if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
7672                                         NEW_ARGLOAD (cfg, this, 0);
7673                                 rgctx = get_runtime_generic_context (cfg, method, this, ip);
7674                                 vtable = get_runtime_generic_context_ptr (cfg, method, bblock, klass,
7675                                         token, MINI_TOKEN_SOURCE_CLASS, generic_context,
7676                                         rgctx, MONO_RGCTX_INFO_VTABLE, ip);
7677
7678                                 *sp++ = handle_box_from_inst (cfg, bblock, val, ip, klass, vtable);
7679                         } else {
7680                                 *sp++ = handle_box (cfg, bblock, val, ip, klass);
7681                         }
7682                         ip += 5;
7683                         inline_costs += 1;
7684                         break;
7685                 }
7686                 case CEE_NEWARR: {
7687                         gboolean shared_access = FALSE;
7688
7689                         CHECK_STACK (1);
7690                         --sp;
7691
7692                         CHECK_OPSIZE (5);
7693                         token = read32 (ip + 1);
7694
7695                         /* allocate the domainvar - becaus this is used in decompose_foreach */
7696                         if (cfg->opt & MONO_OPT_SHARED) {
7697                                 mono_get_domainvar (cfg);
7698                                 /* LAME-IR: Mark it as used since otherwise it will be optimized away */
7699                                 cfg->domainvar->flags |= MONO_INST_VOLATILE;
7700                         }
7701
7702                         /* Ditto */
7703                         mono_get_got_var (cfg);
7704
7705                         klass = mini_get_class (method, token, generic_context);
7706                         CHECK_TYPELOAD (klass);
7707
7708                         if (cfg->generic_sharing_context) {
7709                                 int context_used = mono_class_check_context_used (klass);
7710
7711                                 if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD || klass->valuetype)
7712                                         GENERIC_SHARING_FAILURE (CEE_NEWARR);
7713
7714                                 if (context_used)
7715                                         shared_access = TRUE;
7716                         }
7717
7718                         if (shared_access) {
7719                                 MonoInst *this = NULL, *rgctx;
7720                                 MonoInst *args [3];
7721                                 int temp;
7722
7723                                 GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD (*ip);
7724
7725                                 /* domain */
7726                                 NEW_DOMAINCONST (cfg, args [0]);
7727
7728                                 /* klass */
7729                                 if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
7730                                         NEW_ARGLOAD (cfg, this, 0);
7731                                 rgctx = get_runtime_generic_context (cfg, method, this, ip);
7732                                 args [1] = get_runtime_generic_context_ptr (cfg, method, bblock, klass,
7733                                         token, MINI_TOKEN_SOURCE_CLASS, generic_context, rgctx, MONO_RGCTX_INFO_KLASS, ip);
7734
7735                                 /* array len */
7736                                 args [2] = *sp;
7737
7738                                 temp = mono_emit_jit_icall (cfg, bblock, mono_array_new, args, ip);
7739                                 NEW_TEMPLOAD (cfg, ins, temp);
7740                         } else {
7741                                 MONO_INST_NEW (cfg, ins, *ip);
7742                                 ins->cil_code = ip;
7743                                 ins->inst_newa_class = klass;
7744                                 ins->inst_newa_len = *sp;
7745                                 ins->type = STACK_OBJ;
7746                                 ins->klass = mono_array_class_get (klass, 1);
7747                         }
7748
7749                         ip += 5;
7750                         *sp++ = ins;
7751                         /* 
7752                          * we store the object so calls to create the array are not interleaved
7753                          * with the arguments of other calls.
7754                          */
7755                         if (1) {
7756                                 MonoInst *store, *temp, *load;
7757                                 const char *data_ptr;
7758                                 int data_size = 0;
7759                                 --sp;
7760                                 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
7761                                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
7762                                 store->cil_code = ins->cil_code;
7763                                 MONO_ADD_INS (bblock, store);
7764                                 /* 
7765                                  * we inline/optimize the initialization sequence if possible.
7766                                  * we should also allocate the array as not cleared, since we spend as much time clearing to 0 as initializing
7767                                  * for small sizes open code the memcpy
7768                                  * ensure the rva field is big enough
7769                                  */
7770                                 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))) {
7771                                         MonoMethod *memcpy_method = get_memcpy_method ();
7772                                         MonoInst *data_offset, *add;
7773                                         MonoInst *iargs [3];
7774                                         NEW_ICONST (cfg, iargs [2], data_size);
7775                                         NEW_TEMPLOAD (cfg, load, temp->inst_c0);
7776                                         load->cil_code = ins->cil_code;
7777                                         NEW_ICONST (cfg, data_offset, G_STRUCT_OFFSET (MonoArray, vector));
7778                                         MONO_INST_NEW (cfg, add, OP_PADD);
7779                                         add->inst_left = load;
7780                                         add->inst_right = data_offset;
7781                                         add->cil_code = ip;
7782                                         iargs [0] = add;
7783                                         if (cfg->compile_aot) {
7784                                                 NEW_AOTCONST_TOKEN (cfg, iargs [1], MONO_PATCH_INFO_RVA, method->klass->image, GPOINTER_TO_UINT(data_ptr), STACK_PTR, NULL);
7785                                         } else {
7786                                                 NEW_PCONST (cfg, iargs [1], (char*)data_ptr);
7787                                         }
7788                                         mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
7789                                         ip += 11;
7790                                 }
7791                                 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
7792                                 load->cil_code = ins->cil_code;
7793                                 *sp++ = load;
7794                         }
7795                         inline_costs += 1;
7796                         break;
7797                 }
7798                 case CEE_LDLEN:
7799                         CHECK_STACK (1);
7800                         --sp;
7801                         if (sp [0]->type != STACK_OBJ)
7802                                 UNVERIFIED;
7803                         MONO_INST_NEW (cfg, ins, *ip);
7804                         ins->cil_code = ip++;
7805                         ins->inst_left = *sp;
7806                         ins->type = STACK_PTR;
7807                         *sp++ = ins;
7808                         break;
7809                 case CEE_LDELEMA:
7810                         CHECK_STACK (2);
7811                         sp -= 2;
7812                         CHECK_OPSIZE (5);
7813                         if (sp [0]->type != STACK_OBJ)
7814                                 UNVERIFIED;
7815
7816                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
7817                         CHECK_TYPELOAD (klass);
7818                         /* we need to make sure that this array is exactly the type it needs
7819                          * to be for correctness. the wrappers are lax with their usage
7820                          * so we need to ignore them here
7821                          */
7822                         if (!klass->valuetype && method->wrapper_type == MONO_WRAPPER_NONE && !readonly) {
7823                                 MonoInst* check;
7824
7825                                 /* Needed by the code generated in inssel.brg */
7826                                 mono_get_got_var (cfg);
7827
7828                                 MONO_INST_NEW (cfg, check, OP_CHECK_ARRAY_TYPE);
7829                                 check->cil_code = ip;
7830                                 check->klass = mono_array_class_get (klass, 1);
7831                                 check->inst_left = sp [0];
7832                                 check->type = STACK_OBJ;
7833                                 sp [0] = check;
7834                         }
7835                         
7836                         readonly = FALSE;
7837                         mono_class_init (klass);
7838                         NEW_LDELEMA (cfg, ins, sp, klass);
7839                         ins->cil_code = ip;
7840                         *sp++ = ins;
7841                         ip += 5;
7842                         break;
7843                 case CEE_LDELEM_ANY: {
7844                         MonoInst *load;
7845                         CHECK_STACK (2);
7846                         sp -= 2;
7847                         if (sp [0]->type != STACK_OBJ)
7848                                 UNVERIFIED;
7849                         CHECK_OPSIZE (5);
7850                         token = read32 (ip + 1);
7851                         klass = mini_get_class (method, token, generic_context);
7852                         CHECK_TYPELOAD (klass);
7853                         mono_class_init (klass);
7854                         NEW_LDELEMA (cfg, load, sp, klass);
7855                         load->cil_code = ip;
7856                         MONO_INST_NEW (cfg, ins, mini_type_to_ldind (cfg, &klass->byval_arg));
7857                         ins->cil_code = ip;
7858                         ins->inst_left = load;
7859                         *sp++ = ins;
7860                         type_to_eval_stack_type (cfg, &klass->byval_arg, ins);
7861                         ip += 5;
7862                         break;
7863                 }
7864                 case CEE_LDELEM_I1:
7865                 case CEE_LDELEM_U1:
7866                 case CEE_LDELEM_I2:
7867                 case CEE_LDELEM_U2:
7868                 case CEE_LDELEM_I4:
7869                 case CEE_LDELEM_U4:
7870                 case CEE_LDELEM_I8:
7871                 case CEE_LDELEM_I:
7872                 case CEE_LDELEM_R4:
7873                 case CEE_LDELEM_R8:
7874                 case CEE_LDELEM_REF: {
7875                         MonoInst *load;
7876                         /*
7877                          * translate to:
7878                          * ldind.x (ldelema (array, index))
7879                          * ldelema does the bounds check
7880                          */
7881                         CHECK_STACK (2);
7882                         sp -= 2;
7883                         if (sp [0]->type != STACK_OBJ)
7884                                 UNVERIFIED;
7885                         klass = array_access_to_klass (*ip, sp [0]);
7886                         NEW_LDELEMA (cfg, load, sp, klass);
7887                         load->cil_code = ip;
7888 #ifdef MONO_ARCH_SOFT_FLOAT
7889                         if (*ip == CEE_LDELEM_R4) {
7890                                 int temp;
7891                                 temp = handle_load_float (cfg, bblock, load, ip);
7892                                 NEW_TEMPLOAD (cfg, *sp, temp);
7893                                 sp++;
7894                                 ++ip;
7895                                 break;
7896                         }
7897 #endif
7898                         MONO_INST_NEW (cfg, ins, ldelem_to_ldind [*ip - CEE_LDELEM_I1]);
7899                         ins->cil_code = ip;
7900                         ins->inst_left = load;
7901                         *sp++ = ins;
7902                         ins->type = ldind_type [ins->opcode - CEE_LDIND_I1];
7903                         ins->klass = klass;
7904                         ++ip;
7905                         break;
7906                 }
7907                 case CEE_STELEM_I:
7908                 case CEE_STELEM_I1:
7909                 case CEE_STELEM_I2:
7910                 case CEE_STELEM_I4:
7911                 case CEE_STELEM_I8:
7912                 case CEE_STELEM_R4:
7913                 case CEE_STELEM_R8: {
7914                         MonoInst *load;
7915                         /*
7916                          * translate to:
7917                          * stind.x (ldelema (array, index), val)
7918                          * ldelema does the bounds check
7919                          */
7920                         CHECK_STACK (3);
7921                         sp -= 3;
7922                         if (sp [0]->type != STACK_OBJ)
7923                                 UNVERIFIED;
7924                         klass = array_access_to_klass (*ip, sp [0]);
7925                         NEW_LDELEMA (cfg, load, sp, klass);
7926                         load->cil_code = ip;
7927 #ifdef MONO_ARCH_SOFT_FLOAT
7928                         if (*ip == CEE_STELEM_R4) {
7929                                 handle_store_float (cfg, bblock, load, sp [2], ip);
7930                                 ip++;
7931                                 break;
7932                         }
7933 #endif
7934                         MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
7935                         ins->cil_code = ip;
7936                         ins->inst_left = load;
7937                         ins->inst_right = sp [2];
7938                         ++ip;
7939                         handle_loaded_temps (cfg, bblock, stack_start, sp);
7940                         MONO_ADD_INS (bblock, ins);
7941                         inline_costs += 1;
7942                         break;
7943                 }
7944                 case CEE_STELEM_ANY: {
7945                         MonoInst *load;
7946                         /*
7947                          * translate to:
7948                          * stind.x (ldelema (array, index), val)
7949                          * ldelema does the bounds check
7950                          */
7951                         CHECK_STACK (3);
7952                         sp -= 3;
7953                         if (sp [0]->type != STACK_OBJ)
7954                                 UNVERIFIED;
7955                         CHECK_OPSIZE (5);
7956                         token = read32 (ip + 1);
7957                         klass = mini_get_class (method, token, generic_context);
7958                         CHECK_TYPELOAD (klass);
7959                         mono_class_init (klass);
7960                         if (generic_class_is_reference_type (cfg, klass)) {
7961                                 /* storing a NULL doesn't need any of the complex checks in stelemref */
7962                                 if (sp [2]->opcode == OP_PCONST && sp [2]->inst_p0 == NULL) {
7963                                         MonoInst *load;
7964                                         NEW_LDELEMA (cfg, load, sp, mono_defaults.object_class);
7965                                         load->cil_code = ip;
7966                                         MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
7967                                         ins->cil_code = ip;
7968                                         ins->inst_left = load;
7969                                         ins->inst_right = sp [2];
7970                                         MONO_ADD_INS (bblock, ins);
7971                                 } else {
7972                                         MonoMethod* helper = mono_marshal_get_stelemref ();
7973                                         MonoInst *iargs [3];
7974                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
7975
7976                                         iargs [2] = sp [2];
7977                                         iargs [1] = sp [1];
7978                                         iargs [0] = sp [0];
7979
7980                                         mono_emit_method_call_spilled (cfg, bblock, helper, mono_method_signature (helper), iargs, ip, NULL);
7981                                 }
7982                         } else {
7983                                 NEW_LDELEMA (cfg, load, sp, klass);
7984                                 load->cil_code = ip;
7985
7986                                 n = mini_type_to_stind (cfg, &klass->byval_arg);
7987                                 /* FIXME: CEE_STIND_R4 */
7988                                 if (n == CEE_STOBJ)
7989                                         handle_stobj (cfg, bblock, load, sp [2], ip, klass, FALSE, FALSE, TRUE);
7990                                 else {
7991                                         MONO_INST_NEW (cfg, ins, n);
7992                                         ins->cil_code = ip;
7993                                         ins->inst_left = load;
7994                                         ins->inst_right = sp [2];
7995                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
7996                                         MONO_ADD_INS (bblock, ins);
7997                                 }
7998                         }
7999                         ip += 5;
8000                         inline_costs += 1;
8001                         break;
8002                 }
8003                 case CEE_STELEM_REF: {
8004                         MonoInst *iargs [3];
8005                         MonoMethod* helper = mono_marshal_get_stelemref ();
8006
8007                         CHECK_STACK (3);
8008                         sp -= 3;
8009                         if (sp [0]->type != STACK_OBJ)
8010                                 UNVERIFIED;
8011                         if (sp [2]->type != STACK_OBJ)
8012                                 UNVERIFIED;
8013
8014                         handle_loaded_temps (cfg, bblock, stack_start, sp);
8015
8016                         /* storing a NULL doesn't need any of the complex checks in stelemref */
8017                         if (sp [2]->opcode == OP_PCONST && sp [2]->inst_p0 == NULL) {
8018                                 MonoInst *load;
8019                                 NEW_LDELEMA (cfg, load, sp, mono_defaults.object_class);
8020                                 load->cil_code = ip;
8021                                 MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
8022                                 ins->cil_code = ip;
8023                                 ins->inst_left = load;
8024                                 ins->inst_right = sp [2];
8025                                 MONO_ADD_INS (bblock, ins);
8026                         } else {
8027                                 iargs [2] = sp [2];
8028                                 iargs [1] = sp [1];
8029                                 iargs [0] = sp [0];
8030                         
8031                                 mono_emit_method_call_spilled (cfg, bblock, helper, mono_method_signature (helper), iargs, ip, NULL);
8032                                 inline_costs += 1;
8033                         }
8034
8035                         ++ip;
8036                         break;
8037                 }
8038                 case CEE_CKFINITE: {
8039                         MonoInst *store, *temp;
8040                         CHECK_STACK (1);
8041
8042                         /* this instr. can throw exceptions as side effect,
8043                          * so we cant eliminate dead code which contains CKFINITE opdodes.
8044                          * Spilling to memory makes sure that we always perform
8045                          * this check */
8046
8047                         
8048                         MONO_INST_NEW (cfg, ins, OP_CKFINITE);
8049                         ins->cil_code = ip;
8050                         ins->inst_left = sp [-1];
8051                         temp = mono_compile_create_var (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL);
8052
8053                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
8054                         store->cil_code = ip;
8055                         MONO_ADD_INS (bblock, store);
8056
8057                         NEW_TEMPLOAD (cfg, sp [-1], temp->inst_c0);
8058                        
8059                         ++ip;
8060                         break;
8061                 }
8062                 case CEE_REFANYVAL:
8063                         CHECK_STACK (1);
8064                         MONO_INST_NEW (cfg, ins, *ip);
8065                         --sp;
8066                         CHECK_OPSIZE (5);
8067                         klass = mono_class_get_full (image, read32 (ip + 1), generic_context);
8068                         CHECK_TYPELOAD (klass);
8069                         mono_class_init (klass);
8070                         ins->type = STACK_MP;
8071                         ins->inst_left = *sp;
8072                         ins->klass = klass;
8073                         ins->inst_newa_class = klass;
8074                         ins->cil_code = ip;
8075                         ip += 5;
8076                         *sp++ = ins;
8077                         break;
8078                 case CEE_MKREFANY: {
8079                         MonoInst *loc, *klassconst;
8080
8081                         CHECK_STACK (1);
8082                         MONO_INST_NEW (cfg, ins, *ip);
8083                         --sp;
8084                         CHECK_OPSIZE (5);
8085                         klass = mono_class_get_full (image, read32 (ip + 1), generic_context);
8086                         CHECK_TYPELOAD (klass);
8087                         mono_class_init (klass);
8088                         ins->cil_code = ip;
8089
8090                         if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
8091                                 GENERIC_SHARING_FAILURE (CEE_MKREFANY);
8092
8093                         loc = mono_compile_create_var (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL);
8094                         NEW_TEMPLOADA (cfg, ins->inst_right, loc->inst_c0);
8095
8096                         NEW_PCONST (cfg, klassconst, klass);
8097                         NEW_GROUP (cfg, ins->inst_left, *sp, klassconst);
8098                         
8099                         MONO_ADD_INS (bblock, ins);
8100
8101                         NEW_TEMPLOAD (cfg, *sp, loc->inst_c0);
8102                         ++sp;
8103                         ip += 5;
8104                         break;
8105                 }
8106                 case CEE_LDTOKEN: {
8107                         gpointer handle;
8108                         MonoClass *handle_class;
8109                         int context_used = 0;
8110
8111                         CHECK_STACK_OVF (1);
8112
8113                         CHECK_OPSIZE (5);
8114                         n = read32 (ip + 1);
8115
8116                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8117                                 handle = mono_method_get_wrapper_data (method, n);
8118                                 handle_class = mono_method_get_wrapper_data (method, n + 1);
8119                                 if (handle_class == mono_defaults.typehandle_class)
8120                                         handle = &((MonoClass*)handle)->byval_arg;
8121                         }
8122                         else {
8123                                 handle = mono_ldtoken (image, n, &handle_class, generic_context);
8124                         }
8125                         if (!handle)
8126                                 goto load_error;
8127                         mono_class_init (handle_class);
8128
8129                         if (cfg->generic_sharing_context) {
8130                                 if (handle_class == mono_defaults.typehandle_class) {
8131                                         /* If we get a MONO_TYPE_CLASS
8132                                            then we need to provide the
8133                                            open type, not an
8134                                            instantiation of it. */
8135                                         if (mono_type_get_type (handle) == MONO_TYPE_CLASS)
8136                                                 context_used = 0;
8137                                         else
8138                                                 context_used = mono_class_check_context_used (mono_class_from_mono_type (handle));
8139                                 } else if (handle_class == mono_defaults.fieldhandle_class)
8140                                         context_used = mono_class_check_context_used (((MonoClassField*)handle)->parent);
8141                                 else if (handle_class == mono_defaults.methodhandle_class)
8142                                         context_used = mono_method_check_context_used (handle);
8143                                 else
8144                                         g_assert_not_reached ();
8145
8146                                 if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD)
8147                                         GENERIC_SHARING_FAILURE (CEE_LDTOKEN);
8148                         }
8149
8150                         if (cfg->opt & MONO_OPT_SHARED) {
8151                                 int temp;
8152                                 MonoInst *res, *store, *addr, *vtvar, *iargs [3];
8153
8154                                 GENERIC_SHARING_FAILURE (CEE_LDTOKEN);
8155
8156                                 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL); 
8157
8158                                 NEW_IMAGECONST (cfg, iargs [0], image);
8159                                 NEW_ICONST (cfg, iargs [1], n);
8160                                 NEW_PCONST (cfg, iargs [2], generic_context);
8161                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldtoken_wrapper, iargs, ip);
8162                                 NEW_TEMPLOAD (cfg, res, temp);
8163                                 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
8164                                 NEW_INDSTORE (cfg, store, addr, res, &mono_defaults.int_class->byval_arg);
8165                                 MONO_ADD_INS (bblock, store);
8166                                 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
8167                         } else {
8168                                 if ((ip + 10 < end) && ip_in_bb (cfg, bblock, ip + 5) &&
8169                                         handle_class == mono_defaults.typehandle_class &&
8170                                         ((ip [5] == CEE_CALL) || (ip [5] == CEE_CALLVIRT)) && 
8171                                         (cmethod = mini_get_method (cfg, method, read32 (ip + 6), NULL, generic_context)) &&
8172                                         (cmethod->klass == mono_defaults.monotype_class->parent) &&
8173                                         (strcmp (cmethod->name, "GetTypeFromHandle") == 0)) {
8174                                         MonoClass *tclass = mono_class_from_mono_type (handle);
8175                                         mono_class_init (tclass);
8176                                         if (context_used) {
8177                                                 MonoInst *this, *rgctx;
8178
8179                                                 g_assert (!cfg->compile_aot);
8180                                                 if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
8181                                                         NEW_ARGLOAD (cfg, this, 0);
8182                                                 rgctx = get_runtime_generic_context (cfg, method, this, ip);
8183                                                 ins = get_runtime_generic_context_ptr (cfg, method, bblock, tclass,
8184                                                         token, MINI_TOKEN_SOURCE_CLASS, generic_context,
8185                                                         rgctx, MONO_RGCTX_INFO_REFLECTION_TYPE, ip);
8186                                         } else if (cfg->compile_aot) {
8187                                                 NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, image, n);
8188                                         } else {
8189                                                 NEW_PCONST (cfg, ins, mono_type_get_object (cfg->domain, handle));
8190                                         }
8191                                         ins->type = STACK_OBJ;
8192                                         ins->klass = cmethod->klass;
8193                                         ip += 5;
8194                                 } else {
8195                                         MonoInst *store, *addr, *vtvar;
8196
8197                                         GENERIC_SHARING_FAILURE (CEE_LDTOKEN);
8198
8199                                         if (cfg->compile_aot)
8200                                                 NEW_LDTOKENCONST (cfg, ins, image, n);
8201                                         else
8202                                                 NEW_PCONST (cfg, ins, handle);
8203                                         vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL);
8204                                         NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
8205                                         NEW_INDSTORE (cfg, store, addr, ins, &mono_defaults.int_class->byval_arg);
8206                                         MONO_ADD_INS (bblock, store);
8207                                         NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
8208                                 }
8209                         }
8210
8211                         *sp++ = ins;
8212                         ip += 5;
8213                         break;
8214                 }
8215                 case CEE_CONV_U2:
8216                 case CEE_CONV_U1:
8217                 case CEE_CONV_I:
8218                         CHECK_STACK (1);
8219                         ADD_UNOP (*ip);
8220                         ip++;
8221                         break;
8222                 case CEE_ADD_OVF:
8223                 case CEE_ADD_OVF_UN:
8224                 case CEE_MUL_OVF:
8225                 case CEE_MUL_OVF_UN:
8226                 case CEE_SUB_OVF:
8227                 case CEE_SUB_OVF_UN:
8228                         CHECK_STACK (2);
8229                         ADD_BINOP (*ip);
8230                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
8231                                 --sp;
8232                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
8233                         }
8234                         ip++;
8235                         break;
8236                 case CEE_ENDFINALLY:
8237                         MONO_INST_NEW (cfg, ins, OP_ENDFINALLY);
8238                         MONO_ADD_INS (bblock, ins);
8239                         ins->cil_code = ip++;
8240                         start_new_bblock = 1;
8241
8242                         /*
8243                          * Control will leave the method so empty the stack, otherwise
8244                          * the next basic block will start with a nonempty stack.
8245                          */
8246                         while (sp != stack_start) {
8247                                 MONO_INST_NEW (cfg, ins, CEE_POP);
8248                                 ins->cil_code = ip;
8249                                 sp--;
8250                                 ins->inst_i0 = *sp;
8251                                 MONO_ADD_INS (bblock, ins);
8252                         }
8253                         break;
8254                 case CEE_LEAVE:
8255                 case CEE_LEAVE_S: {
8256                         GList *handlers;
8257
8258                         if (*ip == CEE_LEAVE) {
8259                                 CHECK_OPSIZE (5);
8260                                 target = ip + 5 + (gint32)read32(ip + 1);
8261                         } else {
8262                                 CHECK_OPSIZE (2);
8263                                 target = ip + 2 + (signed char)(ip [1]);
8264                         }
8265
8266                         /* empty the stack */
8267                         while (sp != stack_start) {
8268                                 MONO_INST_NEW (cfg, ins, CEE_POP);
8269                                 ins->cil_code = ip;
8270                                 sp--;
8271                                 ins->inst_i0 = *sp;
8272                                 MONO_ADD_INS (bblock, ins);
8273                         }
8274
8275                         /* 
8276                          * If this leave statement is in a catch block, check for a
8277                          * pending exception, and rethrow it if necessary.
8278                          */
8279                         for (i = 0; i < header->num_clauses; ++i) {
8280                                 MonoExceptionClause *clause = &header->clauses [i];
8281
8282                                 /* 
8283                                  * Use <= in the final comparison to handle clauses with multiple
8284                                  * leave statements, like in bug #78024.
8285                                  * The ordering of the exception clauses guarantees that we find the
8286                                  * innermost clause.
8287                                  */
8288                                 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)) {
8289                                         int temp;
8290                                         MonoInst *load;
8291
8292                                         NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, clause->handler_offset)->inst_c0);
8293                                         load->cil_code = ip;
8294
8295                                         temp = mono_emit_jit_icall (cfg, bblock, mono_thread_get_undeniable_exception, NULL, ip);
8296                                         NEW_TEMPLOAD (cfg, *sp, temp);
8297                                 
8298                                         MONO_INST_NEW (cfg, ins, OP_THROW_OR_NULL);
8299                                         ins->inst_left = *sp;
8300                                         ins->inst_right = load;
8301                                         ins->cil_code = ip;
8302                                         MONO_ADD_INS (bblock, ins);
8303                                 }
8304                         }
8305
8306                         if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
8307                                 GList *tmp;
8308                                 for (tmp = handlers; tmp; tmp = tmp->next) {
8309                                         tblock = tmp->data;
8310                                         link_bblock (cfg, bblock, tblock);
8311                                         MONO_INST_NEW (cfg, ins, OP_CALL_HANDLER);
8312                                         ins->cil_code = ip;
8313                                         ins->inst_target_bb = tblock;
8314                                         MONO_ADD_INS (bblock, ins);
8315                                 }
8316                                 g_list_free (handlers);
8317                         } 
8318
8319                         MONO_INST_NEW (cfg, ins, OP_BR);
8320                         ins->cil_code = ip;
8321                         MONO_ADD_INS (bblock, ins);
8322                         GET_BBLOCK (cfg, tblock, target);
8323                         link_bblock (cfg, bblock, tblock);
8324                         CHECK_BBLOCK (target, ip, tblock);
8325                         ins->inst_target_bb = tblock;
8326                         start_new_bblock = 1;
8327
8328                         if (*ip == CEE_LEAVE)
8329                                 ip += 5;
8330                         else
8331                                 ip += 2;
8332
8333                         break;
8334                 }
8335                 case CEE_STIND_I:
8336                         CHECK_STACK (2);
8337                         MONO_INST_NEW (cfg, ins, *ip);
8338                         sp -= 2;
8339                         handle_loaded_temps (cfg, bblock, stack_start, sp);
8340                         MONO_ADD_INS (bblock, ins);
8341                         ins->cil_code = ip++;
8342                         ins->inst_i0 = sp [0];
8343                         ins->inst_i1 = sp [1];
8344                         inline_costs += 1;
8345                         break;
8346                 case CEE_CONV_U:
8347                         CHECK_STACK (1);
8348                         ADD_UNOP (*ip);
8349                         ip++;
8350                         break;
8351                 /* trampoline mono specific opcodes */
8352                 case MONO_CUSTOM_PREFIX: {
8353
8354                         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
8355
8356                         CHECK_OPSIZE (2);
8357                         switch (ip [1]) {
8358
8359                         case CEE_MONO_ICALL: {
8360                                 int temp;
8361                                 gpointer func;
8362                                 MonoJitICallInfo *info;
8363
8364                                 token = read32 (ip + 2);
8365                                 func = mono_method_get_wrapper_data (method, token);
8366                                 info = mono_find_jit_icall_by_addr (func);
8367                                 if (info == NULL){
8368                                         g_error ("An attempt has been made to perform an icall to address %p, "
8369                                                  "but the address has not been registered as an icall\n", info);
8370                                         g_assert_not_reached ();
8371                                 }
8372
8373                                 CHECK_STACK (info->sig->param_count);
8374                                 sp -= info->sig->param_count;
8375
8376                                 temp = mono_emit_jit_icall (cfg, bblock, info->func, sp, ip);
8377                                 if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
8378                                         NEW_TEMPLOAD (cfg, *sp, temp);
8379                                         sp++;
8380                                 }
8381
8382                                 ip += 6;
8383                                 inline_costs += 10 * num_calls++;
8384
8385                                 break;
8386                         }
8387                         case CEE_MONO_LDPTR: {
8388                                 gpointer ptr;
8389
8390                                 CHECK_STACK_OVF (1);
8391                                 CHECK_OPSIZE (6);
8392                                 token = read32 (ip + 2);
8393
8394                                 ptr = mono_method_get_wrapper_data (method, token);
8395                                 if (cfg->compile_aot && cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
8396                                         MonoMethod *wrapped = mono_marshal_method_from_wrapper (cfg->method);
8397
8398                                         if (wrapped && ptr != NULL && mono_lookup_internal_call (wrapped) == ptr) {
8399                                                 NEW_AOTCONST (cfg, ins, MONO_PATCH_INFO_ICALL_ADDR, wrapped);
8400                                                 ins->cil_code = ip;
8401                                                 *sp++ = ins;
8402                                                 ip += 6;
8403                                                 break;
8404                                         }
8405                                 }
8406                                 NEW_PCONST (cfg, ins, ptr);
8407                                 ins->cil_code = ip;
8408                                 *sp++ = ins;
8409                                 ip += 6;
8410                                 inline_costs += 10 * num_calls++;
8411                                 /* Can't embed random pointers into AOT code */
8412                                 cfg->disable_aot = 1;
8413                                 break;
8414                         }
8415                         case CEE_MONO_VTADDR:
8416                                 CHECK_STACK (1);
8417                                 --sp;
8418                                 MONO_INST_NEW (cfg, ins, OP_VTADDR);
8419                                 ins->cil_code = ip;
8420                                 ins->type = STACK_MP;
8421                                 ins->inst_left = *sp;
8422                                 *sp++ = ins;
8423                                 ip += 2;
8424                                 break;
8425                         case CEE_MONO_NEWOBJ: {
8426                                 MonoInst *iargs [2];
8427                                 int temp;
8428                                 CHECK_STACK_OVF (1);
8429                                 CHECK_OPSIZE (6);
8430                                 token = read32 (ip + 2);
8431                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
8432                                 mono_class_init (klass);
8433                                 NEW_DOMAINCONST (cfg, iargs [0]);
8434                                 NEW_CLASSCONST (cfg, iargs [1], klass);
8435                                 temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
8436                                 NEW_TEMPLOAD (cfg, *sp, temp);
8437                                 sp++;
8438                                 ip += 6;
8439                                 inline_costs += 10 * num_calls++;
8440                                 break;
8441                         }
8442                         case CEE_MONO_OBJADDR:
8443                                 CHECK_STACK (1);
8444                                 --sp;
8445                                 MONO_INST_NEW (cfg, ins, OP_OBJADDR);
8446                                 ins->cil_code = ip;
8447                                 ins->type = STACK_MP;
8448                                 ins->inst_left = *sp;
8449                                 *sp++ = ins;
8450                                 ip += 2;
8451                                 break;
8452                         case CEE_MONO_LDNATIVEOBJ:
8453                                 CHECK_STACK (1);
8454                                 CHECK_OPSIZE (6);
8455                                 token = read32 (ip + 2);
8456                                 klass = mono_method_get_wrapper_data (method, token);
8457                                 g_assert (klass->valuetype);
8458                                 mono_class_init (klass);
8459                                 NEW_INDLOAD (cfg, ins, sp [-1], &klass->byval_arg);
8460                                 sp [-1] = ins;
8461                                 ip += 6;
8462                                 break;
8463                         case CEE_MONO_RETOBJ:
8464                                 g_assert (cfg->ret);
8465                                 g_assert (mono_method_signature (method)->pinvoke); 
8466                                 CHECK_STACK (1);
8467                                 --sp;
8468                                 
8469                                 CHECK_OPSIZE (6);
8470                                 token = read32 (ip + 2);    
8471                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
8472
8473                                 NEW_RETLOADA (cfg, ins);
8474                                 handle_stobj (cfg, bblock, ins, *sp, ip, klass, FALSE, TRUE, FALSE);
8475                                 
8476                                 if (sp != stack_start)
8477                                         UNVERIFIED;
8478                                 
8479                                 MONO_INST_NEW (cfg, ins, OP_BR);
8480                                 ins->cil_code = ip;
8481                                 ins->inst_target_bb = end_bblock;
8482                                 MONO_ADD_INS (bblock, ins);
8483                                 link_bblock (cfg, bblock, end_bblock);
8484                                 start_new_bblock = 1;
8485                                 ip += 6;
8486                                 break;
8487                         case CEE_MONO_CISINST:
8488                         case CEE_MONO_CCASTCLASS: {
8489                                 int token;
8490                                 CHECK_STACK (1);
8491                                 --sp;
8492                                 CHECK_OPSIZE (6);
8493                                 token = read32 (ip + 2);
8494                                 /* Needed by the code generated in inssel.brg */
8495                                 mono_get_got_var (cfg);
8496                 
8497                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
8498                                 MONO_INST_NEW (cfg, ins, (ip [1] == CEE_MONO_CISINST) ? OP_CISINST : OP_CCASTCLASS);
8499                                 ins->type = STACK_I4;
8500                                 ins->inst_left = *sp;
8501                                 ins->inst_newa_class = klass;
8502                                 ins->cil_code = ip;
8503                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 6);
8504                                 ip += 6;
8505                                 break;
8506                         }
8507                         case CEE_MONO_SAVE_LMF:
8508                         case CEE_MONO_RESTORE_LMF:
8509 #ifdef MONO_ARCH_HAVE_LMF_OPS
8510                                 MONO_INST_NEW (cfg, ins, (ip [1] == CEE_MONO_SAVE_LMF) ? OP_SAVE_LMF : OP_RESTORE_LMF);
8511                                 MONO_ADD_INS (bblock, ins);
8512                                 cfg->need_lmf_area = TRUE;
8513 #endif
8514                                 ip += 2;
8515                                 break;
8516                         case CEE_MONO_CLASSCONST:
8517                                 CHECK_STACK_OVF (1);
8518                                 CHECK_OPSIZE (6);
8519                                 token = read32 (ip + 2);
8520                                 NEW_CLASSCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
8521                                 ins->cil_code = ip;
8522                                 *sp++ = ins;
8523                                 ip += 6;
8524                                 inline_costs += 10 * num_calls++;
8525                                 break;
8526                         case CEE_MONO_NOT_TAKEN:
8527                                 bblock->out_of_line = TRUE;
8528                                 ip += 2;
8529                                 break;
8530                         case CEE_MONO_TLS:
8531                                 CHECK_STACK_OVF (1);
8532                                 CHECK_OPSIZE (6);
8533                                 MONO_INST_NEW (cfg, ins, OP_TLS_GET);
8534                                 ins->inst_offset = (gint32)read32 (ip + 2);
8535                                 ins->cil_code = ip;
8536                                 ins->type = STACK_PTR;
8537                                 *sp++ = ins;
8538                                 ip += 6;
8539                                 break;
8540                         default:
8541                                 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
8542                                 break;
8543                         }
8544                         break;
8545                 }
8546                 case CEE_PREFIX1: {
8547                         CHECK_OPSIZE (2);
8548                         switch (ip [1]) {
8549                         case CEE_ARGLIST: {
8550                                 /* somewhat similar to LDTOKEN */
8551                                 MonoInst *addr, *vtvar;
8552                                 CHECK_STACK_OVF (1);
8553                                 vtvar = mono_compile_create_var (cfg, &mono_defaults.argumenthandle_class->byval_arg, OP_LOCAL); 
8554
8555                                 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
8556                                 addr->cil_code = ip;
8557                                 MONO_INST_NEW (cfg, ins, OP_ARGLIST);
8558                                 ins->cil_code = ip;
8559                                 ins->inst_left = addr;
8560                                 MONO_ADD_INS (bblock, ins);
8561                                 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
8562                                 ins->cil_code = ip;
8563                                 *sp++ = ins;
8564                                 ip += 2;
8565                                 break;
8566                         }
8567                         case CEE_CEQ:
8568                         case CEE_CGT:
8569                         case CEE_CGT_UN:
8570                         case CEE_CLT:
8571                         case CEE_CLT_UN: {
8572                                 MonoInst *cmp;
8573                                 CHECK_STACK (2);
8574                                 /*
8575                                  * The following transforms:
8576                                  *    CEE_CEQ    into OP_CEQ
8577                                  *    CEE_CGT    into OP_CGT
8578                                  *    CEE_CGT_UN into OP_CGT_UN
8579                                  *    CEE_CLT    into OP_CLT
8580                                  *    CEE_CLT_UN into OP_CLT_UN
8581                                  */
8582                                 MONO_INST_NEW (cfg, cmp, (OP_CEQ - CEE_CEQ) + ip [1]);
8583                                 
8584                                 MONO_INST_NEW (cfg, ins, cmp->opcode);
8585                                 sp -= 2;
8586                                 cmp->inst_i0 = sp [0];
8587                                 cmp->inst_i1 = sp [1];
8588                                 cmp->cil_code = ip;
8589                                 type_from_op (cmp);
8590                                 CHECK_TYPE (cmp);
8591                                 ins->cil_code = ip;
8592                                 ins->type = STACK_I4;
8593                                 ins->inst_i0 = cmp;
8594 #if MONO_ARCH_SOFT_FLOAT
8595                                 if (sp [0]->type == STACK_R8) {
8596                                         cmp->type = STACK_I4;
8597                                         *sp++ = emit_tree (cfg, bblock, cmp, ip + 2);
8598                                         ip += 2;
8599                                         break;
8600                                 }
8601 #endif
8602                                 if ((sp [0]->type == STACK_I8) || ((sizeof (gpointer) == 8) && ((sp [0]->type == STACK_PTR) || (sp [0]->type == STACK_OBJ) || (sp [0]->type == STACK_MP))))
8603                                         cmp->opcode = OP_LCOMPARE;
8604                                 else
8605                                         cmp->opcode = OP_COMPARE;
8606                                 *sp++ = ins;
8607                                 /* spill it to reduce the expression complexity
8608                                  * and workaround bug 54209 
8609                                  */
8610                                 if (cmp->inst_left->type == STACK_I8) {
8611                                         --sp;
8612                                         *sp++ = emit_tree (cfg, bblock, ins, ip + 2);
8613                                 }
8614                                 ip += 2;
8615                                 break;
8616                         }
8617                         case CEE_LDFTN: {
8618                                 MonoInst *argconst;
8619                                 MonoMethod *cil_method, *ctor_method;
8620                                 int temp;
8621                                 gboolean is_shared;
8622
8623                                 CHECK_STACK_OVF (1);
8624                                 CHECK_OPSIZE (6);
8625                                 n = read32 (ip + 2);
8626                                 cmethod = mini_get_method (cfg, method, n, NULL, generic_context);
8627                                 if (!cmethod)
8628                                         goto load_error;
8629                                 mono_class_init (cmethod->klass);
8630
8631                                 if (cfg->generic_sharing_context && mono_method_check_context_used (cmethod))
8632                                         GENERIC_SHARING_FAILURE (CEE_LDFTN);
8633
8634                                 is_shared = (cmethod->flags & METHOD_ATTRIBUTE_STATIC) &&
8635                                         (cmethod->klass->generic_class || cmethod->klass->generic_container) &&
8636                                         mono_class_generic_sharing_enabled (cmethod->klass);
8637
8638                                 cil_method = cmethod;
8639                                 if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_method (method, cmethod))
8640                                         METHOD_ACCESS_FAILURE;
8641                                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
8642                                         if (check_linkdemand (cfg, method, cmethod, bblock, ip))
8643                                                 INLINE_FAILURE;
8644                                         CHECK_CFG_EXCEPTION;
8645                                 } else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
8646                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod, bblock, ip);
8647                                 }
8648
8649                                 /* 
8650                                  * Optimize the common case of ldftn+delegate creation
8651                                  */
8652 #if defined(MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE) && !defined(HAVE_WRITE_BARRIERS)
8653                                 /* FIXME: SGEN support */
8654                                 /* FIXME: handle shared static generic methods */
8655                                 if (!is_shared && (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)) {
8656                                         MonoInst *target_ins;
8657
8658                                         ip += 6;
8659                                         if (cfg->verbose_level > 3)
8660                                                 g_print ("converting (in B%d: stack: %d) %s", bblock->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
8661                                         target_ins = sp [-1];
8662                                         sp --;
8663                                         *sp = handle_delegate_ctor (cfg, bblock, ctor_method->klass, target_ins, cmethod, ip);
8664                                         ip += 5;                                        
8665                                         sp ++;
8666                                         break;
8667                                 }
8668 #endif
8669
8670                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
8671
8672                                 if (is_shared)
8673                                         NEW_METHODCONST (cfg, argconst, mono_marshal_get_static_rgctx_invoke (cmethod));
8674                                 else
8675                                         NEW_METHODCONST (cfg, argconst, cmethod);
8676                                 if (method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED)
8677                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn, &argconst, ip);
8678                                 else
8679                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn_nosync, &argconst, ip);
8680                                 NEW_TEMPLOAD (cfg, *sp, temp);
8681                                 sp ++;
8682                                 
8683                                 ip += 6;
8684                                 inline_costs += 10 * num_calls++;
8685                                 break;
8686                         }
8687                         case CEE_LDVIRTFTN: {
8688                                 MonoInst *args [2];
8689                                 int temp;
8690
8691                                 CHECK_STACK (1);
8692                                 CHECK_OPSIZE (6);
8693                                 n = read32 (ip + 2);
8694                                 cmethod = mini_get_method (cfg, method, n, NULL, generic_context);
8695                                 if (!cmethod)
8696                                         goto load_error;
8697                                 mono_class_init (cmethod->klass);
8698
8699                                 if (cfg->generic_sharing_context && mono_method_check_context_used (cmethod))
8700                                         GENERIC_SHARING_FAILURE (CEE_LDVIRTFTN);
8701
8702                                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
8703                                         if (check_linkdemand (cfg, method, cmethod, bblock, ip))
8704                                                 INLINE_FAILURE;
8705                                         CHECK_CFG_EXCEPTION;
8706                                 } else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
8707                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod, bblock, ip);
8708                                 }
8709
8710                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
8711
8712                                 --sp;
8713                                 args [0] = *sp;
8714                                 NEW_METHODCONST (cfg, args [1], cmethod);
8715                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldvirtfn, args, ip);
8716                                 NEW_TEMPLOAD (cfg, *sp, temp);
8717                                 sp ++;
8718
8719                                 ip += 6;
8720                                 inline_costs += 10 * num_calls++;
8721                                 break;
8722                         }
8723                         case CEE_LDARG:
8724                                 CHECK_STACK_OVF (1);
8725                                 CHECK_OPSIZE (4);
8726                                 n = read16 (ip + 2);
8727                                 CHECK_ARG (n);
8728                                 NEW_ARGLOAD (cfg, ins, n);
8729                                 LDARG_SOFT_FLOAT (cfg, ins, n, ip);
8730                                 ins->cil_code = ip;
8731                                 *sp++ = ins;
8732                                 ip += 4;
8733                                 break;
8734                         case CEE_LDARGA:
8735                                 CHECK_STACK_OVF (1);
8736                                 CHECK_OPSIZE (4);
8737                                 n = read16 (ip + 2);
8738                                 CHECK_ARG (n);
8739                                 NEW_ARGLOADA (cfg, ins, n);
8740                                 ins->cil_code = ip;
8741                                 *sp++ = ins;
8742                                 ip += 4;
8743                                 break;
8744                         case CEE_STARG:
8745                                 CHECK_STACK (1);
8746                                 --sp;
8747                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
8748                                 CHECK_OPSIZE (4);
8749                                 n = read16 (ip + 2);
8750                                 CHECK_ARG (n);
8751                                 NEW_ARGSTORE (cfg, ins, n, *sp);
8752                                 ins->cil_code = ip;
8753                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [n], *sp))
8754                                         UNVERIFIED;
8755                                 STARG_SOFT_FLOAT (cfg, ins, n, ip);
8756                                 if (ins->opcode == CEE_STOBJ) {
8757                                         NEW_ARGLOADA (cfg, ins, n);
8758                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
8759                                 } else
8760                                         MONO_ADD_INS (bblock, ins);
8761                                 ip += 4;
8762                                 break;
8763                         case CEE_LDLOC:
8764                                 CHECK_STACK_OVF (1);
8765                                 CHECK_OPSIZE (4);
8766                                 n = read16 (ip + 2);
8767                                 CHECK_LOCAL (n);
8768                                 NEW_LOCLOAD (cfg, ins, n);
8769                                 LDLOC_SOFT_FLOAT (cfg, ins, n, ip);
8770                                 ins->cil_code = ip;
8771                                 *sp++ = ins;
8772                                 ip += 4;
8773                                 break;
8774                         case CEE_LDLOCA:
8775                                 CHECK_STACK_OVF (1);
8776                                 CHECK_OPSIZE (4);
8777                                 n = read16 (ip + 2);
8778                                 CHECK_LOCAL (n);
8779                                 NEW_LOCLOADA (cfg, ins, n);
8780                                 ins->cil_code = ip;
8781                                 *sp++ = ins;
8782                                 ip += 4;
8783                                 break;
8784                         case CEE_STLOC:
8785                                 CHECK_STACK (1);
8786                                 --sp;
8787                                 CHECK_OPSIZE (4);
8788                                 n = read16 (ip + 2);
8789                                 CHECK_LOCAL (n);
8790                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
8791                                 NEW_LOCSTORE (cfg, ins, n, *sp);
8792                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
8793                                         UNVERIFIED;
8794                                 ins->cil_code = ip;
8795                                 STLOC_SOFT_FLOAT (cfg, ins, n, ip);
8796                                 if (ins->opcode == CEE_STOBJ) {
8797                                         NEW_LOCLOADA (cfg, ins, n);
8798                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
8799                                 } else
8800                                         MONO_ADD_INS (bblock, ins);
8801                                 ip += 4;
8802                                 inline_costs += 1;
8803                                 break;
8804                         case CEE_LOCALLOC:
8805                                 CHECK_STACK (1);
8806                                 --sp;
8807                                 if (sp != stack_start) 
8808                                         UNVERIFIED;
8809                                 if (cfg->method != method) 
8810                                         /* 
8811                                          * Inlining this into a loop in a parent could lead to 
8812                                          * stack overflows which is different behavior than the
8813                                          * non-inlined case, thus disable inlining in this case.
8814                                          */
8815                                         goto inline_failure;
8816                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
8817                                 ins->inst_left = *sp;
8818                                 ins->cil_code = ip;
8819                                 ins->type = STACK_PTR;
8820
8821                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
8822                                 if (header->init_locals)
8823                                         ins->flags |= MONO_INST_INIT;
8824
8825                                 *sp++ = ins;
8826                                 ip += 2;
8827                                 /* FIXME: set init flag if locals init is set in this method */
8828                                 break;
8829                         case CEE_ENDFILTER: {
8830                                 MonoExceptionClause *clause, *nearest;
8831                                 int cc, nearest_num;
8832
8833                                 CHECK_STACK (1);
8834                                 --sp;
8835                                 if ((sp != stack_start) || (sp [0]->type != STACK_I4)) 
8836                                         UNVERIFIED;
8837                                 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
8838                                 ins->inst_left = *sp;
8839                                 ins->cil_code = ip;
8840                                 MONO_ADD_INS (bblock, ins);
8841                                 start_new_bblock = 1;
8842                                 ip += 2;
8843
8844                                 nearest = NULL;
8845                                 nearest_num = 0;
8846                                 for (cc = 0; cc < header->num_clauses; ++cc) {
8847                                         clause = &header->clauses [cc];
8848                                         if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
8849                                                 ((ip - header->code) > clause->data.filter_offset && (ip - header->code) <= clause->handler_offset) &&
8850                                             (!nearest || (clause->data.filter_offset < nearest->data.filter_offset))) {
8851                                                 nearest = clause;
8852                                                 nearest_num = cc;
8853                                         }
8854                                 }
8855                                 g_assert (nearest);
8856                                 if ((ip - header->code) != nearest->handler_offset)
8857                                         UNVERIFIED;
8858
8859                                 break;
8860                         }
8861                         case CEE_UNALIGNED_:
8862                                 ins_flag |= MONO_INST_UNALIGNED;
8863                                 /* FIXME: record alignment? we can assume 1 for now */
8864                                 CHECK_OPSIZE (3);
8865                                 ip += 3;
8866                                 break;
8867                         case CEE_VOLATILE_:
8868                                 ins_flag |= MONO_INST_VOLATILE;
8869                                 ip += 2;
8870                                 break;
8871                         case CEE_TAIL_:
8872                                 ins_flag   |= MONO_INST_TAILCALL;
8873                                 cfg->flags |= MONO_CFG_HAS_TAIL;
8874                                 /* Can't inline tail calls at this time */
8875                                 inline_costs += 100000;
8876                                 ip += 2;
8877                                 break;
8878                         case CEE_INITOBJ:
8879                                 CHECK_STACK (1);
8880                                 --sp;
8881                                 CHECK_OPSIZE (6);
8882                                 token = read32 (ip + 2);
8883                                 klass = mini_get_class (method, token, generic_context);
8884                                 CHECK_TYPELOAD (klass);
8885
8886                                 if (generic_class_is_reference_type (cfg, klass)) {
8887                                         MonoInst *store, *load;
8888                                         NEW_PCONST (cfg, load, NULL);
8889                                         load->cil_code = ip;
8890                                         load->type = STACK_OBJ;
8891                                         load->klass = klass;
8892                                         MONO_INST_NEW (cfg, store, CEE_STIND_REF);
8893                                         store->cil_code = ip;
8894                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
8895                                         MONO_ADD_INS (bblock, store);
8896                                         store->inst_i0 = sp [0];
8897                                         store->inst_i1 = load;
8898                                 } else {
8899                                         GENERIC_SHARING_FAILURE (CEE_INITOBJ);
8900                                         handle_initobj (cfg, bblock, *sp, NULL, klass, stack_start, sp);
8901                                 }
8902                                 ip += 6;
8903                                 inline_costs += 1;
8904                                 break;
8905                         case CEE_CONSTRAINED_:
8906                                 /* FIXME: implement */
8907                                 CHECK_OPSIZE (6);
8908                                 token = read32 (ip + 2);
8909                                 constrained_call = mono_class_get_full (image, token, generic_context);
8910                                 CHECK_TYPELOAD (constrained_call);
8911                                 ip += 6;
8912                                 break;
8913                         case CEE_CPBLK:
8914                         case CEE_INITBLK: {
8915                                 MonoInst *iargs [3];
8916                                 CHECK_STACK (3);
8917                                 sp -= 3;
8918                                 if ((cfg->opt & MONO_OPT_INTRINS) && (ip [1] == CEE_CPBLK) && (sp [2]->opcode == OP_ICONST) && ((n = sp [2]->inst_c0) <= sizeof (gpointer) * 5)) {
8919                                         MonoInst *copy;
8920                                         NEW_MEMCPY (cfg, copy, sp [0], sp [1], n, 0);
8921                                         MONO_ADD_INS (bblock, copy);
8922                                         ip += 2;
8923                                         break;
8924                                 }
8925                                 iargs [0] = sp [0];
8926                                 iargs [1] = sp [1];
8927                                 iargs [2] = sp [2];
8928                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
8929                                 if (ip [1] == CEE_CPBLK) {
8930                                         MonoMethod *memcpy_method = get_memcpy_method ();
8931                                         mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
8932                                 } else {
8933                                         MonoMethod *memset_method = get_memset_method ();
8934                                         mono_emit_method_call_spilled (cfg, bblock, memset_method, memset_method->signature, iargs, ip, NULL);
8935                                 }
8936                                 ip += 2;
8937                                 inline_costs += 1;
8938                                 break;
8939                         }
8940                         case CEE_NO_:
8941                                 CHECK_OPSIZE (3);
8942                                 if (ip [2] & 0x1)
8943                                         ins_flag |= MONO_INST_NOTYPECHECK;
8944                                 if (ip [2] & 0x2)
8945                                         ins_flag |= MONO_INST_NORANGECHECK;
8946                                 /* we ignore the no-nullcheck for now since we
8947                                  * really do it explicitly only when doing callvirt->call
8948                                  */
8949                                 ip += 3;
8950                                 break;
8951                         case CEE_RETHROW: {
8952                                 MonoInst *load;
8953                                 int handler_offset = -1;
8954
8955                                 for (i = 0; i < header->num_clauses; ++i) {
8956                                         MonoExceptionClause *clause = &header->clauses [i];
8957                                         if (MONO_OFFSET_IN_HANDLER (clause, ip - header->code) && !(clause->flags & MONO_EXCEPTION_CLAUSE_FINALLY))
8958                                                 handler_offset = clause->handler_offset;
8959                                 }
8960
8961                                 bblock->flags |= BB_EXCEPTION_UNSAFE;
8962
8963                                 g_assert (handler_offset != -1);
8964
8965                                 NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, handler_offset)->inst_c0);
8966                                 load->cil_code = ip;
8967                                 MONO_INST_NEW (cfg, ins, OP_RETHROW);
8968                                 ins->inst_left = load;
8969                                 ins->cil_code = ip;
8970                                 MONO_ADD_INS (bblock, ins);
8971                                 sp = stack_start;
8972                                 link_bblock (cfg, bblock, end_bblock);
8973                                 start_new_bblock = 1;
8974                                 ip += 2;
8975                                 break;
8976                         }
8977                         case CEE_SIZEOF:
8978                                 GENERIC_SHARING_FAILURE (CEE_SIZEOF);
8979
8980                                 CHECK_STACK_OVF (1);
8981                                 CHECK_OPSIZE (6);
8982                                 token = read32 (ip + 2);
8983                                 /* FIXXME: handle generics. */
8984                                 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC) {
8985                                         MonoType *type = mono_type_create_from_typespec (image, token);
8986                                         token = mono_type_size (type, &ialign);
8987                                 } else {
8988                                         MonoClass *klass = mono_class_get_full (image, token, generic_context);
8989                                         CHECK_TYPELOAD (klass);
8990                                         mono_class_init (klass);
8991                                         token = mono_class_value_size (klass, &align);
8992                                 }
8993                                 NEW_ICONST (cfg, ins, token);
8994                                 ins->cil_code = ip;
8995                                 *sp++= ins;
8996                                 ip += 6;
8997                                 break;
8998                         case CEE_REFANYTYPE:
8999                                 CHECK_STACK (1);
9000                                 MONO_INST_NEW (cfg, ins, OP_REFANYTYPE);
9001                                 --sp;
9002                                 ins->type = STACK_MP;
9003                                 ins->inst_left = *sp;
9004                                 ins->type = STACK_VTYPE;
9005                                 ins->klass = mono_defaults.typehandle_class;
9006                                 ins->cil_code = ip;
9007                                 ip += 2;
9008                                 *sp++ = ins;
9009                                 break;
9010                         case CEE_READONLY_:
9011                                 readonly = TRUE;
9012                                 ip += 2;
9013                                 break;
9014                         default:
9015                                 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
9016                         }
9017                         break;
9018                 }
9019                 default:
9020                         g_error ("opcode 0x%02x not handled", *ip);
9021                 }
9022         }
9023         if (start_new_bblock != 1)
9024                 UNVERIFIED;
9025
9026         bblock->cil_length = ip - bblock->cil_code;
9027         bblock->next_bb = end_bblock;
9028
9029         if (cfg->method == method && cfg->domainvar) {
9030                 MonoInst *store;
9031                 MonoInst *get_domain;
9032                 
9033                 if (! (get_domain = mono_arch_get_domain_intrinsic (cfg))) {
9034                         MonoCallInst *call;
9035                         
9036                         MONO_INST_NEW_CALL (cfg, call, OP_CALL);
9037                         call->signature = helper_sig_domain_get;
9038                         call->inst.type = STACK_PTR;
9039                         call->fptr = mono_domain_get;
9040                         get_domain = (MonoInst*)call;
9041                 }
9042                 
9043                 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, get_domain);
9044                 MONO_ADD_INS (init_localsbb, store);
9045         }
9046
9047         if (cfg->method == method && cfg->got_var)
9048                 mono_emit_load_got_addr (cfg);
9049
9050         if (header->init_locals) {
9051                 MonoInst *store;
9052                 cfg->ip = header->code;
9053                 for (i = 0; i < header->num_locals; ++i) {
9054                         MonoType *ptype = header->locals [i];
9055                         int t = ptype->type;
9056                         if (t == MONO_TYPE_VALUETYPE && ptype->data.klass->enumtype)
9057                                 t = ptype->data.klass->enum_basetype->type;
9058                         if (ptype->byref) {
9059                                 NEW_PCONST (cfg, ins, NULL);
9060                                 NEW_LOCSTORE (cfg, store, i, ins);
9061                                 MONO_ADD_INS (init_localsbb, store);
9062                         } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
9063                                 NEW_ICONST (cfg, ins, 0);
9064                                 NEW_LOCSTORE (cfg, store, i, ins);
9065                                 MONO_ADD_INS (init_localsbb, store);
9066                         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
9067                                 MONO_INST_NEW (cfg, ins, OP_I8CONST);
9068                                 ins->type = STACK_I8;
9069                                 ins->inst_l = 0;
9070                                 NEW_LOCSTORE (cfg, store, i, ins);
9071                                 MONO_ADD_INS (init_localsbb, store);
9072                         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
9073 #ifdef MONO_ARCH_SOFT_FLOAT
9074                                 /* FIXME: handle init of R4 */
9075 #else
9076                                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
9077                                 ins->type = STACK_R8;
9078                                 ins->inst_p0 = (void*)&r8_0;
9079                                 NEW_LOCSTORE (cfg, store, i, ins);
9080                                 MONO_ADD_INS (init_localsbb, store);
9081 #endif
9082                         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
9083                                    ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (ptype))) {
9084                                 NEW_LOCLOADA (cfg, ins, i);
9085                                 handle_initobj (cfg, init_localsbb, ins, NULL, mono_class_from_mono_type (ptype), NULL, NULL);
9086                         } else {
9087                                 NEW_PCONST (cfg, ins, NULL);
9088                                 NEW_LOCSTORE (cfg, store, i, ins);
9089                                 MONO_ADD_INS (init_localsbb, store);
9090                         }
9091                 }
9092         }
9093
9094         cfg->ip = NULL;
9095
9096         /* resolve backward branches in the middle of an existing basic block */
9097         for (tmp = bb_recheck; tmp; tmp = tmp->next) {
9098                 bblock = tmp->data;
9099                 /*g_print ("need recheck in %s at IL_%04x\n", method->name, bblock->cil_code - header->code);*/
9100                 tblock = find_previous (cfg->cil_offset_to_bb, header->code_size, start_bblock, bblock->cil_code);
9101                 if (tblock != start_bblock) {
9102                         int l;
9103                         split_bblock (cfg, tblock, bblock);
9104                         l = bblock->cil_code - header->code;
9105                         bblock->cil_length = tblock->cil_length - l;
9106                         tblock->cil_length = l;
9107                 } else {
9108                         g_print ("recheck failed.\n");
9109                 }
9110         }
9111
9112         if (cfg->method == method) {
9113                 MonoBasicBlock *bb;
9114                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
9115                         bb->region = mono_find_block_region (cfg, bb->real_offset);
9116                         if (cfg->spvars)
9117                                 mono_create_spvar_for_region (cfg, bb->region);
9118                         if (cfg->verbose_level > 2)
9119                                 g_print ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
9120                 }
9121         }
9122
9123         g_slist_free (class_inits);
9124         dont_inline = g_list_remove (dont_inline, method);
9125
9126         if (inline_costs < 0) {
9127                 char *mname;
9128
9129                 /* Method is too large */
9130                 mname = mono_method_full_name (method, TRUE);
9131                 cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
9132                 cfg->exception_message = g_strdup_printf ("Method %s is too complex.", mname);
9133                 g_free (mname);
9134                 return -1;
9135         }
9136
9137         return inline_costs;
9138
9139  exception_exit:
9140         g_assert (cfg->exception_type != MONO_EXCEPTION_NONE);
9141         g_slist_free (class_inits);
9142         dont_inline = g_list_remove (dont_inline, method);
9143         return -1;
9144
9145  inline_failure:
9146         g_slist_free (class_inits);
9147         dont_inline = g_list_remove (dont_inline, method);
9148         return -1;
9149
9150  load_error:
9151         g_slist_free (class_inits);
9152         dont_inline = g_list_remove (dont_inline, method);
9153         cfg->exception_type = MONO_EXCEPTION_TYPE_LOAD;
9154         return -1;
9155
9156  unverified:
9157         g_slist_free (class_inits);
9158         dont_inline = g_list_remove (dont_inline, method);
9159         set_exception_type_from_invalid_il (cfg, method, ip);
9160         return -1;
9161 }
9162
9163 void
9164 mono_print_tree (MonoInst *tree) {
9165         int arity;
9166
9167         if (!tree)
9168                 return;
9169
9170         arity = mono_burg_arity [tree->opcode];
9171
9172         printf (" %s%s", arity?"(":"",  mono_inst_name (tree->opcode));
9173
9174         switch (tree->opcode) {
9175         case OP_ICONST:
9176                 printf ("[%d]", (int)tree->inst_c0);
9177                 break;
9178         case OP_I8CONST:
9179                 printf ("[%lld]", (long long)tree->inst_l);
9180                 break;
9181         case OP_R8CONST:
9182                 printf ("[%f]", *(double*)tree->inst_p0);
9183                 break;
9184         case OP_R4CONST:
9185                 printf ("[%f]", *(float*)tree->inst_p0);
9186                 break;
9187         case OP_ARG:
9188         case OP_LOCAL:
9189                 printf ("[%d]", (int)tree->inst_c0);
9190                 break;
9191         case OP_REGOFFSET:
9192                 if (tree->inst_offset < 0)
9193                         printf ("[-0x%x(%s)]", (int)(-tree->inst_offset), mono_arch_regname (tree->inst_basereg));
9194                 else
9195                         printf ("[0x%x(%s)]", (int)(tree->inst_offset), mono_arch_regname (tree->inst_basereg));
9196                 break;
9197         case OP_REGVAR:
9198                 printf ("[%s]", mono_arch_regname (tree->dreg));
9199                 break;
9200         case CEE_NEWARR:
9201                 printf ("[%s]",  tree->inst_newa_class->name);
9202                 mono_print_tree (tree->inst_newa_len);
9203                 break;
9204         case OP_CALL:
9205         case OP_CALLVIRT:
9206         case OP_FCALL:
9207         case OP_FCALLVIRT:
9208         case OP_LCALL:
9209         case OP_LCALLVIRT:
9210         case OP_VCALL:
9211         case OP_VCALLVIRT:
9212         case OP_VOIDCALL:
9213         case OP_VOIDCALLVIRT:
9214         case OP_TRAMPCALL_VTABLE: {
9215                 MonoCallInst *call = (MonoCallInst*)tree;
9216                 if (call->method)
9217                         printf ("[%s]", call->method->name);
9218                 else if (call->fptr) {
9219                         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (call->fptr);
9220                         if (info)
9221                                 printf ("[%s]", info->name);
9222                 }
9223                 break;
9224         }
9225         case OP_PHI: {
9226                 int i;
9227                 printf ("[%d (", (int)tree->inst_c0);
9228                 for (i = 0; i < tree->inst_phi_args [0]; i++) {
9229                         if (i)
9230                                 printf (", ");
9231                         printf ("%d", tree->inst_phi_args [i + 1]);
9232                 }
9233                 printf (")]");
9234                 break;
9235         }
9236         case OP_RENAME:
9237         case OP_RETARG:
9238         case OP_NOP:
9239         case OP_JMP:
9240         case OP_BREAK:
9241                 break;
9242         case OP_LOAD_MEMBASE:
9243         case OP_LOADI4_MEMBASE:
9244         case OP_LOADU4_MEMBASE:
9245         case OP_LOADU1_MEMBASE:
9246         case OP_LOADI1_MEMBASE:
9247         case OP_LOADU2_MEMBASE:
9248         case OP_LOADI2_MEMBASE:
9249                 printf ("[%s] <- [%s + 0x%x]", mono_arch_regname (tree->dreg), mono_arch_regname (tree->inst_basereg), (int)tree->inst_offset);
9250                 break;
9251         case OP_BR:
9252         case OP_CALL_HANDLER:
9253                 printf ("[B%d]", tree->inst_target_bb->block_num);
9254                 break;
9255         case OP_SWITCH:
9256         case CEE_ISINST:
9257         case CEE_CASTCLASS:
9258         case OP_OUTARG:
9259         case OP_CALL_REG:
9260         case OP_FCALL_REG:
9261         case OP_LCALL_REG:
9262         case OP_VCALL_REG:
9263         case OP_VOIDCALL_REG:
9264                 mono_print_tree (tree->inst_left);
9265                 break;
9266         case CEE_BNE_UN:
9267         case CEE_BEQ:
9268         case CEE_BLT:
9269         case CEE_BLT_UN:
9270         case CEE_BGT:
9271         case CEE_BGT_UN:
9272         case CEE_BGE:
9273         case CEE_BGE_UN:
9274         case CEE_BLE:
9275         case CEE_BLE_UN:
9276                 printf ("[B%dB%d]", tree->inst_true_bb->block_num, tree->inst_false_bb->block_num);
9277                 mono_print_tree (tree->inst_left);
9278                 break;
9279         default:
9280                 if (!mono_arch_print_tree(tree, arity)) {
9281                         if (arity) {
9282                                 mono_print_tree (tree->inst_left);
9283                                 if (arity > 1)
9284                                         mono_print_tree (tree->inst_right);
9285                         }
9286                 }
9287                 break;
9288         }
9289
9290         if (arity)
9291                 printf (")");
9292 }
9293
9294 void
9295 mono_print_tree_nl (MonoInst *tree)
9296 {
9297         mono_print_tree (tree);
9298         printf ("\n");
9299 }
9300
9301 static void
9302 create_helper_signature (void)
9303 {
9304         helper_sig_domain_get = mono_create_icall_signature ("ptr");
9305         helper_sig_class_init_trampoline = mono_create_icall_signature ("void");
9306         helper_sig_generic_class_init_trampoline = mono_create_icall_signature ("void");
9307         helper_sig_rgctx_lazy_fetch_trampoline = mono_create_icall_signature ("ptr ptr");
9308 }
9309
9310 gconstpointer
9311 mono_icall_get_wrapper (MonoJitICallInfo* callinfo)
9312 {
9313         char *name;
9314         MonoMethod *wrapper;
9315         gconstpointer trampoline;
9316         MonoDomain *domain = mono_get_root_domain ();
9317         
9318         if (callinfo->wrapper) {
9319                 return callinfo->wrapper;
9320         }
9321
9322         if (callinfo->trampoline)
9323                 return callinfo->trampoline;
9324
9325         /* 
9326          * We use the lock on the root domain instead of the JIT lock to protect 
9327          * callinfo->trampoline, since we do a lot of stuff inside the critical section.
9328          */
9329         mono_domain_lock (domain);
9330
9331         if (callinfo->trampoline) {
9332                 mono_domain_unlock (domain);
9333                 return callinfo->trampoline;
9334         }
9335
9336         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
9337         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
9338         g_free (name);
9339
9340         trampoline = mono_create_ftnptr (domain, mono_create_jit_trampoline_in_domain (domain, wrapper));
9341         mono_register_jit_icall_wrapper (callinfo, trampoline);
9342
9343         callinfo->trampoline = trampoline;
9344
9345         mono_domain_unlock (domain);
9346         
9347         return callinfo->trampoline;
9348 }
9349
9350 static void
9351 mono_dynamic_code_hash_insert (MonoDomain *domain, MonoMethod *method, MonoJitDynamicMethodInfo *ji)
9352 {
9353         if (!domain->dynamic_code_hash)
9354                 domain->dynamic_code_hash = g_hash_table_new (NULL, NULL);
9355         g_hash_table_insert (domain->dynamic_code_hash, method, ji);
9356 }
9357
9358 static MonoJitDynamicMethodInfo*
9359 mono_dynamic_code_hash_lookup (MonoDomain *domain, MonoMethod *method)
9360 {
9361         MonoJitDynamicMethodInfo *res;
9362
9363         if (domain->dynamic_code_hash)
9364                 res = g_hash_table_lookup (domain->dynamic_code_hash, method);
9365         else
9366                 res = NULL;
9367         return res;
9368 }
9369
9370 typedef struct {
9371         MonoClass *vtype;
9372         GList *active;
9373         GSList *slots;
9374 } StackSlotInfo;
9375
9376 static inline GSList*
9377 g_slist_prepend_mempool (MonoMemPool *mp, GSList   *list,
9378                                                  gpointer  data)
9379 {
9380   GSList *new_list;
9381
9382   new_list = mono_mempool_alloc (mp, sizeof (GSList));
9383   new_list->data = data;
9384   new_list->next = list;
9385
9386   return new_list;
9387 }
9388
9389 /*
9390  *  mono_allocate_stack_slots_full:
9391  *
9392  *  Allocate stack slots for all non register allocated variables using a
9393  * linear scan algorithm.
9394  * Returns: an array of stack offsets.
9395  * STACK_SIZE is set to the amount of stack space needed.
9396  * STACK_ALIGN is set to the alignment needed by the locals area.
9397  */
9398 gint32*
9399 mono_allocate_stack_slots_full (MonoCompile *cfg, gboolean backward, guint32 *stack_size, guint32 *stack_align)
9400 {
9401         int i, slot, offset, size;
9402         guint32 align;
9403         MonoMethodVar *vmv;
9404         MonoInst *inst;
9405         gint32 *offsets;
9406         GList *vars = NULL, *l;
9407         StackSlotInfo *scalar_stack_slots, *vtype_stack_slots, *slot_info;
9408         MonoType *t;
9409         int nvtypes;
9410
9411         scalar_stack_slots = mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * MONO_TYPE_PINNED);
9412         vtype_stack_slots = NULL;
9413         nvtypes = 0;
9414
9415         offsets = mono_mempool_alloc (cfg->mempool, sizeof (gint32) * cfg->num_varinfo);
9416         for (i = 0; i < cfg->num_varinfo; ++i)
9417                 offsets [i] = -1;
9418
9419         for (i = cfg->locals_start; i < cfg->num_varinfo; i++) {
9420                 inst = cfg->varinfo [i];
9421                 vmv = MONO_VARINFO (cfg, i);
9422
9423                 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR || inst->opcode == OP_REGOFFSET)
9424                         continue;
9425
9426                 vars = g_list_prepend (vars, vmv);
9427         }
9428
9429         vars = mono_varlist_sort (cfg, vars, 0);
9430         offset = 0;
9431         *stack_align = 0;
9432         for (l = vars; l; l = l->next) {
9433                 vmv = l->data;
9434                 inst = cfg->varinfo [vmv->idx];
9435
9436                 /* inst->backend.is_pinvoke indicates native sized value types, this is used by the
9437                 * pinvoke wrappers when they call functions returning structures */
9438                 if (inst->backend.is_pinvoke && MONO_TYPE_ISSTRUCT (inst->inst_vtype) && inst->inst_vtype->type != MONO_TYPE_TYPEDBYREF)
9439                         size = mono_class_native_size (inst->inst_vtype->data.klass, &align);
9440                 else {
9441                         int ialign;
9442
9443                         size = mono_type_size (inst->inst_vtype, &ialign);
9444                         align = ialign;
9445                 }
9446
9447                 t = mono_type_get_underlying_type (inst->inst_vtype);
9448                 if (t->byref) {
9449                         slot_info = &scalar_stack_slots [MONO_TYPE_I];
9450                 } else {
9451                         switch (t->type) {
9452                         case MONO_TYPE_GENERICINST:
9453                                 if (!mono_type_generic_inst_is_valuetype (t)) {
9454                                         slot_info = &scalar_stack_slots [t->type];
9455                                         break;
9456                                 }
9457                                 /* Fall through */
9458                         case MONO_TYPE_VALUETYPE:
9459                                 if (!vtype_stack_slots)
9460                                         vtype_stack_slots = mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * 256);
9461                                 for (i = 0; i < nvtypes; ++i)
9462                                         if (t->data.klass == vtype_stack_slots [i].vtype)
9463                                                 break;
9464                                 if (i < nvtypes)
9465                                         slot_info = &vtype_stack_slots [i];
9466                                 else {
9467                                         g_assert (nvtypes < 256);
9468                                         vtype_stack_slots [nvtypes].vtype = t->data.klass;
9469                                         slot_info = &vtype_stack_slots [nvtypes];
9470                                         nvtypes ++;
9471                                 }
9472                                 break;
9473                         case MONO_TYPE_CLASS:
9474                         case MONO_TYPE_OBJECT:
9475                         case MONO_TYPE_ARRAY:
9476                         case MONO_TYPE_SZARRAY:
9477                         case MONO_TYPE_STRING:
9478                         case MONO_TYPE_PTR:
9479                         case MONO_TYPE_I:
9480                         case MONO_TYPE_U:
9481 #if SIZEOF_VOID_P == 4
9482                         case MONO_TYPE_I4:
9483 #else
9484                         case MONO_TYPE_I8:
9485 #endif
9486                                 /* Share non-float stack slots of the same size */
9487                                 slot_info = &scalar_stack_slots [MONO_TYPE_CLASS];
9488                                 break;
9489                         default:
9490                                 slot_info = &scalar_stack_slots [t->type];
9491                         }
9492                 }
9493
9494                 slot = 0xffffff;
9495                 if (cfg->comp_done & MONO_COMP_LIVENESS) {
9496                         //printf ("START  %2d %08x %08x\n",  vmv->idx, vmv->range.first_use.abs_pos, vmv->range.last_use.abs_pos);
9497                         
9498                         /* expire old intervals in active */
9499                         while (slot_info->active) {
9500                                 MonoMethodVar *amv = (MonoMethodVar *)slot_info->active->data;
9501
9502                                 if (amv->range.last_use.abs_pos > vmv->range.first_use.abs_pos)
9503                                         break;
9504
9505                                 //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);
9506
9507                                 slot_info->active = g_list_delete_link (slot_info->active, slot_info->active);
9508                                 slot_info->slots = g_slist_prepend_mempool (cfg->mempool, slot_info->slots, GINT_TO_POINTER (offsets [amv->idx]));
9509                         }
9510
9511                         /* 
9512                          * This also handles the case when the variable is used in an
9513                          * exception region, as liveness info is not computed there.
9514                          */
9515                         /* 
9516                          * FIXME: All valuetypes are marked as INDIRECT because of LDADDR
9517                          * opcodes.
9518                          */
9519                         if (! (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
9520                                 if (slot_info->slots) {
9521                                         slot = GPOINTER_TO_INT (slot_info->slots->data);
9522
9523                                         slot_info->slots = slot_info->slots->next;
9524                                 }
9525
9526                                 slot_info->active = mono_varlist_insert_sorted (cfg, slot_info->active, vmv, TRUE);
9527                         }
9528                 }
9529
9530                 {
9531                         static int count = 0;
9532                         count ++;
9533
9534                         /*
9535                         if (count == atoi (getenv ("COUNT")))
9536                                 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
9537                         if (count > atoi (getenv ("COUNT")))
9538                                 slot = 0xffffff;
9539                         else {
9540                                 mono_print_tree_nl (inst);
9541                                 }
9542                         */
9543                 }
9544
9545                 if (cfg->disable_reuse_stack_slots)
9546                         slot = 0xffffff;
9547
9548                 if (slot == 0xffffff) {
9549                         /*
9550                          * Allways allocate valuetypes to sizeof (gpointer) to allow more
9551                          * efficient copying (and to work around the fact that OP_MEMCPY
9552                          * and OP_MEMSET ignores alignment).
9553                          */
9554                         if (MONO_TYPE_ISSTRUCT (t))
9555                                 align = sizeof (gpointer);
9556
9557                         if (backward) {
9558                                 offset += size;
9559                                 offset += align - 1;
9560                                 offset &= ~(align - 1);
9561                                 slot = offset;
9562                         }
9563                         else {
9564                                 offset += align - 1;
9565                                 offset &= ~(align - 1);
9566                                 slot = offset;
9567                                 offset += size;
9568                         }
9569
9570                         if (*stack_align == 0)
9571                                 *stack_align = align;
9572                 }
9573
9574                 offsets [vmv->idx] = slot;
9575         }
9576         g_list_free (vars);
9577         for (i = 0; i < MONO_TYPE_PINNED; ++i) {
9578                 if (scalar_stack_slots [i].active)
9579                         g_list_free (scalar_stack_slots [i].active);
9580         }
9581         for (i = 0; i < nvtypes; ++i) {
9582                 if (vtype_stack_slots [i].active)
9583                         g_list_free (vtype_stack_slots [i].active);
9584         }
9585
9586         mono_jit_stats.locals_stack_size += offset;
9587
9588         *stack_size = offset;
9589         return offsets;
9590 }
9591
9592 gint32*
9593 mono_allocate_stack_slots (MonoCompile *m, guint32 *stack_size, guint32 *stack_align)
9594 {
9595         return mono_allocate_stack_slots_full (m, TRUE, stack_size, stack_align);
9596 }
9597
9598 void
9599 mono_register_opcode_emulation (int opcode, const char *name, const char *sigstr, gpointer func, gboolean no_throw)
9600 {
9601         MonoJitICallInfo *info;
9602         MonoMethodSignature *sig = mono_create_icall_signature (sigstr);
9603
9604         if (!emul_opcode_map)
9605                 emul_opcode_map = g_new0 (MonoJitICallInfo*, OP_LAST + 1);
9606
9607         g_assert (!sig->hasthis);
9608         g_assert (sig->param_count < 3);
9609
9610         info = mono_register_jit_icall (func, name, sig, no_throw);
9611
9612         emul_opcode_map [opcode] = info;
9613 }
9614
9615 static void
9616 register_icall (gpointer func, const char *name, const char *sigstr, gboolean save)
9617 {
9618         MonoMethodSignature *sig;
9619
9620         if (sigstr)
9621                 sig = mono_create_icall_signature (sigstr);
9622         else
9623                 sig = NULL;
9624
9625         mono_register_jit_icall (func, name, sig, save);
9626 }
9627
9628 static void
9629 decompose_foreach (MonoInst *tree, gpointer data) 
9630 {
9631         static MonoJitICallInfo *newarr_info = NULL;
9632         static MonoJitICallInfo *newarr_specific_info = NULL;
9633         MonoJitICallInfo *info;
9634         int i;
9635
9636         switch (tree->opcode) {
9637         case CEE_NEWARR: {
9638                 MonoCompile *cfg = data;
9639                 MonoInst *iargs [3];
9640
9641                 if (!newarr_info) {
9642                         newarr_info = mono_find_jit_icall_by_addr (mono_array_new);
9643                         g_assert (newarr_info);
9644                         newarr_specific_info = mono_find_jit_icall_by_addr (mono_array_new_specific);
9645                         g_assert (newarr_specific_info);
9646                 }
9647
9648                 if (cfg->opt & MONO_OPT_SHARED) {
9649                         NEW_DOMAINCONST (cfg, iargs [0]);
9650                         NEW_CLASSCONST (cfg, iargs [1], tree->inst_newa_class);
9651                         iargs [2] = tree->inst_newa_len;
9652
9653                         info = newarr_info;
9654                 }
9655                 else {
9656                         MonoVTable *vtable = mono_class_vtable (cfg->domain, mono_array_class_get (tree->inst_newa_class, 1));
9657
9658                         NEW_VTABLECONST (cfg, iargs [0], vtable);
9659                         iargs [1] = tree->inst_newa_len;
9660
9661                         info = newarr_specific_info;
9662                 }
9663
9664                 mono_emulate_opcode (cfg, tree, iargs, info);
9665
9666                 /* Need to decompose arguments after the the opcode is decomposed */
9667                 for (i = 0; i < info->sig->param_count; ++i)
9668                         dec_foreach (iargs [i], cfg);
9669                 break;
9670         }
9671 #ifdef MONO_ARCH_SOFT_FLOAT
9672         case OP_FBEQ:
9673         case OP_FBGE:
9674         case OP_FBGT:
9675         case OP_FBLE:
9676         case OP_FBLT:
9677         case OP_FBNE_UN:
9678         case OP_FBGE_UN:
9679         case OP_FBGT_UN:
9680         case OP_FBLE_UN:
9681         case OP_FBLT_UN: {
9682                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
9683                         MonoCompile *cfg = data;
9684                         MonoInst *iargs [2];
9685                 
9686                         iargs [0] = tree->inst_i0;
9687                         iargs [1] = tree->inst_i1;
9688                 
9689                         mono_emulate_opcode (cfg, tree, iargs, info);
9690
9691                         dec_foreach (iargs [0], cfg);
9692                         dec_foreach (iargs [1], cfg);
9693                         break;
9694                 } else {
9695                         g_assert_not_reached ();
9696                 }
9697                 break;
9698         }
9699         case OP_FCEQ:
9700         case OP_FCGT:
9701         case OP_FCGT_UN:
9702         case OP_FCLT:
9703         case OP_FCLT_UN: {
9704                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
9705                         MonoCompile *cfg = data;
9706                         MonoInst *iargs [2];
9707
9708                         /* the args are in the compare opcode ... */
9709                         iargs [0] = tree->inst_i0;
9710                         iargs [1] = tree->inst_i1;
9711                 
9712                         mono_emulate_opcode (cfg, tree, iargs, info);
9713
9714                         dec_foreach (iargs [0], cfg);
9715                         dec_foreach (iargs [1], cfg);
9716                         break;
9717                 } else {
9718                         g_assert_not_reached ();
9719                 }
9720                 break;
9721         }
9722 #endif
9723
9724         default:
9725                 break;
9726         }
9727 }
9728
9729 void
9730 mono_inst_foreach (MonoInst *tree, MonoInstFunc func, gpointer data) {
9731
9732         switch (mono_burg_arity [tree->opcode]) {
9733         case 0: break;
9734         case 1: 
9735                 mono_inst_foreach (tree->inst_left, func, data);
9736                 break;
9737         case 2: 
9738                 mono_inst_foreach (tree->inst_left, func, data);
9739                 mono_inst_foreach (tree->inst_right, func, data);
9740                 break;
9741         default:
9742                 g_assert_not_reached ();
9743         }
9744         func (tree, data);
9745 }
9746
9747 G_GNUC_UNUSED
9748 static void
9749 mono_print_bb_code (MonoBasicBlock *bb)
9750 {
9751         MonoInst *c;
9752
9753         MONO_BB_FOR_EACH_INS (bb, c) {
9754                 mono_print_tree (c);
9755                 g_print ("\n");
9756         }
9757 }
9758
9759 static void
9760 print_dfn (MonoCompile *cfg) {
9761         int i, j;
9762         char *code;
9763         MonoBasicBlock *bb;
9764
9765         g_print ("IR code for method %s\n", mono_method_full_name (cfg->method, TRUE));
9766
9767         for (i = 0; i < cfg->num_bblocks; ++i) {
9768                 MonoInst *c;
9769
9770                 bb = cfg->bblocks [i];
9771                 /*if (bb->cil_code) {
9772                         char* code1, *code2;
9773                         code1 = mono_disasm_code_one (NULL, cfg->method, bb->cil_code, NULL);
9774                         if (bb->last_ins->cil_code)
9775                                 code2 = mono_disasm_code_one (NULL, cfg->method, bb->last_ins->cil_code, NULL);
9776                         else
9777                                 code2 = g_strdup ("");
9778
9779                         code1 [strlen (code1) - 1] = 0;
9780                         code = g_strdup_printf ("%s -> %s", code1, code2);
9781                         g_free (code1);
9782                         g_free (code2);
9783                 } else*/
9784                         code = g_strdup ("\n");
9785                 g_print ("\nBB%d DFN%d (len: %d): %s", bb->block_num, i, bb->cil_length, code);
9786                 MONO_BB_FOR_EACH_INS (bb, c) {
9787                         mono_print_tree (c);
9788                         g_print ("\n");
9789                 }
9790
9791                 g_print ("\tprev:");
9792                 for (j = 0; j < bb->in_count; ++j) {
9793                         g_print (" BB%d", bb->in_bb [j]->block_num);
9794                 }
9795                 g_print ("\t\tsucc:");
9796                 for (j = 0; j < bb->out_count; ++j) {
9797                         g_print (" BB%d", bb->out_bb [j]->block_num);
9798                 }
9799                 g_print ("\n\tidom: BB%d\n", bb->idom? bb->idom->block_num: -1);
9800
9801                 if (bb->idom)
9802                         g_assert (mono_bitset_test_fast (bb->dominators, bb->idom->dfn));
9803
9804                 if (bb->dominators)
9805                         mono_blockset_print (cfg, bb->dominators, "\tdominators", bb->idom? bb->idom->dfn: -1);
9806                 if (bb->dfrontier)
9807                         mono_blockset_print (cfg, bb->dfrontier, "\tdfrontier", -1);
9808                 g_free (code);
9809         }
9810
9811         g_print ("\n");
9812 }
9813
9814 void
9815 mono_bblock_add_inst (MonoBasicBlock *bb, MonoInst *inst)
9816 {
9817         MONO_ADD_INS (bb, inst);
9818 }
9819
9820 void
9821 mono_destroy_compile (MonoCompile *cfg)
9822 {
9823         //mono_mempool_stats (cfg->mempool);
9824         mono_free_loop_info (cfg);
9825         if (cfg->rs)
9826                 mono_regstate_free (cfg->rs);
9827         if (cfg->spvars)
9828                 g_hash_table_destroy (cfg->spvars);
9829         if (cfg->exvars)
9830                 g_hash_table_destroy (cfg->exvars);
9831         mono_mempool_destroy (cfg->mempool);
9832         g_list_free (cfg->ldstr_list);
9833         g_hash_table_destroy (cfg->token_info_hash);
9834
9835         g_free (cfg->varinfo);
9836         g_free (cfg->vars);
9837         g_free (cfg->exception_message);
9838         g_free (cfg);
9839 }
9840
9841 #ifdef HAVE_KW_THREAD
9842 static __thread gpointer mono_lmf_addr MONO_TLS_FAST;
9843 #ifdef MONO_ARCH_ENABLE_MONO_LMF_VAR
9844 /* 
9845  * When this is defined, the current lmf is stored in this tls variable instead of in 
9846  * jit_tls->lmf.
9847  */
9848 static __thread gpointer mono_lmf MONO_TLS_FAST;
9849 #endif
9850 #endif
9851
9852 guint32
9853 mono_get_jit_tls_key (void)
9854 {
9855         return mono_jit_tls_id;
9856 }
9857
9858 gint32
9859 mono_get_jit_tls_offset (void)
9860 {
9861 #ifdef HAVE_KW_THREAD
9862         int offset;
9863         MONO_THREAD_VAR_OFFSET (mono_jit_tls, offset);
9864         return offset;
9865 #else
9866         return -1;
9867 #endif
9868 }
9869
9870 gint32
9871 mono_get_lmf_tls_offset (void)
9872 {
9873 #if defined(HAVE_KW_THREAD) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
9874         int offset;
9875         MONO_THREAD_VAR_OFFSET(mono_lmf,offset);
9876         return offset;
9877 #else
9878         return -1;
9879 #endif
9880 }
9881
9882 gint32
9883 mono_get_lmf_addr_tls_offset (void)
9884 {
9885         int offset;
9886         MONO_THREAD_VAR_OFFSET(mono_lmf_addr,offset);
9887         return offset;
9888 }
9889
9890 MonoLMF *
9891 mono_get_lmf (void)
9892 {
9893 #if defined(HAVE_KW_THREAD) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
9894         return mono_lmf;
9895 #else
9896         MonoJitTlsData *jit_tls;
9897
9898         if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
9899                 return jit_tls->lmf;
9900
9901         g_assert_not_reached ();
9902         return NULL;
9903 #endif
9904 }
9905
9906 MonoLMF **
9907 mono_get_lmf_addr (void)
9908 {
9909 #ifdef HAVE_KW_THREAD
9910         return mono_lmf_addr;
9911 #else
9912         MonoJitTlsData *jit_tls;
9913
9914         if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
9915                 return &jit_tls->lmf;
9916
9917         g_assert_not_reached ();
9918         return NULL;
9919 #endif
9920 }
9921
9922 /* Called by native->managed wrappers */
9923 void
9924 mono_jit_thread_attach (MonoDomain *domain)
9925 {
9926 #ifdef HAVE_KW_THREAD
9927         if (!mono_lmf_addr) {
9928                 mono_thread_attach (domain);
9929         }
9930 #else
9931         if (!TlsGetValue (mono_jit_tls_id))
9932                 mono_thread_attach (domain);
9933 #endif
9934         if (mono_domain_get () != domain)
9935                 mono_domain_set (domain, TRUE);
9936 }       
9937
9938 /**
9939  * mono_thread_abort:
9940  * @obj: exception object
9941  *
9942  * abort the thread, print exception information and stack trace
9943  */
9944 static void
9945 mono_thread_abort (MonoObject *obj)
9946 {
9947         /* MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id); */
9948         
9949         /* handle_remove should be eventually called for this thread, too
9950         g_free (jit_tls);*/
9951
9952         if ((mono_runtime_unhandled_exception_policy_get () == MONO_UNHANLED_POLICY_LEGACY) ||
9953                         (obj->vtable->klass == mono_defaults.threadabortexception_class)) {
9954                 mono_thread_exit ();
9955         } else {
9956                 exit (mono_environment_exitcode_get ());
9957         }
9958 }
9959
9960 static void*
9961 setup_jit_tls_data (gpointer stack_start, gpointer abort_func)
9962 {
9963         MonoJitTlsData *jit_tls;
9964         MonoLMF *lmf;
9965
9966         jit_tls = TlsGetValue (mono_jit_tls_id);
9967         if (jit_tls)
9968                 return jit_tls;
9969
9970         jit_tls = g_new0 (MonoJitTlsData, 1);
9971
9972         TlsSetValue (mono_jit_tls_id, jit_tls);
9973
9974 #ifdef HAVE_KW_THREAD
9975         mono_jit_tls = jit_tls;
9976 #endif
9977
9978         jit_tls->abort_func = abort_func;
9979         jit_tls->end_of_stack = stack_start;
9980
9981         lmf = g_new0 (MonoLMF, 1);
9982 #ifdef MONO_ARCH_INIT_TOP_LMF_ENTRY
9983         MONO_ARCH_INIT_TOP_LMF_ENTRY (lmf);
9984 #else
9985         lmf->ebp = -1;
9986 #endif
9987
9988         jit_tls->first_lmf = lmf;
9989
9990 #if defined(HAVE_KW_THREAD) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
9991         /* jit_tls->lmf is unused */
9992         mono_lmf = lmf;
9993         mono_lmf_addr = &mono_lmf;
9994 #else
9995 #if defined(HAVE_KW_THREAD)
9996         mono_lmf_addr = &jit_tls->lmf;  
9997 #endif
9998
9999         jit_tls->lmf = lmf;
10000 #endif
10001
10002         mono_arch_setup_jit_tls_data (jit_tls);
10003         mono_setup_altstack (jit_tls);
10004
10005         return jit_tls;
10006 }
10007
10008 static void
10009 mono_thread_start_cb (gsize tid, gpointer stack_start, gpointer func)
10010 {
10011         MonoThread *thread;
10012         void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort);
10013         thread = mono_thread_current ();
10014         mono_debugger_thread_created (tid, thread, jit_tls);
10015         if (thread)
10016                 thread->jit_data = jit_tls;
10017 }
10018
10019 void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
10020
10021 static void
10022 mono_thread_abort_dummy (MonoObject *obj)
10023 {
10024   if (mono_thread_attach_aborted_cb)
10025     mono_thread_attach_aborted_cb (obj);
10026   else
10027     mono_thread_abort (obj);
10028 }
10029
10030 static void
10031 mono_thread_attach_cb (gsize tid, gpointer stack_start)
10032 {
10033         MonoThread *thread;
10034         void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort_dummy);
10035         thread = mono_thread_current ();
10036         mono_debugger_thread_created (tid, thread, (MonoJitTlsData *) jit_tls);
10037         if (thread)
10038                 thread->jit_data = jit_tls;
10039         if (mono_profiler_get_events () & MONO_PROFILE_STATISTICAL)
10040                 setup_stat_profiler ();
10041 }
10042
10043 static void
10044 mini_thread_cleanup (MonoThread *thread)
10045 {
10046         MonoJitTlsData *jit_tls = thread->jit_data;
10047
10048         if (jit_tls) {
10049                 mono_debugger_thread_cleanup (jit_tls);
10050                 mono_arch_free_jit_tls_data (jit_tls);
10051
10052                 mono_free_altstack (jit_tls);
10053                 g_free (jit_tls->first_lmf);
10054                 g_free (jit_tls);
10055                 thread->jit_data = NULL;
10056                 TlsSetValue (mono_jit_tls_id, NULL);
10057         }
10058 }
10059
10060 static MonoInst*
10061 mono_create_tls_get (MonoCompile *cfg, int offset)
10062 {
10063 #ifdef MONO_ARCH_HAVE_TLS_GET
10064         MonoInst* ins;
10065         
10066         if (offset == -1)
10067                 return NULL;
10068         
10069         MONO_INST_NEW (cfg, ins, OP_TLS_GET);
10070         ins->dreg = mono_regstate_next_int (cfg->rs);
10071         ins->inst_offset = offset;
10072         return ins;
10073 #else
10074         return NULL;
10075 #endif
10076 }
10077
10078 MonoInst*
10079 mono_get_jit_tls_intrinsic (MonoCompile *cfg)
10080 {
10081         return mono_create_tls_get (cfg, mono_get_jit_tls_offset ());
10082 }
10083
10084 void
10085 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
10086 {
10087         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
10088
10089         ji->ip.i = ip;
10090         ji->type = type;
10091         ji->data.target = target;
10092         ji->next = cfg->patch_info;
10093
10094         cfg->patch_info = ji;
10095 }
10096
10097 void
10098 mono_remove_patch_info (MonoCompile *cfg, int ip)
10099 {
10100         MonoJumpInfo **ji = &cfg->patch_info;
10101
10102         while (*ji) {
10103                 if ((*ji)->ip.i == ip)
10104                         *ji = (*ji)->next;
10105                 else
10106                         ji = &((*ji)->next);
10107         }
10108 }
10109
10110 /**
10111  * mono_patch_info_dup_mp:
10112  *
10113  * Make a copy of PATCH_INFO, allocating memory from the mempool MP.
10114  */
10115 MonoJumpInfo*
10116 mono_patch_info_dup_mp (MonoMemPool *mp, MonoJumpInfo *patch_info)
10117 {
10118         MonoJumpInfo *res = mono_mempool_alloc (mp, sizeof (MonoJumpInfo));
10119         memcpy (res, patch_info, sizeof (MonoJumpInfo));
10120
10121         switch (patch_info->type) {
10122         case MONO_PATCH_INFO_RVA:
10123         case MONO_PATCH_INFO_LDSTR:
10124         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
10125         case MONO_PATCH_INFO_LDTOKEN:
10126         case MONO_PATCH_INFO_DECLSEC:
10127                 res->data.token = mono_mempool_alloc (mp, sizeof (MonoJumpInfoToken));
10128                 memcpy (res->data.token, patch_info->data.token, sizeof (MonoJumpInfoToken));
10129                 break;
10130         case MONO_PATCH_INFO_SWITCH:
10131                 res->data.table = mono_mempool_alloc (mp, sizeof (MonoJumpInfoBBTable));
10132                 memcpy (res->data.table, patch_info->data.table, sizeof (MonoJumpInfoBBTable));
10133                 break;
10134         default:
10135                 break;
10136         }
10137
10138         return res;
10139 }
10140
10141 guint
10142 mono_patch_info_hash (gconstpointer data)
10143 {
10144         const MonoJumpInfo *ji = (MonoJumpInfo*)data;
10145
10146         switch (ji->type) {
10147         case MONO_PATCH_INFO_RVA:
10148         case MONO_PATCH_INFO_LDSTR:
10149         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
10150         case MONO_PATCH_INFO_LDTOKEN:
10151         case MONO_PATCH_INFO_DECLSEC:
10152                 return (ji->type << 8) | ji->data.token->token;
10153         case MONO_PATCH_INFO_VTABLE:
10154         case MONO_PATCH_INFO_CLASS:
10155         case MONO_PATCH_INFO_IID:
10156         case MONO_PATCH_INFO_ADJUSTED_IID:
10157                 return (ji->type << 8) | (gssize)ji->data.klass;
10158         case MONO_PATCH_INFO_FIELD:
10159         case MONO_PATCH_INFO_SFLDA:
10160                 return (ji->type << 8) | (gssize)ji->data.field;
10161         case MONO_PATCH_INFO_METHODCONST:
10162         case MONO_PATCH_INFO_METHOD:
10163         case MONO_PATCH_INFO_METHOD_JUMP:
10164                 return (ji->type << 8) | (gssize)ji->data.method;
10165         case MONO_PATCH_INFO_IMAGE:
10166                 return (ji->type << 8) | (gssize)ji->data.image;                
10167         default:
10168                 return (ji->type << 8);
10169         }
10170 }
10171
10172 /* 
10173  * mono_patch_info_equal:
10174  * 
10175  * This might fail to recognize equivalent patches, i.e. floats, so its only
10176  * usable in those cases where this is not a problem, i.e. sharing GOT slots
10177  * in AOT.
10178  */
10179 gint
10180 mono_patch_info_equal (gconstpointer ka, gconstpointer kb)
10181 {
10182         const MonoJumpInfo *ji1 = (MonoJumpInfo*)ka;
10183         const MonoJumpInfo *ji2 = (MonoJumpInfo*)kb;
10184
10185         if (ji1->type != ji2->type)
10186                 return 0;
10187
10188         switch (ji1->type) {
10189         case MONO_PATCH_INFO_RVA:
10190         case MONO_PATCH_INFO_LDSTR:
10191         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
10192         case MONO_PATCH_INFO_LDTOKEN:
10193         case MONO_PATCH_INFO_DECLSEC:
10194                 if ((ji1->data.token->image != ji2->data.token->image) ||
10195                         (ji1->data.token->token != ji2->data.token->token))
10196                         return 0;
10197                 break;
10198         default:
10199                 if (ji1->data.name != ji2->data.name)
10200                         return 0;
10201                 break;
10202         }
10203
10204         return 1;
10205 }
10206
10207 gpointer
10208 mono_resolve_patch_target (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors)
10209 {
10210         unsigned char *ip = patch_info->ip.i + code;
10211         gconstpointer target = NULL;
10212
10213         switch (patch_info->type) {
10214         case MONO_PATCH_INFO_BB:
10215                 target = patch_info->data.bb->native_offset + code;
10216                 break;
10217         case MONO_PATCH_INFO_ABS:
10218                 target = patch_info->data.target;
10219                 break;
10220         case MONO_PATCH_INFO_LABEL:
10221                 target = patch_info->data.inst->inst_c0 + code;
10222                 break;
10223         case MONO_PATCH_INFO_IP:
10224                 target = ip;
10225                 break;
10226         case MONO_PATCH_INFO_METHOD_REL:
10227                 target = code + patch_info->data.offset;
10228                 break;
10229         case MONO_PATCH_INFO_INTERNAL_METHOD: {
10230                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
10231                 if (!mi) {
10232                         g_warning ("unknown MONO_PATCH_INFO_INTERNAL_METHOD %s", patch_info->data.name);
10233                         g_assert_not_reached ();
10234                 }
10235                 target = mono_icall_get_wrapper (mi);
10236                 break;
10237         }
10238         case MONO_PATCH_INFO_METHOD_JUMP: {
10239                 GSList *list;
10240
10241                 /* get the trampoline to the method from the domain */
10242                 target = mono_create_jump_trampoline (domain, patch_info->data.method, TRUE);
10243                 if (!domain->jump_target_hash)
10244                         domain->jump_target_hash = g_hash_table_new (NULL, NULL);
10245                 list = g_hash_table_lookup (domain->jump_target_hash, patch_info->data.method);
10246                 list = g_slist_prepend (list, ip);
10247                 g_hash_table_insert (domain->jump_target_hash, patch_info->data.method, list);
10248                 break;
10249         }
10250         case MONO_PATCH_INFO_METHOD:
10251                 if (patch_info->data.method == method) {
10252                         target = code;
10253                 } else {
10254                         /* get the trampoline to the method from the domain */
10255                         if (method && method->wrapper_type == MONO_WRAPPER_STATIC_RGCTX_INVOKE)
10256                                 target = mono_ldftn_nosync (patch_info->data.method);
10257                         else
10258                                 target = mono_create_jit_trampoline (patch_info->data.method);
10259                 }
10260                 break;
10261         case MONO_PATCH_INFO_SWITCH: {
10262                 gpointer *jump_table;
10263                 int i;
10264
10265                 if (method && method->dynamic) {
10266                         jump_table = mono_code_manager_reserve (mono_dynamic_code_hash_lookup (domain, method)->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
10267                 } else {
10268                         mono_domain_lock (domain);
10269                         jump_table = mono_code_manager_reserve (domain->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
10270                         mono_domain_unlock (domain);
10271                 }
10272
10273                 for (i = 0; i < patch_info->data.table->table_size; i++) {
10274                         jump_table [i] = code + GPOINTER_TO_INT (patch_info->data.table->table [i]);
10275                 }
10276                 target = jump_table;
10277                 break;
10278         }
10279         case MONO_PATCH_INFO_METHODCONST:
10280         case MONO_PATCH_INFO_CLASS:
10281         case MONO_PATCH_INFO_IMAGE:
10282         case MONO_PATCH_INFO_FIELD:
10283                 target = patch_info->data.target;
10284                 break;
10285         case MONO_PATCH_INFO_IID:
10286                 mono_class_init (patch_info->data.klass);
10287                 target = GINT_TO_POINTER ((int)patch_info->data.klass->interface_id);
10288                 break;
10289         case MONO_PATCH_INFO_ADJUSTED_IID:
10290                 mono_class_init (patch_info->data.klass);
10291                 target = GINT_TO_POINTER ((int)(-((patch_info->data.klass->interface_id + 1) * SIZEOF_VOID_P)));
10292                 break;
10293         case MONO_PATCH_INFO_VTABLE:
10294                 target = mono_class_vtable (domain, patch_info->data.klass);
10295                 break;
10296         case MONO_PATCH_INFO_CLASS_INIT:
10297                 target = mono_create_class_init_trampoline (mono_class_vtable (domain, patch_info->data.klass));
10298                 break;
10299         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
10300                 target = mono_create_delegate_trampoline (patch_info->data.klass);
10301                 break;
10302         case MONO_PATCH_INFO_SFLDA: {
10303                 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.field->parent);
10304                 if (!vtable->initialized && !(vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) && (method && mono_class_needs_cctor_run (vtable->klass, method)))
10305                         /* Done by the generated code */
10306                         ;
10307                 else {
10308                         if (run_cctors)
10309                                 mono_runtime_class_init (vtable);
10310                 }
10311                 target = (char*)vtable->data + patch_info->data.field->offset;
10312                 break;
10313         }
10314         case MONO_PATCH_INFO_RVA:
10315                 target = mono_image_rva_map (patch_info->data.token->image, patch_info->data.token->token);
10316                 break;
10317         case MONO_PATCH_INFO_R4:
10318         case MONO_PATCH_INFO_R8:
10319                 target = patch_info->data.target;
10320                 break;
10321         case MONO_PATCH_INFO_EXC_NAME:
10322                 target = patch_info->data.name;
10323                 break;
10324         case MONO_PATCH_INFO_LDSTR:
10325                 target =
10326                         mono_ldstr (domain, patch_info->data.token->image, 
10327                                                 mono_metadata_token_index (patch_info->data.token->token));
10328                 break;
10329         case MONO_PATCH_INFO_TYPE_FROM_HANDLE: {
10330                 gpointer handle;
10331                 MonoClass *handle_class;
10332
10333                 handle = mono_ldtoken (patch_info->data.token->image, 
10334                                        patch_info->data.token->token, &handle_class, NULL);
10335                 mono_class_init (handle_class);
10336                 mono_class_init (mono_class_from_mono_type (handle));
10337
10338                 target =
10339                         mono_type_get_object (domain, handle);
10340                 break;
10341         }
10342         case MONO_PATCH_INFO_LDTOKEN: {
10343                 gpointer handle;
10344                 MonoClass *handle_class;
10345                 
10346                 handle = mono_ldtoken (patch_info->data.token->image,
10347                                        patch_info->data.token->token, &handle_class, NULL);
10348                 mono_class_init (handle_class);
10349                 
10350                 target = handle;
10351                 break;
10352         }
10353         case MONO_PATCH_INFO_DECLSEC:
10354                 target = (mono_metadata_blob_heap (patch_info->data.token->image, patch_info->data.token->token) + 2);
10355                 break;
10356         case MONO_PATCH_INFO_ICALL_ADDR:
10357                 target = mono_lookup_internal_call (patch_info->data.method);
10358                 break;
10359         case MONO_PATCH_INFO_BB_OVF:
10360         case MONO_PATCH_INFO_EXC_OVF:
10361         case MONO_PATCH_INFO_GOT_OFFSET:
10362         case MONO_PATCH_INFO_NONE:
10363                 break;
10364         default:
10365                 g_assert_not_reached ();
10366         }
10367
10368         return (gpointer)target;
10369 }
10370
10371 static void
10372 dec_foreach (MonoInst *tree, MonoCompile *cfg) {
10373         MonoJitICallInfo *info;
10374
10375         decompose_foreach (tree, cfg);
10376
10377         switch (mono_burg_arity [tree->opcode]) {
10378         case 0: break;
10379         case 1: 
10380                 dec_foreach (tree->inst_left, cfg);
10381
10382                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
10383                         MonoInst *iargs [2];
10384                 
10385                         iargs [0] = tree->inst_left;
10386
10387                         mono_emulate_opcode (cfg, tree, iargs, info);
10388                         return;
10389                 }
10390
10391                 break;
10392         case 2:
10393 #ifdef MONO_ARCH_BIGMUL_INTRINS
10394                 if (tree->opcode == OP_LMUL
10395                                 && (cfg->opt & MONO_OPT_INTRINS)
10396                                 && (tree->inst_left->opcode == CEE_CONV_I8 
10397                                         || tree->inst_left->opcode == CEE_CONV_U8)
10398                                 && tree->inst_left->inst_left->type == STACK_I4
10399                                 && (tree->inst_right->opcode == CEE_CONV_I8 
10400                                         || tree->inst_right->opcode == CEE_CONV_U8)
10401                                 && tree->inst_right->inst_left->type == STACK_I4
10402                                 && tree->inst_left->opcode == tree->inst_right->opcode) {
10403                         tree->opcode = (tree->inst_left->opcode == CEE_CONV_I8 ? OP_BIGMUL: OP_BIGMUL_UN);
10404                         tree->inst_left = tree->inst_left->inst_left;
10405                         tree->inst_right = tree->inst_right->inst_left;
10406                         dec_foreach (tree, cfg);
10407                 } else 
10408 #endif
10409                         if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
10410                         MonoInst *iargs [2];
10411                 
10412                         iargs [0] = tree->inst_i0;
10413                         iargs [1] = tree->inst_i1;
10414                 
10415                         mono_emulate_opcode (cfg, tree, iargs, info);
10416
10417                         dec_foreach (iargs [0], cfg);
10418                         dec_foreach (iargs [1], cfg);
10419                         return;
10420                 } else {
10421                         dec_foreach (tree->inst_left, cfg);
10422                         dec_foreach (tree->inst_right, cfg);
10423                 }
10424                 break;
10425         default:
10426                 g_assert_not_reached ();
10427         }
10428 }
10429
10430 static void
10431 decompose_pass (MonoCompile *cfg) {
10432         MonoBasicBlock *bb;
10433
10434         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
10435                 MonoInst *tree;
10436                 cfg->cbb = bb;
10437                 cfg->prev_ins = NULL;
10438                 MONO_BB_FOR_EACH_INS (cfg->cbb, tree) {
10439                         dec_foreach (tree, cfg);
10440                         cfg->prev_ins = tree;
10441                 }
10442         }
10443 }
10444
10445 static void
10446 nullify_basic_block (MonoBasicBlock *bb) 
10447 {
10448         bb->in_count = 0;
10449         bb->out_count = 0;
10450         bb->in_bb = NULL;
10451         bb->out_bb = NULL;
10452         bb->next_bb = NULL;
10453         MONO_INST_LIST_INIT (&bb->ins_list);
10454         bb->cil_code = NULL;
10455 }
10456
10457 static void 
10458 replace_out_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
10459 {
10460         int i;
10461
10462         for (i = 0; i < bb->out_count; i++) {
10463                 MonoBasicBlock *ob = bb->out_bb [i];
10464                 if (ob == orig) {
10465                         if (!repl) {
10466                                 if (bb->out_count > 1) {
10467                                         bb->out_bb [i] = bb->out_bb [bb->out_count - 1];
10468                                 }
10469                                 bb->out_count--;
10470                         } else {
10471                                 bb->out_bb [i] = repl;
10472                         }
10473                 }
10474         }
10475 }
10476
10477 static void 
10478 replace_in_block (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl)
10479 {
10480         int i;
10481
10482         for (i = 0; i < bb->in_count; i++) {
10483                 MonoBasicBlock *ib = bb->in_bb [i];
10484                 if (ib == orig) {
10485                         if (!repl) {
10486                                 if (bb->in_count > 1) {
10487                                         bb->in_bb [i] = bb->in_bb [bb->in_count - 1];
10488                                 }
10489                                 bb->in_count--;
10490                         } else {
10491                                 bb->in_bb [i] = repl;
10492                         }
10493                 }
10494         }
10495 }
10496
10497 static void
10498 replace_out_block_in_code (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl) {
10499         MonoInst *inst;
10500         
10501         MONO_BB_FOR_EACH_INS (bb, inst) {
10502                 if (inst->opcode == OP_CALL_HANDLER) {
10503                         if (inst->inst_target_bb == orig)
10504                                 inst->inst_target_bb = repl;
10505                 }
10506         }
10507
10508         inst = mono_inst_list_last (&bb->ins_list);
10509         if (!inst)
10510                 return;
10511
10512         switch (inst->opcode) {
10513         case OP_BR:
10514                 if (inst->inst_target_bb == orig)
10515                         inst->inst_target_bb = repl;
10516                 break;
10517         case OP_SWITCH: {
10518                 int i;
10519                 int n = GPOINTER_TO_INT (inst->klass);
10520                 for (i = 0; i < n; i++ ) {
10521                         if (inst->inst_many_bb [i] == orig)
10522                                 inst->inst_many_bb [i] = repl;
10523                 }
10524                 break;
10525         }
10526         case CEE_BNE_UN:
10527         case CEE_BEQ:
10528         case CEE_BLT:
10529         case CEE_BLT_UN:
10530         case CEE_BGT:
10531         case CEE_BGT_UN:
10532         case CEE_BGE:
10533         case CEE_BGE_UN:
10534         case CEE_BLE:
10535         case CEE_BLE_UN:
10536                 if (inst->inst_true_bb == orig)
10537                         inst->inst_true_bb = repl;
10538                 if (inst->inst_false_bb == orig)
10539                         inst->inst_false_bb = repl;
10540                 break;
10541         default:
10542                 break;
10543         }
10544 }
10545
10546 static void 
10547 replace_basic_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
10548 {
10549         int i, j;
10550
10551         for (i = 0; i < bb->out_count; i++) {
10552                 MonoBasicBlock *ob = bb->out_bb [i];
10553                 for (j = 0; j < ob->in_count; j++) {
10554                         if (ob->in_bb [j] == orig) {
10555                                 ob->in_bb [j] = repl;
10556                         }
10557                 }
10558         }
10559
10560 }
10561
10562 /**
10563   * Check if a bb is useless (is just made of NOPs and ends with an
10564   * unconditional branch, or nothing).
10565   * If it is so, unlink it from the CFG and nullify it, and return TRUE.
10566   * Otherwise, return FALSE;
10567   */
10568 static gboolean
10569 remove_block_if_useless (MonoCompile *cfg, MonoBasicBlock *bb, MonoBasicBlock *previous_bb) {
10570         MonoBasicBlock *target_bb = NULL;
10571         MonoInst *inst;
10572         
10573         /* Do not touch handlers */
10574         if (bb->region != -1) {
10575                 bb->not_useless = TRUE;
10576                 return FALSE;
10577         }
10578         
10579         MONO_BB_FOR_EACH_INS (bb, inst) {
10580                 switch (inst->opcode) {
10581                 case OP_NOP:
10582                         break;
10583                 case OP_BR:
10584                         target_bb = inst->inst_target_bb;
10585                         break;
10586                 default:
10587                         bb->not_useless = TRUE;
10588                         return FALSE;
10589                 }
10590         }
10591         
10592         if (target_bb == NULL) {
10593                 if ((bb->out_count == 1) && (bb->out_bb [0] == bb->next_bb)) {
10594                         target_bb = bb->next_bb;
10595                 } else {
10596                         /* Do not touch empty BBs that do not "fall through" to their next BB (like the exit BB) */
10597                         return FALSE;
10598                 }
10599         }
10600         
10601         /* Do not touch BBs following a switch (they are the "default" branch) */
10602         inst = mono_inst_list_last (&previous_bb->ins_list);
10603         if (inst && inst->opcode == OP_SWITCH)
10604                 return FALSE;
10605         
10606         /* Do not touch BBs following the entry BB and jumping to something that is not */
10607         /* thiry "next" bb (the entry BB cannot contain the branch) */
10608         if ((previous_bb == cfg->bb_entry) && (bb->next_bb != target_bb)) {
10609                 return FALSE;
10610         }
10611
10612         /* 
10613          * Do not touch BBs following a try block as the code in 
10614          * mini_method_compile needs them to compute the length of the try block.
10615          */
10616         if (MONO_BBLOCK_IS_IN_REGION (previous_bb, MONO_REGION_TRY))
10617                 return FALSE;
10618         
10619         /* Check that there is a target BB, and that bb is not an empty loop (Bug 75061) */
10620         if ((target_bb != NULL) && (target_bb != bb)) {
10621                 MonoInst *last_ins;
10622                 int i;
10623
10624                 if (cfg->verbose_level > 1) {
10625                         printf ("remove_block_if_useless %s, removed BB%d\n", mono_method_full_name (cfg->method, TRUE), bb->block_num);
10626                 }
10627                 
10628                 /* unlink_bblock () modifies the bb->in_bb array so can't use a for loop here */
10629                 while (bb->in_count) {
10630                         MonoBasicBlock *in_bb = bb->in_bb [0];
10631                         mono_unlink_bblock (cfg, in_bb, bb);
10632                         link_bblock (cfg, in_bb, target_bb);
10633                         replace_out_block_in_code (in_bb, bb, target_bb);
10634                 }
10635                 
10636                 mono_unlink_bblock (cfg, bb, target_bb);
10637                 
10638                 last_ins = mono_inst_list_last (&previous_bb->ins_list);
10639
10640                 if ((previous_bb != cfg->bb_entry) &&
10641                                 (previous_bb->region == bb->region) &&
10642                                 ((last_ins == NULL) ||
10643                                 ((last_ins->opcode != OP_BR) &&
10644                                 (!(MONO_IS_COND_BRANCH_OP (last_ins))) &&
10645                                 (last_ins->opcode != OP_SWITCH)))) {
10646                         for (i = 0; i < previous_bb->out_count; i++) {
10647                                 if (previous_bb->out_bb [i] == target_bb) {
10648                                         MonoInst *jump;
10649                                         MONO_INST_NEW (cfg, jump, OP_BR);
10650                                         MONO_ADD_INS (previous_bb, jump);
10651                                         jump->cil_code = previous_bb->cil_code;
10652                                         jump->inst_target_bb = target_bb;
10653                                         break;
10654                                 }
10655                         }
10656                 }
10657                 
10658                 previous_bb->next_bb = bb->next_bb;
10659                 nullify_basic_block (bb);
10660                 
10661                 return TRUE;
10662         } else {
10663                 return FALSE;
10664         }
10665 }
10666
10667 static void
10668 merge_basic_blocks (MonoBasicBlock *bb, MonoBasicBlock *bbn) 
10669 {
10670         MonoInst *last_ins;
10671
10672         bb->out_count = bbn->out_count;
10673         bb->out_bb = bbn->out_bb;
10674
10675         replace_basic_block (bb, bbn, bb);
10676
10677         last_ins = mono_inst_list_last (&bb->ins_list);
10678
10679         /* Nullify branch at the end of bb */
10680         if (last_ins && MONO_IS_BRANCH_OP (last_ins))
10681                 last_ins->opcode = OP_NOP;
10682
10683         MONO_INST_LIST_SPLICE_TAIL_INIT (&bbn->ins_list, &bb->ins_list);
10684
10685         bb->next_bb = bbn->next_bb;
10686         nullify_basic_block (bbn);
10687 }
10688
10689 static void
10690 move_basic_block_to_end (MonoCompile *cfg, MonoBasicBlock *bb)
10691 {
10692         MonoBasicBlock *bbn, *next;
10693         MonoInst *last_ins;
10694
10695         next = bb->next_bb;
10696
10697         /* Find the previous */
10698         for (bbn = cfg->bb_entry; bbn->next_bb && bbn->next_bb != bb; bbn = bbn->next_bb)
10699                 ;
10700         if (bbn->next_bb) {
10701                 bbn->next_bb = bb->next_bb;
10702         }
10703
10704         /* Find the last */
10705         for (bbn = cfg->bb_entry; bbn->next_bb; bbn = bbn->next_bb)
10706                 ;
10707         bbn->next_bb = bb;
10708         bb->next_bb = NULL;
10709
10710         last_ins = mono_inst_list_last (&bb->ins_list);
10711
10712         /* Add a branch */
10713         if (next && (!last_ins || (last_ins->opcode != OP_NOT_REACHED))) {
10714                 MonoInst *ins;
10715
10716                 MONO_INST_NEW (cfg, ins, OP_BR);
10717                 MONO_ADD_INS (bb, ins);
10718                 link_bblock (cfg, bb, next);
10719                 ins->inst_target_bb = next;
10720         }               
10721 }
10722
10723 /* checks that a and b represent the same instructions, conservatively,
10724  * it can return FALSE also for two trees that are equal.
10725  * FIXME: also make sure there are no side effects.
10726  */
10727 static int
10728 same_trees (MonoInst *a, MonoInst *b)
10729 {
10730         int arity;
10731         if (a->opcode != b->opcode)
10732                 return FALSE;
10733         arity = mono_burg_arity [a->opcode];
10734         if (arity == 1) {
10735                 if (a->ssa_op == b->ssa_op && a->ssa_op == MONO_SSA_LOAD && a->inst_i0 == b->inst_i0)
10736                         return TRUE;
10737                 return same_trees (a->inst_left, b->inst_left);
10738         } else if (arity == 2) {
10739                 return same_trees (a->inst_left, b->inst_left) && same_trees (a->inst_right, b->inst_right);
10740         } else if (arity == 0) {
10741                 switch (a->opcode) {
10742                 case OP_ICONST:
10743                         return a->inst_c0 == b->inst_c0;
10744                 default:
10745                         return FALSE;
10746                 }
10747         }
10748         return FALSE;
10749 }
10750
10751 static int
10752 get_unsigned_condbranch (int opcode)
10753 {
10754         switch (opcode) {
10755         case CEE_BLE: return CEE_BLE_UN;
10756         case CEE_BLT: return CEE_BLT_UN;
10757         case CEE_BGE: return CEE_BGE_UN;
10758         case CEE_BGT: return CEE_BGT_UN;
10759         }
10760         g_assert_not_reached ();
10761         return 0;
10762 }
10763
10764 static int
10765 tree_is_unsigned (MonoInst* ins) {
10766         switch (ins->opcode) {
10767         case OP_ICONST:
10768                 return (int)ins->inst_c0 >= 0;
10769         /* array lengths are positive as are string sizes */
10770         case CEE_LDLEN:
10771         case OP_STRLEN:
10772                 return TRUE;
10773         case CEE_CONV_U1:
10774         case CEE_CONV_U2:
10775         case CEE_CONV_U4:
10776         case CEE_CONV_OVF_U1:
10777         case CEE_CONV_OVF_U2:
10778         case CEE_CONV_OVF_U4:
10779                 return TRUE;
10780         case CEE_LDIND_U1:
10781         case CEE_LDIND_U2:
10782         case CEE_LDIND_U4:
10783                 return TRUE;
10784         default:
10785                 return FALSE;
10786         }
10787 }
10788
10789 /* check if an unsigned compare can be used instead of two signed compares
10790  * for (val < 0 || val > limit) conditionals.
10791  * Returns TRUE if the optimization has been applied.
10792  * Note that this can't be applied if the second arg is not positive...
10793  */
10794 static int
10795 try_unsigned_compare (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *bb_last)
10796 {
10797         MonoBasicBlock *truet, *falset;
10798         MonoInst *cmp_inst = bb_last->inst_left;
10799         MonoInst *condb;
10800         if (!cmp_inst->inst_right->inst_c0 == 0)
10801                 return FALSE;
10802         truet = bb_last->inst_true_bb;
10803         falset = bb_last->inst_false_bb;
10804         if (falset->in_count != 1)
10805                 return FALSE;
10806         condb = mono_inst_list_last (&falset->ins_list);
10807         /* target bb must have one instruction */
10808         if (!condb || (condb->node.next != &falset->ins_list))
10809                 return FALSE;
10810         if ((((condb->opcode == CEE_BLE || condb->opcode == CEE_BLT) && (condb->inst_false_bb == truet))
10811                         || ((condb->opcode == CEE_BGE || condb->opcode == CEE_BGT) && (condb->inst_true_bb == truet)))
10812                         && same_trees (cmp_inst->inst_left, condb->inst_left->inst_left)) {
10813                 if (!tree_is_unsigned (condb->inst_left->inst_right))
10814                         return FALSE;
10815                 condb->opcode = get_unsigned_condbranch (condb->opcode);
10816                 /* change the original condbranch to just point to the new unsigned check */
10817                 bb_last->opcode = OP_BR;
10818                 bb_last->inst_target_bb = falset;
10819                 replace_out_block (bb, truet, NULL);
10820                 replace_in_block (truet, bb, NULL);
10821                 return TRUE;
10822         }
10823         return FALSE;
10824 }
10825
10826 /*
10827  * Optimizes the branches on the Control Flow Graph
10828  *
10829  */
10830 static void
10831 optimize_branches (MonoCompile *cfg)
10832 {
10833         int i, changed = FALSE;
10834         MonoBasicBlock *bb, *bbn;
10835         guint32 niterations;
10836
10837         /*
10838          * Some crazy loops could cause the code below to go into an infinite
10839          * loop, see bug #53003 for an example. To prevent this, we put an upper
10840          * bound on the number of iterations.
10841          */
10842         if (cfg->num_bblocks > 1000)
10843                 niterations = cfg->num_bblocks * 2;
10844         else
10845                 niterations = 1000;
10846
10847         do {
10848                 MonoBasicBlock *previous_bb;
10849                 changed = FALSE;
10850                 niterations --;
10851
10852                 /* we skip the entry block (exit is handled specially instead ) */
10853                 for (previous_bb = cfg->bb_entry, bb = cfg->bb_entry->next_bb; bb; previous_bb = bb, bb = bb->next_bb) {
10854                         MonoInst *last_ins;
10855
10856                         /* dont touch code inside exception clauses */
10857                         if (bb->region != -1)
10858                                 continue;
10859
10860                         if (!bb->not_useless && remove_block_if_useless (cfg, bb, previous_bb)) {
10861                                 changed = TRUE;
10862                                 continue;
10863                         }
10864
10865                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
10866                                 if (cfg->verbose_level > 2)
10867                                         g_print ("nullify block triggered %d\n", bbn->block_num);
10868
10869                                 bb->next_bb = bbn->next_bb;
10870
10871                                 for (i = 0; i < bbn->out_count; i++)
10872                                         replace_in_block (bbn->out_bb [i], bbn, NULL);
10873
10874                                 nullify_basic_block (bbn);                      
10875                                 changed = TRUE;
10876                         }
10877
10878                         last_ins = mono_inst_list_last (&bb->ins_list);
10879                         if (bb->out_count == 1) {
10880                                 bbn = bb->out_bb [0];
10881
10882                                 /* conditional branches where true and false targets are the same can be also replaced with OP_BR */
10883                                 if (last_ins && MONO_IS_COND_BRANCH_OP (last_ins)) {
10884                                         MonoInst *pop;
10885                                         MONO_INST_NEW (cfg, pop, CEE_POP);
10886                                         pop->inst_left = last_ins->inst_left->inst_left;
10887                                         mono_add_ins_to_end (bb, pop);
10888                                         MONO_INST_NEW (cfg, pop, CEE_POP);
10889                                         pop->inst_left = last_ins->inst_left->inst_right;
10890                                         mono_add_ins_to_end (bb, pop);
10891                                         last_ins->opcode = OP_BR;
10892                                         last_ins->inst_target_bb = last_ins->inst_true_bb;
10893                                         changed = TRUE;
10894                                         if (cfg->verbose_level > 2)
10895                                                 g_print ("cond branch removal triggered in %d %d\n", bb->block_num, bb->out_count);
10896                                 }
10897
10898                                 if (bb->region == bbn->region && bb->next_bb == bbn) {
10899                                         /* the block are in sequence anyway ... */
10900
10901                                         /* branches to the following block can be removed */
10902                                         if (last_ins && last_ins->opcode == OP_BR) {
10903                                                 last_ins->opcode = OP_NOP;
10904                                                 changed = TRUE;
10905                                                 if (cfg->verbose_level > 2)
10906                                                         g_print ("br removal triggered %d -> %d\n", bb->block_num, bbn->block_num);
10907                                         }
10908
10909                                         if (bbn->in_count == 1) {
10910
10911                                                 if (bbn != cfg->bb_exit) {
10912                                                         if (cfg->verbose_level > 2)
10913                                                                 g_print ("block merge triggered %d -> %d\n", bb->block_num, bbn->block_num);
10914                                                         merge_basic_blocks (bb, bbn);
10915                                                         changed = TRUE;
10916                                                         continue;
10917                                                 }
10918
10919                                                 //mono_print_bb_code (bb);
10920                                         }
10921                                 }
10922                         }
10923                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
10924                                 if (cfg->verbose_level > 2) {
10925                                         g_print ("nullify block triggered %d\n", bbn->block_num);
10926                                 }
10927                                 bb->next_bb = bbn->next_bb;
10928
10929                                 for (i = 0; i < bbn->out_count; i++)
10930                                         replace_in_block (bbn->out_bb [i], bbn, NULL);
10931
10932                                 nullify_basic_block (bbn);                      
10933                                 changed = TRUE;
10934                                 continue;
10935                         }
10936
10937                         if (bb->out_count == 1) {
10938                                 bbn = bb->out_bb [0];
10939
10940                                 if (last_ins && last_ins->opcode == OP_BR) {
10941                                         MonoInst *bbn_code;
10942
10943                                         bbn = last_ins->inst_target_bb;
10944                                         bbn_code = mono_inst_list_first (&bbn->ins_list);
10945                                         if (bb->region == bbn->region && bbn_code &&
10946                                                         bbn_code->opcode == OP_BR &&
10947                                                         bbn_code->inst_target_bb->region == bb->region) {
10948                                                 if (cfg->verbose_level > 2)
10949                                                         g_print ("in %s branch to branch triggered %d -> %d -> %d\n", cfg->method->name, 
10950                                                                  bb->block_num, bbn->block_num, bbn_code->inst_target_bb->block_num);
10951
10952                                                 replace_in_block (bbn, bb, NULL);
10953                                                 replace_out_block (bb, bbn, bbn_code->inst_target_bb);
10954                                                 link_bblock (cfg, bb, bbn_code->inst_target_bb);
10955                                                 last_ins->inst_target_bb = bbn_code->inst_target_bb;
10956                                                 changed = TRUE;
10957                                                 continue;
10958                                         }
10959                                 }
10960                         } else if (bb->out_count == 2) {
10961                                 if (last_ins && MONO_IS_COND_BRANCH_NOFP (last_ins)) {
10962                                         int branch_result = mono_eval_cond_branch (last_ins);
10963                                         MonoBasicBlock *taken_branch_target = NULL, *untaken_branch_target = NULL;
10964                                         MonoInst *bbn_code;
10965
10966                                         if (branch_result == BRANCH_TAKEN) {
10967                                                 taken_branch_target = last_ins->inst_true_bb;
10968                                                 untaken_branch_target = last_ins->inst_false_bb;
10969                                         } else if (branch_result == BRANCH_NOT_TAKEN) {
10970                                                 taken_branch_target = last_ins->inst_false_bb;
10971                                                 untaken_branch_target = last_ins->inst_true_bb;
10972                                         }
10973                                         if (taken_branch_target) {
10974                                                 /* if mono_eval_cond_branch () is ever taken to handle 
10975                                                  * non-constant values to compare, issue a pop here.
10976                                                  */
10977                                                 last_ins->opcode = OP_BR;
10978                                                 last_ins->inst_target_bb = taken_branch_target;
10979                                                 mono_unlink_bblock (cfg, bb, untaken_branch_target);
10980                                                 changed = TRUE;
10981                                                 continue;
10982                                         }
10983                                         bbn = last_ins->inst_true_bb;
10984                                         bbn_code = mono_inst_list_first (&bbn->ins_list);
10985                                         if (bb->region == bbn->region && bbn_code && bbn_code->opcode == OP_BR &&
10986                                                         bbn_code->inst_target_bb->region == bb->region) {
10987                                                 if (cfg->verbose_level > 2)             
10988                                                         g_print ("cbranch1 to branch triggered %d -> (%d) %d (0x%02x)\n", 
10989                                                                  bb->block_num, bbn->block_num, bbn_code->inst_target_bb->block_num, 
10990                                                                  bbn_code->opcode);
10991
10992                                                 /* 
10993                                                  * Unlink, then relink bblocks to avoid various
10994                                                  * tricky situations when the two targets of the branch
10995                                                  * are equal, or will become equal after the change.
10996                                                  */
10997                                                 mono_unlink_bblock (cfg, bb, last_ins->inst_true_bb);
10998                                                 mono_unlink_bblock (cfg, bb, last_ins->inst_false_bb);
10999
11000                                                 last_ins->inst_true_bb = bbn_code->inst_target_bb;
11001
11002                                                 link_bblock (cfg, bb, last_ins->inst_true_bb);
11003                                                 link_bblock (cfg, bb, last_ins->inst_false_bb);
11004
11005                                                 changed = TRUE;
11006                                                 continue;
11007                                         }
11008
11009                                         bbn = last_ins->inst_false_bb;
11010                                         bbn_code = mono_inst_list_first (&bbn->ins_list);
11011                                         if (bb->region == bbn->region && bbn_code && bbn_code->opcode == OP_BR &&
11012                                                         bbn_code->inst_target_bb->region == bb->region) {
11013                                                 if (cfg->verbose_level > 2)
11014                                                         g_print ("cbranch2 to branch triggered %d -> (%d) %d (0x%02x)\n", 
11015                                                                  bb->block_num, bbn->block_num, bbn_code->inst_target_bb->block_num, 
11016                                                                  bbn_code->opcode);
11017
11018                                                 mono_unlink_bblock (cfg, bb, last_ins->inst_true_bb);
11019                                                 mono_unlink_bblock (cfg, bb, last_ins->inst_false_bb);
11020
11021                                                 last_ins->inst_false_bb = bbn_code->inst_target_bb;
11022
11023                                                 link_bblock (cfg, bb, last_ins->inst_true_bb);
11024                                                 link_bblock (cfg, bb, last_ins->inst_false_bb);
11025
11026                                                 changed = TRUE;
11027                                                 continue;
11028                                         }
11029                                 }
11030
11031                                 /* detect and optimize to unsigned compares checks like: if (v < 0 || v > limit */
11032                                 if (last_ins && last_ins->opcode == CEE_BLT && last_ins->inst_left->inst_right->opcode == OP_ICONST) {
11033                                         if (try_unsigned_compare (cfg, bb, last_ins)) {
11034                                                 /*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));*/
11035                                                 changed = TRUE;
11036                                                 continue;
11037                                         }
11038                                 }
11039
11040                                 if (last_ins && MONO_IS_COND_BRANCH_NOFP (last_ins)) {
11041                                         if (last_ins->inst_false_bb->out_of_line && (bb->region == last_ins->inst_false_bb->region)) {
11042                                                 /* Reverse the branch */
11043                                                 last_ins->opcode = reverse_branch_op (last_ins->opcode);
11044                                                 bbn = last_ins->inst_false_bb;
11045                                                 last_ins->inst_false_bb = last_ins->inst_true_bb;
11046                                                 last_ins->inst_true_bb = bbn;
11047
11048                                                 move_basic_block_to_end (cfg, last_ins->inst_true_bb);
11049                                                 if (cfg->verbose_level > 2)
11050                                                         g_print ("cbranch to throw block triggered %d.\n", 
11051                                                                          bb->block_num);
11052                                         }
11053                                 }
11054                         }
11055                 }
11056         } while (changed && (niterations > 0));
11057
11058 }
11059
11060 static void
11061 mono_compile_create_vars (MonoCompile *cfg)
11062 {
11063         MonoMethodSignature *sig;
11064         MonoMethodHeader *header;
11065         int i;
11066
11067         header = mono_method_get_header (cfg->method);
11068
11069         sig = mono_method_signature (cfg->method);
11070         
11071         if (!MONO_TYPE_IS_VOID (sig->ret)) {
11072                 cfg->ret = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
11073                 cfg->ret->opcode = OP_RETARG;
11074                 cfg->ret->inst_vtype = sig->ret;
11075                 cfg->ret->klass = mono_class_from_mono_type (sig->ret);
11076         }
11077         if (cfg->verbose_level > 2)
11078                 g_print ("creating vars\n");
11079
11080         cfg->args = mono_mempool_alloc0 (cfg->mempool, (sig->param_count + sig->hasthis) * sizeof (MonoInst*));
11081
11082         if (sig->hasthis)
11083                 cfg->args [0] = mono_compile_create_var (cfg, &cfg->method->klass->this_arg, OP_ARG);
11084
11085         for (i = 0; i < sig->param_count; ++i) {
11086                 cfg->args [i + sig->hasthis] = mono_compile_create_var (cfg, sig->params [i], OP_ARG);
11087                 if (sig->params [i]->byref) {
11088                         cfg->disable_ssa = TRUE;
11089                 }
11090         }
11091
11092         cfg->locals_start = cfg->num_varinfo;
11093
11094         if (cfg->verbose_level > 2)
11095                 g_print ("creating locals\n");
11096
11097         for (i = 0; i < header->num_locals; ++i)
11098                 mono_compile_create_var (cfg, header->locals [i], OP_LOCAL);
11099         if (cfg->verbose_level > 2)
11100                 g_print ("locals done\n");
11101
11102         mono_arch_create_vars (cfg);
11103 }
11104
11105 void
11106 mono_print_code (MonoCompile *cfg)
11107 {
11108         MonoBasicBlock *bb;
11109         
11110         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11111                 MonoInst *tree;
11112
11113                 if (!MONO_INST_LIST_EMPTY (&bb->ins_list))
11114                         g_print ("CODE BLOCK %d (nesting %d):\n",
11115                                  bb->block_num, bb->nesting);
11116
11117                 MONO_BB_FOR_EACH_INS (bb, tree) {
11118                         mono_print_tree (tree);
11119                         g_print ("\n");
11120                 }
11121         }
11122 }
11123
11124 extern const char * const mono_burg_rule_string [];
11125
11126 static void
11127 emit_state (MonoCompile *cfg, MBState *state, int goal)
11128 {
11129         MBState *kids [10];
11130         int ern = mono_burg_rule (state, goal);
11131         const guint16 *nts = mono_burg_nts_data + mono_burg_nts [ern];
11132
11133         //g_print ("rule: %s\n", mono_burg_rule_string [ern]);
11134         switch (goal) {
11135         case MB_NTERM_reg:
11136                 //if (state->reg2)
11137                 //      state->reg1 = state->reg2; /* chain rule */
11138                 //else
11139 #ifdef MONO_ARCH_ENABLE_EMIT_STATE_OPT
11140                 if (!state->reg1)
11141 #endif
11142                         state->reg1 = mono_regstate_next_int (cfg->rs);
11143                 //g_print ("alloc symbolic R%d (reg2: R%d) in block %d\n", state->reg1, state->reg2, cfg->cbb->block_num);
11144                 break;
11145         case MB_NTERM_lreg:
11146                 state->reg1 = mono_regstate_next_int (cfg->rs);
11147                 state->reg2 = mono_regstate_next_int (cfg->rs);
11148                 break;
11149         case MB_NTERM_freg:
11150 #ifdef MONO_ARCH_SOFT_FLOAT
11151                 state->reg1 = mono_regstate_next_int (cfg->rs);
11152                 state->reg2 = mono_regstate_next_int (cfg->rs);
11153 #else
11154                 state->reg1 = mono_regstate_next_float (cfg->rs);
11155 #endif
11156                 break;
11157         default:
11158 #ifdef MONO_ARCH_ENABLE_EMIT_STATE_OPT
11159                 /*
11160                  * Enabling this might cause bugs to surface in the local register
11161                  * allocators on some architectures like x86.
11162                  */
11163                 if ((state->tree->ssa_op == MONO_SSA_STORE) && (state->left->tree->opcode == OP_REGVAR)) {
11164                         /* Do not optimize away reg-reg moves */
11165                         if (! ((state->right->tree->ssa_op == MONO_SSA_LOAD) && (state->right->left->tree->opcode == OP_REGVAR))) {
11166                                 state->right->reg1 = state->left->tree->dreg;
11167                         }
11168                 }
11169 #endif
11170
11171                 /* do nothing */
11172                 break;
11173         }
11174         if (nts [0]) {
11175                 mono_burg_kids (state, ern, kids);
11176
11177                 emit_state (cfg, kids [0], nts [0]);
11178                 if (nts [1]) {
11179                         emit_state (cfg, kids [1], nts [1]);
11180                         if (nts [2]) {
11181                                 g_assert (!nts [3]);
11182                                 emit_state (cfg, kids [2], nts [2]);
11183                         }
11184                 }
11185         }
11186
11187 //      g_print ("emit: %s (%p)\n", mono_burg_rule_string [ern], state);
11188         mono_burg_emit (ern, state, state->tree, cfg);
11189 }
11190
11191 #define DEBUG_SELECTION
11192
11193 static void 
11194 mini_select_instructions (MonoCompile *cfg)
11195 {
11196         MonoBasicBlock *bb;
11197         
11198         cfg->state_pool = mono_mempool_new ();
11199         cfg->rs = mono_regstate_new ();
11200
11201         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11202                 MonoInst *last_ins = mono_inst_list_last (&bb->ins_list);
11203
11204                 if (last_ins && MONO_IS_COND_BRANCH_OP (last_ins) &&
11205                                 bb->next_bb != last_ins->inst_false_bb) {
11206
11207                         /* we are careful when inverting, since bugs like #59580
11208                          * could show up when dealing with NaNs.
11209                          */
11210                         if (MONO_IS_COND_BRANCH_NOFP(last_ins) && bb->next_bb == last_ins->inst_true_bb) {
11211                                 MonoBasicBlock *tmp =  last_ins->inst_true_bb;
11212                                 last_ins->inst_true_bb = last_ins->inst_false_bb;
11213                                 last_ins->inst_false_bb = tmp;
11214
11215                                 last_ins->opcode = reverse_branch_op (last_ins->opcode);
11216                         } else {                        
11217                                 MonoInst *inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
11218                                 inst->opcode = OP_BR;
11219                                 inst->inst_target_bb = last_ins->inst_false_bb;
11220                                 mono_bblock_add_inst (bb, inst);
11221                         }
11222                 }
11223         }
11224
11225 #ifdef DEBUG_SELECTION
11226         if (cfg->verbose_level >= 4) {
11227         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11228                 MonoInst *tree; 
11229                 g_print ("DUMP BLOCK %d:\n", bb->block_num);
11230
11231                 MONO_BB_FOR_EACH_INS (bb, tree) {
11232                         mono_print_tree (tree);
11233                         g_print ("\n");
11234                 }
11235         }
11236         }
11237 #endif
11238
11239         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11240                 MonoInst *tree, *n;     
11241                 MonoInstList head;
11242                 MBState *mbstate;
11243
11244                 MONO_INST_LIST_INIT (&head);
11245                 if (MONO_INST_LIST_EMPTY (&bb->ins_list))
11246                         continue;
11247                 MONO_INST_LIST_SPLICE_INIT (&bb->ins_list, &head);
11248                 
11249                 cfg->cbb = bb;
11250                 mono_regstate_reset (cfg->rs);
11251
11252 #ifdef DEBUG_SELECTION
11253                 if (cfg->verbose_level >= 3)
11254                         g_print ("LABEL BLOCK %d:\n", bb->block_num);
11255 #endif
11256                 MONO_INST_LIST_FOR_EACH_ENTRY_SAFE (tree, n, &head, node) {
11257 #ifdef DEBUG_SELECTION
11258                         if (cfg->verbose_level >= 3) {
11259                                 mono_print_tree (tree);
11260                                 g_print ("\n");
11261                         }
11262 #endif
11263
11264                         cfg->ip = tree->cil_code;
11265                         if (!(mbstate = mono_burg_label (tree, cfg))) {
11266                                 g_warning ("unable to label tree %p", tree);
11267                                 mono_print_tree (tree);
11268                                 g_print ("\n");                         
11269                                 g_assert_not_reached ();
11270                         }
11271                         emit_state (cfg, mbstate, MB_NTERM_stmt);
11272                 }
11273                 bb->max_vreg = cfg->rs->next_vreg;
11274
11275                 mono_mempool_empty (cfg->state_pool); 
11276         }
11277         mono_mempool_destroy (cfg->state_pool); 
11278
11279         cfg->ip = NULL;
11280 }
11281
11282 /*
11283  * mono_normalize_opcodes:
11284  *
11285  *   Replace CEE_ and OP_ opcodes with the corresponding OP_I or OP_L opcodes.
11286  */
11287
11288 static gint16 *remap_table;
11289
11290 #if SIZEOF_VOID_P == 8
11291 #define REMAP_OPCODE(opcode) OP_L ## opcode
11292 #else
11293 #define REMAP_OPCODE(opcode) OP_I ## opcode
11294 #endif
11295
11296 static G_GNUC_UNUSED void
11297 mono_normalize_opcodes (MonoCompile *cfg, MonoBasicBlock *bb)
11298 {
11299         MonoInst *ins;
11300
11301         if (!remap_table) {
11302                 remap_table = g_new0 (gint16, OP_LAST);
11303
11304 #if SIZEOF_VOID_P == 8
11305                 remap_table [CEE_CONV_U8] = OP_ZEXT_I4;
11306                 remap_table [CEE_CONV_U] = OP_ZEXT_I4;
11307                 remap_table [CEE_CONV_I8] = OP_SEXT_I4;
11308                 remap_table [CEE_CONV_I] = OP_SEXT_I4;
11309                 remap_table [CEE_CONV_OVF_U4] = OP_LCONV_TO_OVF_U4;
11310                 remap_table [CEE_CONV_OVF_I4_UN] = OP_LCONV_TO_OVF_I4_UN;
11311 #else
11312 #endif
11313                 remap_table [CEE_CONV_R4] = OP_ICONV_TO_R4;
11314                 remap_table [CEE_CONV_R8] = OP_ICONV_TO_R8;
11315                 remap_table [CEE_CONV_I4] = OP_MOVE;
11316                 remap_table [CEE_CONV_U4] = OP_MOVE;
11317                 remap_table [CEE_CONV_I1] = REMAP_OPCODE (CONV_TO_I1);
11318                 remap_table [CEE_CONV_I2] = REMAP_OPCODE (CONV_TO_I2);
11319                 remap_table [CEE_CONV_U1] = REMAP_OPCODE (CONV_TO_U1);
11320                 remap_table [CEE_CONV_U2] = REMAP_OPCODE (CONV_TO_U2);
11321                 remap_table [CEE_CONV_R_UN] = REMAP_OPCODE (CONV_TO_R_UN);
11322                 remap_table [CEE_ADD] = REMAP_OPCODE (ADD);
11323                 remap_table [CEE_SUB] = REMAP_OPCODE (SUB);
11324                 remap_table [CEE_MUL] = REMAP_OPCODE (MUL);
11325                 remap_table [CEE_DIV] = REMAP_OPCODE (DIV);
11326                 remap_table [CEE_REM] = REMAP_OPCODE (REM);
11327                 remap_table [CEE_DIV_UN] = REMAP_OPCODE (DIV_UN);
11328                 remap_table [CEE_REM_UN] = REMAP_OPCODE (REM_UN);
11329                 remap_table [CEE_AND] = REMAP_OPCODE (AND);
11330                 remap_table [CEE_OR] = REMAP_OPCODE (OR);
11331                 remap_table [CEE_XOR] = REMAP_OPCODE (XOR);
11332                 remap_table [CEE_SHL] = REMAP_OPCODE (SHL);
11333                 remap_table [CEE_SHR] = REMAP_OPCODE (SHR);
11334                 remap_table [CEE_SHR_UN] = REMAP_OPCODE (SHR_UN);
11335                 remap_table [CEE_NOT] = REMAP_OPCODE (NOT);
11336                 remap_table [CEE_NEG] = REMAP_OPCODE (NEG);
11337                 remap_table [CEE_CALL] = OP_CALL;
11338                 remap_table [CEE_BEQ] = REMAP_OPCODE (BEQ);
11339                 remap_table [CEE_BNE_UN] = REMAP_OPCODE (BNE_UN);
11340                 remap_table [CEE_BLT] = REMAP_OPCODE (BLT);
11341                 remap_table [CEE_BLT_UN] = REMAP_OPCODE (BLT_UN);
11342                 remap_table [CEE_BGT] = REMAP_OPCODE (BGT);
11343                 remap_table [CEE_BGT_UN] = REMAP_OPCODE (BGT_UN);
11344                 remap_table [CEE_BGE] = REMAP_OPCODE (BGE);
11345                 remap_table [CEE_BGE_UN] = REMAP_OPCODE (BGE_UN);
11346                 remap_table [CEE_BLE] = REMAP_OPCODE (BLE);
11347                 remap_table [CEE_BLE_UN] = REMAP_OPCODE (BLE_UN);
11348                 remap_table [CEE_ADD_OVF] = REMAP_OPCODE (ADD_OVF);
11349                 remap_table [CEE_ADD_OVF_UN] = REMAP_OPCODE (ADD_OVF_UN);
11350                 remap_table [CEE_SUB_OVF] = REMAP_OPCODE (SUB_OVF);
11351                 remap_table [CEE_SUB_OVF_UN] = REMAP_OPCODE (SUB_OVF_UN);
11352                 remap_table [CEE_MUL_OVF] = REMAP_OPCODE (MUL_OVF);
11353                 remap_table [CEE_MUL_OVF_UN] = REMAP_OPCODE (MUL_OVF_UN);
11354         }
11355
11356         MONO_BB_FOR_EACH_INS (bb, ins) {
11357                 int remapped = remap_table [ins->opcode];
11358                 if (remapped)
11359                         ins->opcode = remapped;
11360         }
11361 }
11362
11363 void
11364 mono_codegen (MonoCompile *cfg)
11365 {
11366         MonoJumpInfo *patch_info;
11367         MonoBasicBlock *bb;
11368         int i, max_epilog_size;
11369         guint8 *code;
11370
11371         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11372                 cfg->spill_count = 0;
11373                 /* we reuse dfn here */
11374                 /* bb->dfn = bb_count++; */
11375 #ifdef MONO_ARCH_ENABLE_NORMALIZE_OPCODES
11376                 mono_normalize_opcodes (cfg, bb);
11377 #endif
11378
11379                 mono_arch_lowering_pass (cfg, bb);
11380
11381                 if (cfg->opt & MONO_OPT_PEEPHOLE)
11382                         mono_arch_peephole_pass_1 (cfg, bb);
11383
11384                 mono_local_regalloc (cfg, bb);
11385
11386                 if (cfg->opt & MONO_OPT_PEEPHOLE)
11387                         mono_arch_peephole_pass_2 (cfg, bb);
11388         }
11389
11390         if (cfg->prof_options & MONO_PROFILE_COVERAGE)
11391                 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, cfg->num_bblocks);
11392
11393         code = mono_arch_emit_prolog (cfg);
11394
11395         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
11396                 code = mono_arch_instrument_prolog (cfg, mono_profiler_method_enter, code, FALSE);
11397
11398         cfg->code_len = code - cfg->native_code;
11399         cfg->prolog_end = cfg->code_len;
11400
11401         mono_debug_open_method (cfg);
11402
11403         /* emit code all basic blocks */
11404         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11405                 bb->native_offset = cfg->code_len;
11406                 mono_arch_output_basic_block (cfg, bb);
11407
11408                 if (bb == cfg->bb_exit) {
11409                         cfg->epilog_begin = cfg->code_len;
11410
11411                         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE) {
11412                                 code = cfg->native_code + cfg->code_len;
11413                                 code = mono_arch_instrument_epilog (cfg, mono_profiler_method_leave, code, FALSE);
11414                                 cfg->code_len = code - cfg->native_code;
11415                                 g_assert (cfg->code_len < cfg->code_size);
11416                         }
11417
11418                         mono_arch_emit_epilog (cfg);
11419                 }
11420         }
11421
11422         mono_arch_emit_exceptions (cfg);
11423
11424         max_epilog_size = 0;
11425
11426         code = cfg->native_code + cfg->code_len;
11427
11428         /* we always allocate code in cfg->domain->code_mp to increase locality */
11429         cfg->code_size = cfg->code_len + max_epilog_size;
11430         /* fixme: align to MONO_ARCH_CODE_ALIGNMENT */
11431
11432         if (cfg->method->dynamic) {
11433                 /* Allocate the code into a separate memory pool so it can be freed */
11434                 cfg->dynamic_info = g_new0 (MonoJitDynamicMethodInfo, 1);
11435                 cfg->dynamic_info->code_mp = mono_code_manager_new_dynamic ();
11436                 mono_domain_lock (cfg->domain);
11437                 mono_dynamic_code_hash_insert (cfg->domain, cfg->method, cfg->dynamic_info);
11438                 mono_domain_unlock (cfg->domain);
11439
11440                 code = mono_code_manager_reserve (cfg->dynamic_info->code_mp, cfg->code_size);
11441         } else {
11442                 mono_domain_lock (cfg->domain);
11443                 code = mono_code_manager_reserve (cfg->domain->code_mp, cfg->code_size);
11444                 mono_domain_unlock (cfg->domain);
11445         }
11446
11447         memcpy (code, cfg->native_code, cfg->code_len);
11448         g_free (cfg->native_code);
11449         cfg->native_code = code;
11450         code = cfg->native_code + cfg->code_len;
11451   
11452         /* g_assert (((int)cfg->native_code & (MONO_ARCH_CODE_ALIGNMENT - 1)) == 0); */
11453         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
11454                 switch (patch_info->type) {
11455                 case MONO_PATCH_INFO_ABS: {
11456                         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (patch_info->data.target);
11457                         if (info) {
11458                                 //printf ("TEST %s %p\n", info->name, patch_info->data.target);
11459                                 if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && 
11460                                         strstr (cfg->method->name, info->name))
11461                                         /*
11462                                          * This is an icall wrapper, and this is a call to the
11463                                          * wrapped function.
11464                                          */
11465                                         ;
11466                                 else {
11467                                         /* for these array methods we currently register the same function pointer
11468                                          * since it's a vararg function. But this means that mono_find_jit_icall_by_addr ()
11469                                          * will return the incorrect one depending on the order they are registered.
11470                                          * See tests/test-arr.cs
11471                                          */
11472                                         if (strstr (info->name, "ves_array_new_va_") == NULL && strstr (info->name, "ves_array_element_address_") == NULL) {
11473                                                 patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
11474                                                 patch_info->data.name = info->name;
11475                                         }
11476                                 }
11477                         }
11478                         else {
11479                                 MonoVTable *vtable = mono_find_class_init_trampoline_by_addr (patch_info->data.target);
11480                                 if (vtable) {
11481                                         patch_info->type = MONO_PATCH_INFO_CLASS_INIT;
11482                                         patch_info->data.klass = vtable->klass;
11483                                 } else {
11484                                         MonoClass *klass = mono_find_delegate_trampoline_by_addr (patch_info->data.target);
11485                                         if (klass) {
11486                                                 patch_info->type = MONO_PATCH_INFO_DELEGATE_TRAMPOLINE;
11487                                                 patch_info->data.klass = klass;
11488                                         }
11489                                 }
11490                         }
11491                         break;
11492                 }
11493                 case MONO_PATCH_INFO_SWITCH: {
11494                         gpointer *table;
11495                         if (cfg->method->dynamic) {
11496                                 table = mono_code_manager_reserve (cfg->dynamic_info->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
11497                         } else {
11498                                 mono_domain_lock (cfg->domain);
11499                                 table = mono_code_manager_reserve (cfg->domain->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
11500                                 mono_domain_unlock (cfg->domain);
11501                         }
11502
11503                         if (!cfg->compile_aot)
11504                                 /* In the aot case, the patch already points to the correct location */
11505                                 patch_info->ip.i = patch_info->ip.label->inst_c0;
11506                         for (i = 0; i < patch_info->data.table->table_size; i++) {
11507                                 table [i] = GINT_TO_POINTER (patch_info->data.table->table [i]->native_offset);
11508                         }
11509                         patch_info->data.table->table = (MonoBasicBlock**)table;
11510                         break;
11511                 }
11512                 default:
11513                         /* do nothing */
11514                         break;
11515                 }
11516         }
11517
11518 #ifdef VALGRIND_JIT_REGISTER_MAP
11519 if (valgrind_register){
11520                 char* nm = mono_method_full_name (cfg->method, TRUE);
11521                 VALGRIND_JIT_REGISTER_MAP (nm, cfg->native_code, cfg->native_code + cfg->code_len);
11522                 g_free (nm);
11523         }
11524 #endif
11525  
11526         if (cfg->verbose_level > 0) {
11527                 char* nm = mono_method_full_name (cfg->method, TRUE);
11528                 g_print ("Method %s emitted at %p to %p (code length %d) [%s]\n", 
11529                                  nm, 
11530                                  cfg->native_code, cfg->native_code + cfg->code_len, cfg->code_len, cfg->domain->friendly_name);
11531                 g_free (nm);
11532         }
11533
11534 #ifdef MONO_ARCH_HAVE_SAVE_UNWIND_INFO
11535         mono_arch_save_unwind_info (cfg);
11536 #endif
11537         
11538         mono_arch_patch_code (cfg->method, cfg->domain, cfg->native_code, cfg->patch_info, cfg->run_cctors);
11539
11540         if (cfg->method->dynamic) {
11541                 mono_code_manager_commit (cfg->dynamic_info->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
11542         } else {
11543                 mono_domain_lock (cfg->domain);
11544                 mono_code_manager_commit (cfg->domain->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
11545                 mono_domain_unlock (cfg->domain);
11546         }
11547         
11548         mono_arch_flush_icache (cfg->native_code, cfg->code_len);
11549
11550         mono_debug_close_method (cfg);
11551 }
11552
11553
11554
11555 static void
11556 remove_critical_edges (MonoCompile *cfg) {
11557         MonoBasicBlock *bb;
11558         MonoBasicBlock *previous_bb;
11559         
11560         if (cfg->verbose_level > 3) {
11561                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11562                         MonoInst *last_ins;
11563                         int i;
11564                         printf ("remove_critical_edges %s, BEFORE BB%d (in:", mono_method_full_name (cfg->method, TRUE), bb->block_num);
11565                         for (i = 0; i < bb->in_count; i++) {
11566                                 printf (" %d", bb->in_bb [i]->block_num);
11567                         }
11568                         printf (") (out:");
11569                         for (i = 0; i < bb->out_count; i++) {
11570                                 printf (" %d", bb->out_bb [i]->block_num);
11571                         }
11572                         printf (")");
11573                         last_ins = mono_inst_list_last (&bb->ins_list);
11574                         if (last_ins) {
11575                                 printf (" ");
11576                                 mono_print_tree (last_ins);
11577                         }
11578                         printf ("\n");
11579                 }
11580         }
11581         
11582         for (previous_bb = cfg->bb_entry, bb = previous_bb->next_bb; bb != NULL; previous_bb = previous_bb->next_bb, bb = bb->next_bb) {
11583                 if (bb->in_count > 1) {
11584                         int in_bb_index;
11585                         for (in_bb_index = 0; in_bb_index < bb->in_count; in_bb_index++) {
11586                                 MonoBasicBlock *in_bb = bb->in_bb [in_bb_index];
11587                                 if (in_bb->out_count > 1) {
11588                                         MonoBasicBlock *new_bb = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock));
11589                                         MONO_INST_LIST_INIT (&new_bb->ins_list);
11590                                         new_bb->block_num = cfg->num_bblocks++;
11591 //                                      new_bb->real_offset = bb->real_offset;
11592                                         new_bb->region = bb->region;
11593                                         
11594                                         /* Do not alter the CFG while altering the BB list */
11595                                         if (previous_bb->region == bb->region) {
11596                                                 if (previous_bb != cfg->bb_entry) {
11597                                                         MonoInst *last_ins;
11598                                                         /* If previous_bb "followed through" to bb, */
11599                                                         /* keep it linked with a OP_BR */
11600                                                         last_ins = mono_inst_list_last (&previous_bb->ins_list);
11601                                                         if ((last_ins == NULL) ||
11602                                                                         ((last_ins->opcode != OP_BR) &&
11603                                                                         (!(MONO_IS_COND_BRANCH_OP (last_ins))) &&
11604                                                                         (last_ins->opcode != OP_SWITCH))) {
11605                                                                 int i;
11606                                                                 /* Make sure previous_bb really falls through bb */
11607                                                                 for (i = 0; i < previous_bb->out_count; i++) {
11608                                                                         if (previous_bb->out_bb [i] == bb) {
11609                                                                                 MonoInst *jump;
11610                                                                                 MONO_INST_NEW (cfg, jump, OP_BR);
11611                                                                                 MONO_ADD_INS (previous_bb, jump);
11612                                                                                 jump->cil_code = previous_bb->cil_code;
11613                                                                                 jump->inst_target_bb = bb;
11614                                                                                 break;
11615                                                                         }
11616                                                                 }
11617                                                         }
11618                                                 } else {
11619                                                         /* We cannot add any inst to the entry BB, so we must */
11620                                                         /* put a new BB in the middle to hold the OP_BR */
11621                                                         MonoInst *jump;
11622                                                         MonoBasicBlock *new_bb_after_entry = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock));
11623                                                         MONO_INST_LIST_INIT (&new_bb_after_entry->ins_list);
11624                                                         new_bb_after_entry->block_num = cfg->num_bblocks++;
11625 //                                                      new_bb_after_entry->real_offset = bb->real_offset;
11626                                                         new_bb_after_entry->region = bb->region;
11627                                                         
11628                                                         MONO_INST_NEW (cfg, jump, OP_BR);
11629                                                         MONO_ADD_INS (new_bb_after_entry, jump);
11630                                                         jump->cil_code = bb->cil_code;
11631                                                         jump->inst_target_bb = bb;
11632                                                         
11633                                                         previous_bb->next_bb = new_bb_after_entry;
11634                                                         previous_bb = new_bb_after_entry;
11635                                                         
11636                                                         if (cfg->verbose_level > 2) {
11637                                                                 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);
11638                                                         }
11639                                                 }
11640                                         }
11641                                         
11642                                         /* Insert new_bb in the BB list */
11643                                         previous_bb->next_bb = new_bb;
11644                                         new_bb->next_bb = bb;
11645                                         previous_bb = new_bb;
11646                                         
11647                                         /* Setup in_bb and out_bb */
11648                                         new_bb->in_bb = mono_mempool_alloc ((cfg)->mempool, sizeof (MonoBasicBlock*));
11649                                         new_bb->in_bb [0] = in_bb;
11650                                         new_bb->in_count = 1;
11651                                         new_bb->out_bb = mono_mempool_alloc ((cfg)->mempool, sizeof (MonoBasicBlock*));
11652                                         new_bb->out_bb [0] = bb;
11653                                         new_bb->out_count = 1;
11654                                         
11655                                         /* Relink in_bb and bb to (from) new_bb */
11656                                         replace_out_block (in_bb, bb, new_bb);
11657                                         replace_out_block_in_code (in_bb, bb, new_bb);
11658                                         replace_in_block (bb, in_bb, new_bb);
11659                                         
11660                                         if (cfg->verbose_level > 2) {
11661                                                 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);
11662                                         }
11663                                 }
11664                         }
11665                 }
11666         }
11667         
11668         if (cfg->verbose_level > 3) {
11669                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11670                         MonoInst *last_ins;
11671                         int i;
11672                         printf ("remove_critical_edges %s, AFTER BB%d (in:", mono_method_full_name (cfg->method, TRUE), bb->block_num);
11673                         for (i = 0; i < bb->in_count; i++) {
11674                                 printf (" %d", bb->in_bb [i]->block_num);
11675                         }
11676                         printf (") (out:");
11677                         for (i = 0; i < bb->out_count; i++) {
11678                                 printf (" %d", bb->out_bb [i]->block_num);
11679                         }
11680                         printf (")");
11681                         last_ins = mono_inst_list_last (&bb->ins_list);
11682                         if (last_ins) {
11683                                 printf (" ");
11684                                 mono_print_tree (last_ins);
11685                         }
11686                         printf ("\n");
11687                 }
11688         }
11689 }
11690
11691 /*
11692  * mini_method_compile:
11693  * @method: the method to compile
11694  * @opts: the optimization flags to use
11695  * @domain: the domain where the method will be compiled in
11696  * @run_cctors: whether we should run type ctors if possible
11697  * @compile_aot: whether this is an AOT compilation
11698  * @parts: debug flag
11699  *
11700  * Returns: a MonoCompile* pointer. Caller must check the exception_type
11701  * field in the returned struct to see if compilation succeded.
11702  */
11703 MonoCompile*
11704 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gboolean run_cctors, gboolean compile_aot, int parts)
11705 {
11706         MonoMethodHeader *header;
11707         guint8 *ip;
11708         MonoCompile *cfg;
11709         MonoJitInfo *jinfo;
11710         int dfn = 0, i, code_size_ratio;
11711         gboolean deadce_has_run = FALSE;
11712         gboolean try_generic_shared;
11713         MonoMethod *method_to_compile;
11714         int generic_info_size;
11715
11716         mono_jit_stats.methods_compiled++;
11717         if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)
11718                 mono_profiler_method_jit (method);
11719  
11720         if (compile_aot)
11721                 /* We are passed the original generic method definition */
11722                 try_generic_shared = mono_class_generic_sharing_enabled (method->klass) &&
11723                         (opts & MONO_OPT_GSHARED) && (method->generic_container || method->klass->generic_container);
11724         else
11725                 try_generic_shared = mono_class_generic_sharing_enabled (method->klass) &&
11726                         (opts & MONO_OPT_GSHARED) && mono_method_is_generic_sharable_impl (method);
11727
11728         if (opts & MONO_OPT_GSHARED) {
11729                 if (try_generic_shared)
11730                         mono_stats.generics_sharable_methods++;
11731                 else if (mono_method_is_generic_impl (method))
11732                         mono_stats.generics_unsharable_methods++;
11733         }
11734
11735  restart_compile:
11736         if (try_generic_shared) {
11737                 MonoMethod *declaring_method;
11738                 MonoGenericContext *shared_context;
11739
11740                 if (compile_aot) {
11741                         declaring_method = method;
11742                 } else {
11743                         declaring_method = mono_method_get_declaring_generic_method (method);
11744                         g_assert (method->klass->generic_class->container_class == declaring_method->klass);
11745                 }
11746
11747                 if (declaring_method->generic_container)
11748                         shared_context = &declaring_method->generic_container->context;
11749                 else
11750                         shared_context = &declaring_method->klass->generic_container->context;
11751
11752                 method_to_compile = mono_class_inflate_generic_method (declaring_method, shared_context);
11753                 g_assert (method_to_compile);
11754         } else {
11755                 method_to_compile = method;
11756         }
11757
11758         cfg = g_new0 (MonoCompile, 1);
11759         cfg->method = method_to_compile;
11760         cfg->mempool = mono_mempool_new ();
11761         cfg->opt = opts;
11762         cfg->prof_options = mono_profiler_get_events ();
11763         cfg->run_cctors = run_cctors;
11764         cfg->domain = domain;
11765         cfg->verbose_level = mini_verbose;
11766         cfg->compile_aot = compile_aot;
11767         cfg->skip_visibility = method->skip_visibility;
11768         if (try_generic_shared)
11769                 cfg->generic_sharing_context = (MonoGenericSharingContext*)&cfg->generic_sharing_context;
11770         cfg->token_info_hash = g_hash_table_new (NULL, NULL);
11771
11772         /* The debugger has no liveness information, so avoid sharing registers/stack slots */
11773         if (mono_debug_using_mono_debugger () || debug_options.mdb_optimizations) {
11774                 cfg->disable_reuse_registers = TRUE;
11775                 cfg->disable_reuse_stack_slots = TRUE;
11776                 /* 
11777                  * This decreases the change the debugger will read registers/stack slots which are
11778                  * not yet initialized.
11779                  */
11780                 cfg->disable_initlocals_opt = TRUE;
11781
11782                 /* Temporarily disable this when running in the debugger until we have support
11783                  * for this in the debugger. */
11784                 cfg->disable_omit_fp = TRUE;
11785
11786                 // cfg->opt |= MONO_OPT_SHARED;
11787                 cfg->opt &= ~MONO_OPT_INLINE;
11788                 cfg->opt &= ~MONO_OPT_COPYPROP;
11789                 cfg->opt &= ~MONO_OPT_CONSPROP;
11790         }
11791
11792         header = mono_method_get_header (method_to_compile);
11793         if (!header) {
11794                 cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
11795                 cfg->exception_message = g_strdup_printf ("Missing or incorrect header for method %s", cfg->method->name);
11796                 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
11797                         mono_profiler_method_end_jit (method, NULL, MONO_PROFILE_FAILED);
11798                 return cfg;
11799         }
11800
11801         ip = (guint8 *)header->code;
11802
11803         if (cfg->verbose_level > 2) {
11804                 if (cfg->generic_sharing_context)
11805                         g_print ("converting shared method %s\n", mono_method_full_name (method, TRUE));
11806                 else
11807                         g_print ("converting method %s\n", mono_method_full_name (method, TRUE));
11808         }
11809
11810         /*
11811          * create MonoInst* which represents arguments and local variables
11812          */
11813         mono_compile_create_vars (cfg);
11814
11815         if ((i = mono_method_to_ir (cfg, method_to_compile, NULL, NULL, cfg->locals_start, NULL, NULL, NULL, 0, FALSE)) < 0) {
11816                 if (try_generic_shared && cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
11817                         if (compile_aot)
11818                                 return cfg;
11819                         mono_destroy_compile (cfg);
11820                         try_generic_shared = FALSE;
11821                         goto restart_compile;
11822                 }
11823                 g_assert (cfg->exception_type != MONO_EXCEPTION_GENERIC_SHARING_FAILED);
11824
11825                 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
11826                         mono_profiler_method_end_jit (method, NULL, MONO_PROFILE_FAILED);
11827                 /* cfg contains the details of the failure, so let the caller cleanup */
11828                 return cfg;
11829         }
11830
11831         mono_jit_stats.basic_blocks += cfg->num_bblocks;
11832         mono_jit_stats.max_basic_blocks = MAX (cfg->num_bblocks, mono_jit_stats.max_basic_blocks);
11833
11834         if ((cfg->num_varinfo > 2000) && !cfg->compile_aot) {
11835                 /* 
11836                  * we disable some optimizations if there are too many variables
11837                  * because JIT time may become too expensive. The actual number needs 
11838                  * to be tweaked and eventually the non-linear algorithms should be fixed.
11839                  */
11840                 cfg->opt &= ~ (MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP);
11841                 cfg->disable_ssa = TRUE;
11842         }
11843
11844         /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/
11845
11846         if (cfg->opt & MONO_OPT_BRANCH)
11847                 optimize_branches (cfg);
11848
11849         if (cfg->opt & MONO_OPT_SSAPRE) {
11850                 remove_critical_edges (cfg);
11851         }
11852
11853         /* Depth-first ordering on basic blocks */
11854         cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
11855
11856         df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
11857         if (cfg->num_bblocks != dfn + 1) {
11858                 MonoBasicBlock *bb;
11859
11860                 cfg->num_bblocks = dfn + 1;
11861
11862                 if (!header->clauses) {
11863                         /* remove unreachable code, because the code in them may be 
11864                          * inconsistent  (access to dead variables for example) */
11865                         for (bb = cfg->bb_entry; bb;) {
11866                                 MonoBasicBlock *bbn = bb->next_bb;
11867
11868                                 if (bbn && bbn->region == -1 && !bbn->dfn) {
11869                                         if (cfg->verbose_level > 1)
11870                                                 g_print ("found unreachable code in BB%d\n", bbn->block_num);
11871                                         bb->next_bb = bbn->next_bb;
11872                                         nullify_basic_block (bbn);                      
11873                                 } else {
11874                                         bb = bb->next_bb;
11875                                 }
11876                         }
11877                 }
11878         }
11879
11880         if (cfg->opt & MONO_OPT_LOOP) {
11881                 mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM);
11882                 mono_compute_natural_loops (cfg);
11883         }
11884
11885         /* after method_to_ir */
11886         if (parts == 1)
11887                 return cfg;
11888
11889 //#define DEBUGSSA "logic_run"
11890 #define DEBUGSSA_CLASS "Tests"
11891 #ifdef DEBUGSSA
11892
11893         if (!header->num_clauses && !cfg->disable_ssa) {
11894                 mono_local_cprop (cfg);
11895 #ifndef DISABLE_SSA
11896                 mono_ssa_compute (cfg);
11897 #endif
11898         }
11899 #else 
11900
11901         /* fixme: add all optimizations which requires SSA */
11902         if (cfg->opt & (MONO_OPT_SSA | MONO_OPT_ABCREM | MONO_OPT_SSAPRE)) {
11903                 if (!(cfg->comp_done & MONO_COMP_SSA) && !header->num_clauses && !cfg->disable_ssa) {
11904                         mono_local_cprop (cfg);
11905 #ifndef DISABLE_SSA
11906                         mono_ssa_compute (cfg);
11907 #endif
11908
11909                         if (cfg->verbose_level >= 2) {
11910                                 print_dfn (cfg);
11911                         }
11912                 }
11913         }
11914 #endif
11915
11916         /* after SSA translation */
11917         if (parts == 2)
11918                 return cfg;
11919
11920         if ((cfg->opt & MONO_OPT_CONSPROP) || (cfg->opt & MONO_OPT_COPYPROP)) {
11921                 if (cfg->comp_done & MONO_COMP_SSA) {
11922 #ifndef DISABLE_SSA
11923                         mono_ssa_cprop (cfg);
11924 #endif
11925                 } else {
11926                         mono_local_cprop (cfg);
11927                 }
11928         }
11929
11930 #ifndef DISABLE_SSA
11931         if (cfg->comp_done & MONO_COMP_SSA) {                   
11932                 //mono_ssa_deadce (cfg);
11933
11934                 //mono_ssa_strength_reduction (cfg);
11935
11936                 if (cfg->opt & MONO_OPT_SSAPRE) {
11937                         mono_perform_ssapre (cfg);
11938                         //mono_local_cprop (cfg);
11939                 }
11940                 
11941                 if (cfg->opt & MONO_OPT_DEADCE) {
11942                         mono_ssa_deadce (cfg);
11943                         deadce_has_run = TRUE;
11944                 }
11945                 
11946                 if ((cfg->flags & MONO_CFG_HAS_LDELEMA) && (cfg->opt & MONO_OPT_ABCREM))
11947                         mono_perform_abc_removal (cfg);
11948                 
11949                 mono_ssa_remove (cfg);
11950
11951                 if (cfg->opt & MONO_OPT_BRANCH)
11952                         optimize_branches (cfg);
11953         }
11954 #endif
11955
11956         /* after SSA removal */
11957         if (parts == 3)
11958                 return cfg;
11959
11960         if (cfg->verbose_level > 4) {
11961                 printf ("BEFORE DECOMPSE START\n");
11962                 mono_print_code (cfg);
11963                 printf ("BEFORE DECOMPSE END\n");
11964         }
11965         
11966         decompose_pass (cfg);
11967
11968         if (cfg->got_var) {
11969                 GList *regs;
11970
11971                 g_assert (cfg->got_var_allocated);
11972
11973                 /* 
11974                  * Allways allocate the GOT var to a register, because keeping it
11975                  * in memory will increase the number of live temporaries in some
11976                  * code created by inssel.brg, leading to the well known spills+
11977                  * branches problem. Testcase: mcs crash in 
11978                  * System.MonoCustomAttrs:GetCustomAttributes.
11979                  */
11980                 regs = mono_arch_get_global_int_regs (cfg);
11981                 g_assert (regs);
11982                 cfg->got_var->opcode = OP_REGVAR;
11983                 cfg->got_var->dreg = GPOINTER_TO_INT (regs->data);
11984                 cfg->used_int_regs |= 1LL << cfg->got_var->dreg;
11985                 
11986                 g_list_free (regs);
11987         }
11988
11989         /* todo: remove code when we have verified that the liveness for try/catch blocks
11990          * works perfectly 
11991          */
11992         /* 
11993          * Currently, this can't be commented out since exception blocks are not
11994          * processed during liveness analysis.
11995          */
11996         mono_liveness_handle_exception_clauses (cfg);
11997
11998         if (cfg->opt & MONO_OPT_LINEARS) {
11999                 GList *vars, *regs;
12000                 
12001                 /* For now, compute aliasing info only if needed for deadce... */
12002                 if ((cfg->opt & MONO_OPT_DEADCE) && (! deadce_has_run) && (header->num_clauses == 0)) {
12003                         cfg->aliasing_info = mono_build_aliasing_information (cfg);
12004                 }
12005
12006                 /* fixme: maybe we can avoid to compute livenesss here if already computed ? */
12007                 cfg->comp_done &= ~MONO_COMP_LIVENESS;
12008                 if (!(cfg->comp_done & MONO_COMP_LIVENESS))
12009                         mono_analyze_liveness (cfg);
12010
12011                 if (cfg->aliasing_info != NULL) {
12012                         mono_aliasing_deadce (cfg->aliasing_info);
12013                         deadce_has_run = TRUE;
12014                 }
12015                 
12016                 if ((vars = mono_arch_get_allocatable_int_vars (cfg))) {
12017                         regs = mono_arch_get_global_int_regs (cfg);
12018                         if (cfg->got_var)
12019                                 regs = g_list_delete_link (regs, regs);
12020                         mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs);
12021                 }
12022                 
12023                 if (cfg->aliasing_info != NULL) {
12024                         mono_destroy_aliasing_information (cfg->aliasing_info);
12025                         cfg->aliasing_info = NULL;
12026                 }
12027         }
12028
12029         //mono_print_code (cfg);
12030
12031     //print_dfn (cfg);
12032         
12033         /* variables are allocated after decompose, since decompose could create temps */
12034         mono_arch_allocate_vars (cfg);
12035
12036         if (cfg->opt & MONO_OPT_CFOLD)
12037                 mono_constant_fold (cfg);
12038
12039         mini_select_instructions (cfg);
12040
12041         mono_codegen (cfg);
12042         if (cfg->verbose_level >= 2) {
12043                 char *id =  mono_method_full_name (cfg->method, FALSE);
12044                 mono_disassemble_code (cfg, cfg->native_code, cfg->code_len, id + 3);
12045                 g_free (id);
12046         }
12047
12048         if (cfg->generic_sharing_context)
12049                 generic_info_size = sizeof (MonoGenericJitInfo);
12050         else
12051                 generic_info_size = 0;
12052
12053         if (cfg->method->dynamic) {
12054                 jinfo = g_malloc0 (sizeof (MonoJitInfo) + (header->num_clauses * sizeof (MonoJitExceptionInfo)) +
12055                                 generic_info_size);
12056         } else {
12057                 /* we access cfg->domain->mp */
12058                 mono_domain_lock (cfg->domain);
12059                 jinfo = mono_mempool_alloc0 (cfg->domain->mp, sizeof (MonoJitInfo) +
12060                                 (header->num_clauses * sizeof (MonoJitExceptionInfo)) +
12061                                 generic_info_size);
12062                 mono_domain_unlock (cfg->domain);
12063         }
12064
12065         jinfo->method = method;
12066         jinfo->code_start = cfg->native_code;
12067         jinfo->code_size = cfg->code_len;
12068         jinfo->used_regs = cfg->used_int_regs;
12069         jinfo->domain_neutral = (cfg->opt & MONO_OPT_SHARED) != 0;
12070         jinfo->cas_inited = FALSE; /* initialization delayed at the first stalk walk using this method */
12071         jinfo->num_clauses = header->num_clauses;
12072
12073         /*
12074          * Static methods only get a generic JIT info if they use the
12075          * rgctx variable (which they are forced to if they have any
12076          * open catch clauses).
12077          */
12078         if (cfg->generic_sharing_context &&
12079                         (cfg->rgctx_var || !(method_to_compile->flags & METHOD_ATTRIBUTE_STATIC))) {
12080                 MonoInst *inst;
12081                 MonoGenericJitInfo *gi;
12082
12083                 jinfo->has_generic_jit_info = 1;
12084
12085                 gi = mono_jit_info_get_generic_jit_info (jinfo);
12086                 g_assert (gi);
12087
12088                 gi->generic_sharing_context = cfg->generic_sharing_context;
12089
12090                 if (method_to_compile->flags & METHOD_ATTRIBUTE_STATIC) {
12091                         inst = cfg->rgctx_var;
12092                         g_assert (inst->opcode == OP_REGOFFSET);
12093                 } else {
12094                         inst = cfg->args [0];
12095                 }
12096
12097                 if (inst->opcode == OP_REGVAR) {
12098                         gi->this_in_reg = 1;
12099                         gi->this_reg = inst->dreg;
12100
12101                         //g_print ("this in reg %d\n", inst->dreg);
12102                 } else {
12103                         g_assert (inst->opcode == OP_REGOFFSET);
12104 #ifdef __i386__
12105                         g_assert (inst->inst_basereg == X86_EBP);
12106 #elif defined(__x86_64__)
12107                         g_assert (inst->inst_basereg == X86_EBP || inst->inst_basereg == X86_ESP);
12108 #endif
12109                         g_assert (inst->inst_offset >= G_MININT32 && inst->inst_offset <= G_MAXINT32);
12110
12111                         gi->this_in_reg = 0;
12112                         gi->this_reg = inst->inst_basereg;
12113                         gi->this_offset = inst->inst_offset;
12114
12115                         //g_print ("this at offset %d\n", inst->inst_offset);
12116                 }
12117         }
12118
12119         if (header->num_clauses) {
12120                 int i;
12121
12122                 for (i = 0; i < header->num_clauses; i++) {
12123                         MonoExceptionClause *ec = &header->clauses [i];
12124                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
12125                         MonoBasicBlock *tblock;
12126                         MonoInst *exvar;
12127
12128                         ei->flags = ec->flags;
12129
12130                         exvar = mono_find_exvar_for_offset (cfg, ec->handler_offset);
12131                         ei->exvar_offset = exvar ? exvar->inst_offset : 0;
12132
12133                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
12134                                 tblock = cfg->cil_offset_to_bb [ec->data.filter_offset];
12135                                 g_assert (tblock);
12136                                 ei->data.filter = cfg->native_code + tblock->native_offset;
12137                         } else {
12138                                 ei->data.catch_class = ec->data.catch_class;
12139                         }
12140
12141                         tblock = cfg->cil_offset_to_bb [ec->try_offset];
12142                         g_assert (tblock);
12143                         ei->try_start = cfg->native_code + tblock->native_offset;
12144                         g_assert (tblock->native_offset);
12145                         tblock = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
12146                         g_assert (tblock);
12147                         ei->try_end = cfg->native_code + tblock->native_offset;
12148                         g_assert (tblock->native_offset);
12149                         tblock = cfg->cil_offset_to_bb [ec->handler_offset];
12150                         g_assert (tblock);
12151                         ei->handler_start = cfg->native_code + tblock->native_offset;
12152                 }
12153         }
12154
12155         cfg->jit_info = jinfo;
12156 #if defined(__arm__)
12157         mono_arch_fixup_jinfo (cfg);
12158 #endif
12159
12160         mono_domain_lock (cfg->domain);
12161         mono_jit_info_table_add (cfg->domain, jinfo);
12162
12163         if (cfg->method->dynamic)
12164                 mono_dynamic_code_hash_lookup (cfg->domain, cfg->method)->ji = jinfo;
12165         mono_domain_unlock (cfg->domain);
12166
12167         /* collect statistics */
12168         mono_jit_stats.allocated_code_size += cfg->code_len;
12169         code_size_ratio = cfg->code_len;
12170         if (code_size_ratio > mono_jit_stats.biggest_method_size) {
12171                         mono_jit_stats.biggest_method_size = code_size_ratio;
12172                         mono_jit_stats.biggest_method = method;
12173         }
12174         code_size_ratio = (code_size_ratio * 100) / mono_method_get_header (method)->code_size;
12175         if (code_size_ratio > mono_jit_stats.max_code_size_ratio) {
12176                 mono_jit_stats.max_code_size_ratio = code_size_ratio;
12177                 mono_jit_stats.max_ratio_method = method;
12178         }
12179         mono_jit_stats.native_code_size += cfg->code_len;
12180
12181         if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
12182                 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
12183
12184         return cfg;
12185 }
12186
12187 static MonoJitInfo*
12188 lookup_generic_method (MonoDomain *domain, MonoMethod *method)
12189 {
12190         MonoMethod *open_method;
12191
12192         if (!mono_method_is_generic_sharable_impl (method))
12193                 return NULL;
12194
12195         open_method = mono_method_get_declaring_generic_method (method);
12196
12197         return mono_domain_lookup_shared_generic (domain, open_method);
12198 }
12199
12200 static MonoJitInfo*
12201 lookup_method (MonoDomain *domain, MonoMethod *method)
12202 {
12203         MonoJitInfo *ji = mono_internal_hash_table_lookup (&domain->jit_code_hash, method);
12204
12205         if (ji != NULL)
12206                 return ji;
12207
12208         return lookup_generic_method (domain, method);
12209 }
12210
12211 static gpointer
12212 mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain, int opt)
12213 {
12214         MonoCompile *cfg;
12215         gpointer code = NULL;
12216         MonoJitInfo *info;
12217
12218 #ifdef MONO_USE_AOT_COMPILER
12219         if ((opt & MONO_OPT_AOT) && !(mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)) {
12220                 MonoDomain *domain = mono_domain_get ();
12221
12222                 mono_class_init (method->klass);
12223
12224                 mono_domain_lock (domain);
12225                 if ((code = mono_aot_get_method (domain, method))) {
12226                         mono_domain_unlock (domain);
12227                         mono_runtime_class_init (mono_class_vtable (domain, method->klass));
12228                         return code;
12229                 }
12230
12231                 mono_domain_unlock (domain);
12232         }
12233 #endif
12234
12235         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
12236             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
12237                 MonoMethod *nm;
12238                 MonoMethodPInvoke* piinfo = (MonoMethodPInvoke *) method;
12239
12240                 if (!piinfo->addr) {
12241                         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
12242                                 piinfo->addr = mono_lookup_internal_call (method);
12243                         else if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)
12244 #ifdef PLATFORM_WIN32
12245                                 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);
12246 #else
12247                                 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);
12248 #endif
12249                         else
12250                                 mono_lookup_pinvoke_call (method, NULL, NULL);
12251                 }
12252                         nm = mono_marshal_get_native_wrapper (method, check_for_pending_exc);
12253                         return mono_get_addr_from_ftnptr (mono_compile_method (nm));
12254
12255                         //if (mono_debug_format != MONO_DEBUG_FORMAT_NONE) 
12256                         //mono_debug_add_wrapper (method, nm);
12257         } else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
12258                 const char *name = method->name;
12259                 MonoMethod *nm;
12260
12261                 if (method->klass->parent == mono_defaults.multicastdelegate_class) {
12262                         if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
12263                                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name ("mono_delegate_ctor");
12264                                 g_assert (mi);
12265                                 return mono_get_addr_from_ftnptr ((gpointer)mono_icall_get_wrapper (mi));
12266                         } else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
12267 #ifdef MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE
12268                                 return mono_create_delegate_trampoline (method->klass);
12269 #else
12270                                 nm = mono_marshal_get_delegate_invoke (method, NULL);
12271                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
12272 #endif
12273                         } else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
12274                                 nm = mono_marshal_get_delegate_begin_invoke (method);
12275                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
12276                         } else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
12277                                 nm = mono_marshal_get_delegate_end_invoke (method);
12278                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
12279                         }
12280                 }
12281                 return NULL;
12282         }
12283
12284         cfg = mini_method_compile (method, opt, target_domain, TRUE, FALSE, 0);
12285
12286         switch (cfg->exception_type) {
12287         case MONO_EXCEPTION_NONE: break;
12288         case MONO_EXCEPTION_TYPE_LOAD:
12289         case MONO_EXCEPTION_MISSING_FIELD:
12290         case MONO_EXCEPTION_MISSING_METHOD:
12291         case MONO_EXCEPTION_FILE_NOT_FOUND: {
12292                 /* Throw a type load exception if needed */
12293                 MonoLoaderError *error = mono_loader_get_last_error ();
12294                 MonoException *ex;
12295
12296                 if (error) {
12297                         ex = mono_loader_error_prepare_exception (error);
12298                 } else {
12299                         if (cfg->exception_ptr) {
12300                                 ex = mono_class_get_exception_for_failure (cfg->exception_ptr);
12301                         } else {
12302                                 if (cfg->exception_type == MONO_EXCEPTION_MISSING_FIELD)
12303                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingFieldException", cfg->exception_message);
12304                                 else if (cfg->exception_type == MONO_EXCEPTION_MISSING_METHOD)
12305                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingMethodException", cfg->exception_message);
12306                                 else if (cfg->exception_type == MONO_EXCEPTION_TYPE_LOAD)
12307                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "TypeLoadException", cfg->exception_message);
12308                                 else if (cfg->exception_type == MONO_EXCEPTION_FILE_NOT_FOUND)
12309                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "FileNotFoundException", cfg->exception_message);
12310                                 else
12311                                         g_assert_not_reached ();
12312                         }
12313                 }
12314                 mono_destroy_compile (cfg);
12315                 mono_raise_exception (ex);
12316                 break;
12317         }
12318         case MONO_EXCEPTION_INVALID_PROGRAM: {
12319                 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "InvalidProgramException", cfg->exception_message);
12320                 mono_destroy_compile (cfg);
12321                 mono_raise_exception (ex);
12322                 break;
12323         }
12324         case MONO_EXCEPTION_UNVERIFIABLE_IL: {
12325                 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System.Security", "VerificationException", cfg->exception_message);
12326                 mono_destroy_compile (cfg);
12327                 mono_raise_exception (ex);
12328                 break;
12329         }
12330         case MONO_EXCEPTION_METHOD_ACCESS: {
12331                 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MethodAccessException", cfg->exception_message);
12332                 mono_destroy_compile (cfg);
12333                 mono_raise_exception (ex);
12334                 break;
12335         }
12336         case MONO_EXCEPTION_FIELD_ACCESS: {
12337                 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "FieldAccessException", cfg->exception_message);
12338                 mono_destroy_compile (cfg);
12339                 mono_raise_exception (ex);
12340                 break;
12341         }
12342         /* this can only be set if the security manager is active */
12343         case MONO_EXCEPTION_SECURITY_LINKDEMAND: {
12344                 MonoSecurityManager* secman = mono_security_manager_get_methods ();
12345                 MonoObject *exc = NULL;
12346                 gpointer args [2];
12347
12348                 args [0] = &cfg->exception_data;
12349                 args [1] = &method;
12350                 mono_runtime_invoke (secman->linkdemandsecurityexception, NULL, args, &exc);
12351
12352                 mono_destroy_compile (cfg);
12353                 cfg = NULL;
12354
12355                 mono_raise_exception ((MonoException*)exc);
12356         }
12357         default:
12358                 g_assert_not_reached ();
12359         }
12360
12361         mono_domain_lock (target_domain);
12362
12363         /* Check if some other thread already did the job. In this case, we can
12364        discard the code this thread generated. */
12365
12366         if ((info = lookup_method (target_domain, method))) {
12367                 /* We can't use a domain specific method in another domain */
12368                 if ((target_domain == mono_domain_get ()) || info->domain_neutral) {
12369                         code = info->code_start;
12370 //                      printf("Discarding code for method %s\n", method->name);
12371                 }
12372         }
12373         
12374         if (code == NULL) {
12375                 mono_internal_hash_table_insert (&target_domain->jit_code_hash, method, cfg->jit_info);
12376                 code = cfg->native_code;
12377
12378                 if (cfg->generic_sharing_context && mono_method_is_generic_sharable_impl (method)) {
12379                         /* g_print ("inserting method %s.%s.%s\n", method->klass->name_space, method->klass->name, method->name); */
12380                         mono_domain_register_shared_generic (target_domain, 
12381                                 mono_method_get_declaring_generic_method (method), cfg->jit_info);
12382                         mono_stats.generics_shared_methods++;
12383                 }
12384         }
12385
12386         mono_destroy_compile (cfg);
12387
12388         if (target_domain->jump_target_hash) {
12389                 MonoJumpInfo patch_info;
12390                 GSList *list, *tmp;
12391                 list = g_hash_table_lookup (target_domain->jump_target_hash, method);
12392                 if (list) {
12393                         patch_info.next = NULL;
12394                         patch_info.ip.i = 0;
12395                         patch_info.type = MONO_PATCH_INFO_METHOD_JUMP;
12396                         patch_info.data.method = method;
12397                         g_hash_table_remove (target_domain->jump_target_hash, method);
12398                 }
12399                 for (tmp = list; tmp; tmp = tmp->next)
12400                         mono_arch_patch_code (NULL, target_domain, tmp->data, &patch_info, TRUE);
12401                 g_slist_free (list);
12402         }
12403
12404         mono_domain_unlock (target_domain);
12405
12406         mono_runtime_class_init (mono_class_vtable (target_domain, method->klass));
12407         return code;
12408 }
12409
12410 static gpointer
12411 mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt)
12412 {
12413         MonoDomain *target_domain, *domain = mono_domain_get ();
12414         MonoJitInfo *info;
12415         gpointer p;
12416         MonoJitICallInfo *callinfo = NULL;
12417
12418         /*
12419          * ICALL wrappers are handled specially, since there is only one copy of them
12420          * shared by all appdomains.
12421          */
12422         if ((method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && (strstr (method->name, "__icall_wrapper_") == method->name)) {
12423                 const char *icall_name;
12424
12425                 icall_name = method->name + strlen ("__icall_wrapper_");
12426                 g_assert (icall_name);
12427                 callinfo = mono_find_jit_icall_by_name (icall_name);
12428                 g_assert (callinfo);
12429
12430                 /* Must be domain neutral since there is only one copy */
12431                 opt |= MONO_OPT_SHARED;
12432         }
12433
12434         if (opt & MONO_OPT_SHARED)
12435                 target_domain = mono_get_root_domain ();
12436         else 
12437                 target_domain = domain;
12438
12439         mono_domain_lock (target_domain);
12440
12441         if ((info = lookup_method (target_domain, method))) {
12442                 /* We can't use a domain specific method in another domain */
12443                 if (! ((domain != target_domain) && !info->domain_neutral)) {
12444                         mono_domain_unlock (target_domain);
12445                         mono_jit_stats.methods_lookups++;
12446                         mono_runtime_class_init (mono_class_vtable (domain, method->klass));
12447                         return mono_create_ftnptr (target_domain, info->code_start);
12448                 }
12449         }
12450
12451         mono_domain_unlock (target_domain);
12452         p = mono_create_ftnptr (target_domain, mono_jit_compile_method_inner (method, target_domain, opt));
12453
12454         if (callinfo) {
12455                 mono_jit_lock ();
12456                 if (!callinfo->wrapper) {
12457                         callinfo->wrapper = p;
12458                         mono_register_jit_icall_wrapper (callinfo, p);
12459                         mono_debug_add_icall_wrapper (method, callinfo);
12460                 }
12461                 mono_jit_unlock ();
12462         }
12463
12464         return p;
12465 }
12466
12467 static gpointer
12468 mono_jit_compile_method (MonoMethod *method)
12469 {
12470         return mono_jit_compile_method_with_opt (method, default_opt);
12471 }
12472
12473 static void
12474 invalidated_delegate_trampoline (char *desc)
12475 {
12476         g_error ("Unmanaged code called delegate of type %s which was already garbage collected.\n"
12477                  "See http://www.go-mono.com/delegate.html for an explanation and ways to fix this.",
12478                  desc);
12479 }
12480
12481 /*
12482  * mono_jit_free_method:
12483  *
12484  *  Free all memory allocated by the JIT for METHOD.
12485  */
12486 static void
12487 mono_jit_free_method (MonoDomain *domain, MonoMethod *method)
12488 {
12489         MonoJitDynamicMethodInfo *ji;
12490         gboolean destroy = TRUE;
12491
12492         g_assert (method->dynamic);
12493
12494         mono_domain_lock (domain);
12495         ji = mono_dynamic_code_hash_lookup (domain, method);
12496         mono_domain_unlock (domain);
12497
12498         if (!ji)
12499                 return;
12500         mono_domain_lock (domain);
12501         g_hash_table_remove (domain->dynamic_code_hash, method);
12502         mono_internal_hash_table_remove (&domain->jit_code_hash, method);
12503         g_hash_table_remove (domain->jump_trampoline_hash, method);
12504         mono_domain_unlock (domain);
12505
12506 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
12507         if (debug_options.keep_delegates && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
12508                 /*
12509                  * Instead of freeing the code, change it to call an error routine
12510                  * so people can fix their code.
12511                  */
12512                 char *type = mono_type_full_name (&method->klass->byval_arg);
12513                 char *type_and_method = g_strdup_printf ("%s.%s", type, method->name);
12514
12515                 g_free (type);
12516                 mono_arch_invalidate_method (ji->ji, invalidated_delegate_trampoline, type_and_method);
12517                 destroy = FALSE;
12518         }
12519 #endif
12520
12521         /* 
12522          * This needs to be done before freeing code_mp, since the code address is the
12523          * key in the table, so if we free the code_mp first, another thread can grab the
12524          * same code address and replace our entry in the table.
12525          */
12526         mono_jit_info_table_remove (domain, ji->ji);
12527
12528         if (destroy)
12529                 mono_code_manager_destroy (ji->code_mp);
12530         mono_thread_hazardous_free_or_queue (ji->ji, g_free);
12531         g_free (ji);
12532 }
12533
12534 gpointer
12535 mono_jit_find_compiled_method (MonoDomain *domain, MonoMethod *method)
12536 {
12537         MonoDomain *target_domain;
12538         MonoJitInfo *info;
12539
12540         if (default_opt & MONO_OPT_SHARED)
12541                 target_domain = mono_get_root_domain ();
12542         else 
12543                 target_domain = domain;
12544
12545         mono_domain_lock (target_domain);
12546
12547         if ((info = lookup_method (target_domain, method))) {
12548                 /* We can't use a domain specific method in another domain */
12549                 if (! ((domain != target_domain) && !info->domain_neutral)) {
12550                         mono_domain_unlock (target_domain);
12551                         mono_jit_stats.methods_lookups++;
12552                         return info->code_start;
12553                 }
12554         }
12555
12556         mono_domain_unlock (target_domain);
12557
12558         return NULL;
12559 }
12560
12561 /**
12562  * mono_jit_runtime_invoke:
12563  * @method: the method to invoke
12564  * @obj: this pointer
12565  * @params: array of parameter values.
12566  * @exc: used to catch exceptions objects
12567  */
12568 static MonoObject*
12569 mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
12570 {
12571         MonoMethod *to_compile;
12572         MonoMethod *invoke;
12573         MonoObject *(*runtime_invoke) (MonoObject *this, void **params, MonoObject **exc, void* compiled_method);
12574         void* compiled_method;
12575
12576         if (obj == NULL && !(method->flags & METHOD_ATTRIBUTE_STATIC) && !method->string_ctor && (method->wrapper_type == 0)) {
12577                 g_warning ("Ignoring invocation of an instance method on a NULL instance.\n");
12578                 return NULL;
12579         }
12580
12581         if ((method->flags & METHOD_ATTRIBUTE_STATIC) &&
12582                         mono_class_generic_sharing_enabled (method->klass) &&
12583                         mono_method_is_generic_sharable_impl (method)) {
12584                 to_compile = mono_marshal_get_static_rgctx_invoke (method);
12585         } else {
12586                 to_compile = method;
12587         }
12588
12589         invoke = mono_marshal_get_runtime_invoke (method);
12590         runtime_invoke = mono_jit_compile_method (invoke);
12591         
12592         /* We need this here becuase mono_marshal_get_runtime_invoke can be place 
12593          * the helper method in System.Object and not the target class
12594          */
12595         mono_runtime_class_init (mono_class_vtable (mono_domain_get (), method->klass));
12596
12597         if (method->klass->rank && (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
12598                 (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
12599                 /* 
12600                  * Array Get/Set/Address methods. The JIT implements them using inline code 
12601                  * inside the runtime invoke wrappers, so no need to compile them.
12602                  */
12603                 compiled_method = NULL;
12604         } else {
12605                 compiled_method = mono_jit_compile_method (to_compile);
12606         }
12607         return runtime_invoke (obj, params, exc, compiled_method);
12608 }
12609
12610 #ifdef MONO_GET_CONTEXT
12611 #define GET_CONTEXT MONO_GET_CONTEXT
12612 #endif
12613
12614 #ifndef GET_CONTEXT
12615 #ifdef PLATFORM_WIN32
12616 #define GET_CONTEXT \
12617         struct sigcontext *ctx = (struct sigcontext*)_dummy;
12618 #else
12619 #ifdef MONO_ARCH_USE_SIGACTION
12620 #define GET_CONTEXT \
12621     void *ctx = context;
12622 #elif defined(__sparc__)
12623 #define GET_CONTEXT \
12624     void *ctx = sigctx;
12625 #else
12626 #define GET_CONTEXT \
12627         void **_p = (void **)&_dummy; \
12628         struct sigcontext *ctx = (struct sigcontext *)++_p;
12629 #endif
12630 #endif
12631 #endif
12632
12633 #ifdef MONO_ARCH_USE_SIGACTION
12634 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy, siginfo_t *info, void *context)
12635 #elif defined(__sparc__)
12636 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy, void *sigctx)
12637 #else
12638 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy)
12639 #endif
12640
12641 static void
12642 SIG_HANDLER_SIGNATURE (sigfpe_signal_handler)
12643 {
12644         MonoException *exc = NULL;
12645 #ifndef MONO_ARCH_USE_SIGACTION
12646         void *info = NULL;
12647 #endif
12648         GET_CONTEXT;
12649
12650 #if defined(MONO_ARCH_HAVE_IS_INT_OVERFLOW)
12651         if (mono_arch_is_int_overflow (ctx, info))
12652                 exc = mono_get_exception_arithmetic ();
12653         else
12654                 exc = mono_get_exception_divide_by_zero ();
12655 #else
12656         exc = mono_get_exception_divide_by_zero ();
12657 #endif
12658         
12659         mono_arch_handle_exception (ctx, exc, FALSE);
12660 }
12661
12662 static void
12663 SIG_HANDLER_SIGNATURE (sigill_signal_handler)
12664 {
12665         MonoException *exc;
12666         GET_CONTEXT;
12667
12668         exc = mono_get_exception_execution_engine ("SIGILL");
12669         
12670         mono_arch_handle_exception (ctx, exc, FALSE);
12671 }
12672
12673 static void
12674 SIG_HANDLER_SIGNATURE (sigsegv_signal_handler)
12675 {
12676 #ifndef MONO_ARCH_SIGSEGV_ON_ALTSTACK
12677         MonoException *exc = NULL;
12678 #endif
12679         MonoJitInfo *ji;
12680
12681 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
12682         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
12683 #endif
12684         GET_CONTEXT;
12685
12686 #ifdef MONO_ARCH_USE_SIGACTION
12687         if (debug_options.collect_pagefault_stats) {
12688                 if (mono_raw_buffer_is_pagefault (info->si_addr)) {
12689                         mono_raw_buffer_handle_pagefault (info->si_addr);
12690                         return;
12691                 }
12692                 if (mono_aot_is_pagefault (info->si_addr)) {
12693                         mono_aot_handle_pagefault (info->si_addr);
12694                         return;
12695                 }
12696         }
12697 #endif
12698
12699         ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context (ctx));
12700
12701 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
12702         /* we got a stack overflow in the soft-guard pages
12703          * There are two cases:
12704          * 1) managed code caused the overflow: we unprotect the soft-guard page
12705          * and let the arch-specific code trigger the exception handling mechanism
12706          * in the thread stack. The soft-guard pages will be protected again as the stack is unwound.
12707          * 2) unmanaged code caused the overflow: we unprotect the soft-guard page
12708          * and hope we can continue with those enabled, at least until the hard-guard page
12709          * is hit. The alternative to continuing here is to just print a message and abort.
12710          * We may add in the future the code to protect the pages again in the codepath
12711          * when we return from unmanaged to managed code.
12712          */
12713         if (jit_tls->stack_ovf_guard_size && (guint8*)info->si_addr >= (guint8*)jit_tls->stack_ovf_guard_base &&
12714                         (guint8*)info->si_addr < (guint8*)jit_tls->stack_ovf_guard_base + jit_tls->stack_ovf_guard_size) {
12715                 mono_mprotect (jit_tls->stack_ovf_guard_base, jit_tls->stack_ovf_guard_size, MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
12716                 if (ji) {
12717                         mono_arch_handle_altstack_exception (ctx, info->si_addr, TRUE);
12718                 } else {
12719                         /* We print a message: after this even managed stack overflows
12720                          * may crash the runtime
12721                          */
12722                         fprintf (stderr, "Stack overflow in unmanaged: IP: %p, fault addr: %p\n", mono_arch_ip_from_context (ctx), (gpointer)info->si_addr);
12723                 }
12724                 return;
12725         }
12726         /* The hard-guard page has been hit: there is not much we can do anymore
12727          * Print a hopefully clear message and abort.
12728          */
12729         if (jit_tls->stack_size && 
12730                         ABS ((guint8*)info->si_addr - ((guint8*)jit_tls->end_of_stack - jit_tls->stack_size)) < 32768) {
12731                 const char *method;
12732                 /* we don't do much now, but we can warn the user with a useful message */
12733                 fprintf (stderr, "Stack overflow: IP: %p, fault addr: %p\n", mono_arch_ip_from_context (ctx), (gpointer)info->si_addr);
12734                 if (ji && ji->method)
12735                         method = mono_method_full_name (ji->method, TRUE);
12736                 else
12737                         method = "Unmanaged";
12738                 fprintf (stderr, "At %s\n", method);
12739                 abort ();
12740         } else {
12741                 mono_arch_handle_altstack_exception (ctx, info->si_addr, FALSE);
12742         }
12743 #else
12744
12745         if (!ji) {
12746                 mono_handle_native_sigsegv (SIGSEGV, ctx);
12747         }
12748                         
12749         mono_arch_handle_exception (ctx, exc, FALSE);
12750 #endif
12751 }
12752
12753 #ifndef PLATFORM_WIN32
12754
12755 static void
12756 SIG_HANDLER_SIGNATURE (sigabrt_signal_handler)
12757 {
12758         MonoJitInfo *ji;
12759         GET_CONTEXT;
12760
12761         ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
12762         if (!ji) {
12763                 mono_handle_native_sigsegv (SIGABRT, ctx);
12764         }
12765 }
12766
12767 static void
12768 SIG_HANDLER_SIGNATURE (sigusr1_signal_handler)
12769 {
12770         gboolean running_managed;
12771         MonoException *exc;
12772         MonoThread *thread = mono_thread_current ();
12773         void *ji;
12774         
12775         GET_CONTEXT;
12776
12777         if (thread->thread_dump_requested) {
12778                 thread->thread_dump_requested = FALSE;
12779
12780                 mono_print_thread_dump (ctx);
12781         }
12782
12783         /*
12784          * FIXME:
12785          * This is an async signal, so the code below must not call anything which
12786          * is not async safe. That includes the pthread locking functions. If we
12787          * know that we interrupted managed code, then locking is safe.
12788          */
12789         ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
12790         running_managed = ji != NULL;
12791         
12792         exc = mono_thread_request_interruption (running_managed); 
12793         if (!exc) return;
12794
12795         mono_arch_handle_exception (ctx, exc, FALSE);
12796 }
12797
12798 static void
12799 SIG_HANDLER_SIGNATURE (sigprof_signal_handler)
12800 {
12801         GET_CONTEXT;
12802
12803         mono_profiler_stat_hit (mono_arch_ip_from_context (ctx), ctx);
12804 }
12805
12806 static void
12807 SIG_HANDLER_SIGNATURE (sigquit_signal_handler)
12808 {
12809         GET_CONTEXT;
12810
12811         printf ("Full thread dump:\n");
12812
12813         mono_threads_request_thread_dump ();
12814
12815         /*
12816          * print_thread_dump () skips the current thread, since sending a signal
12817          * to it would invoke the signal handler below the sigquit signal handler,
12818          * and signal handlers don't create an lmf, so the stack walk could not
12819          * be performed.
12820          */
12821         mono_print_thread_dump (ctx);
12822 }
12823
12824 static void
12825 SIG_HANDLER_SIGNATURE (sigusr2_signal_handler)
12826 {
12827         gboolean enabled = mono_trace_is_enabled ();
12828
12829         mono_trace_enable (!enabled);
12830 }
12831
12832 #endif
12833
12834 static void
12835 SIG_HANDLER_SIGNATURE (sigint_signal_handler)
12836 {
12837         MonoException *exc;
12838         GET_CONTEXT;
12839
12840         exc = mono_get_exception_execution_engine ("Interrupted (SIGINT).");
12841         
12842         mono_arch_handle_exception (ctx, exc, FALSE);
12843 }
12844
12845 #ifdef PLATFORM_MACOSX
12846
12847 /*
12848  * This code disables the CrashReporter of MacOS X by installing
12849  * a dummy Mach exception handler.
12850  */
12851
12852 /*
12853  * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/exc_server.html
12854  */
12855 extern
12856 boolean_t
12857 exc_server (mach_msg_header_t *request_msg,
12858             mach_msg_header_t *reply_msg);
12859
12860 /*
12861  * The exception message
12862  */
12863 typedef struct {
12864         mach_msg_base_t msg;  /* common mach message header */
12865         char payload [1024];  /* opaque */
12866 } mach_exception_msg_t;
12867
12868 /* The exception port */
12869 static mach_port_t mach_exception_port = VM_MAP_NULL;
12870
12871 /*
12872  * Implicitly called by exc_server. Must be public.
12873  *
12874  * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/catch_exception_raise.html
12875  */
12876 kern_return_t
12877 catch_exception_raise (
12878         mach_port_t exception_port,
12879         mach_port_t thread,
12880         mach_port_t task,
12881         exception_type_t exception,
12882         exception_data_t code,
12883         mach_msg_type_number_t code_count)
12884 {
12885         /* consume the exception */
12886         return KERN_FAILURE;
12887 }
12888
12889 /*
12890  * Exception thread handler.
12891  */
12892 static
12893 void *
12894 mach_exception_thread (void *arg)
12895 {
12896         for (;;) {
12897                 mach_exception_msg_t request;
12898                 mach_exception_msg_t reply;
12899                 mach_msg_return_t result;
12900
12901                 /* receive from "mach_exception_port" */
12902                 result = mach_msg (&request.msg.header,
12903                                    MACH_RCV_MSG | MACH_RCV_LARGE,
12904                                    0,
12905                                    sizeof (request),
12906                                    mach_exception_port,
12907                                    MACH_MSG_TIMEOUT_NONE,
12908                                    MACH_PORT_NULL);
12909
12910                 g_assert (result == MACH_MSG_SUCCESS);
12911
12912                 /* dispatch to catch_exception_raise () */
12913                 exc_server (&request.msg.header, &reply.msg.header);
12914
12915                 /* send back to sender */
12916                 result = mach_msg (&reply.msg.header,
12917                                    MACH_SEND_MSG,
12918                                    reply.msg.header.msgh_size,
12919                                    0,
12920                                    MACH_PORT_NULL,
12921                                    MACH_MSG_TIMEOUT_NONE,
12922                                    MACH_PORT_NULL);
12923
12924                 g_assert (result == MACH_MSG_SUCCESS);
12925         }
12926         return NULL;
12927 }
12928
12929 static void
12930 macosx_register_exception_handler ()
12931 {
12932         mach_port_t task;
12933         pthread_attr_t attr;
12934         pthread_t thread;
12935
12936         if (mach_exception_port != VM_MAP_NULL)
12937                 return;
12938
12939         task = mach_task_self ();
12940
12941         /* create the "mach_exception_port" with send & receive rights */
12942         g_assert (mach_port_allocate (task, MACH_PORT_RIGHT_RECEIVE,
12943                                       &mach_exception_port) == KERN_SUCCESS);
12944         g_assert (mach_port_insert_right (task, mach_exception_port, mach_exception_port,
12945                                           MACH_MSG_TYPE_MAKE_SEND) == KERN_SUCCESS);
12946
12947         /* create the exception handler thread */
12948         g_assert (!pthread_attr_init (&attr));
12949         g_assert (!pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED));
12950         g_assert (!pthread_create (&thread, &attr, mach_exception_thread, NULL));
12951         pthread_attr_destroy (&attr);
12952
12953         /*
12954          * register "mach_exception_port" as a receiver for the
12955          * EXC_BAD_ACCESS exception
12956          *
12957          * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/task_set_exception_ports.html
12958          */
12959         g_assert (task_set_exception_ports (task, EXC_MASK_BAD_ACCESS,
12960                                             mach_exception_port,
12961                                             EXCEPTION_DEFAULT,
12962                                             MACHINE_THREAD_STATE) == KERN_SUCCESS);
12963 }
12964 #endif
12965
12966 #ifndef PLATFORM_WIN32
12967 static void
12968 add_signal_handler (int signo, gpointer handler)
12969 {
12970         struct sigaction sa;
12971
12972 #ifdef MONO_ARCH_USE_SIGACTION
12973         sa.sa_sigaction = handler;
12974         sigemptyset (&sa.sa_mask);
12975         sa.sa_flags = SA_SIGINFO;
12976 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
12977         if (signo == SIGSEGV)
12978                 sa.sa_flags |= SA_ONSTACK;
12979 #endif
12980 #else
12981         sa.sa_handler = handler;
12982         sigemptyset (&sa.sa_mask);
12983         sa.sa_flags = 0;
12984 #endif
12985         g_assert (sigaction (signo, &sa, NULL) != -1);
12986 }
12987
12988 static void
12989 remove_signal_handler (int signo)
12990 {
12991         struct sigaction sa;
12992
12993         sa.sa_handler = SIG_DFL;
12994         sigemptyset (&sa.sa_mask);
12995         sa.sa_flags = 0;
12996
12997         g_assert (sigaction (signo, &sa, NULL) != -1);
12998 }
12999 #endif
13000
13001 static void
13002 mono_runtime_install_handlers (void)
13003 {
13004 #ifdef PLATFORM_WIN32
13005         win32_seh_init();
13006         win32_seh_set_handler(SIGFPE, sigfpe_signal_handler);
13007         win32_seh_set_handler(SIGILL, sigill_signal_handler);
13008         win32_seh_set_handler(SIGSEGV, sigsegv_signal_handler);
13009         if (debug_options.handle_sigint)
13010                 win32_seh_set_handler(SIGINT, sigint_signal_handler);
13011
13012 #else /* !PLATFORM_WIN32 */
13013
13014
13015 #ifdef PLATFORM_MACOSX
13016         macosx_register_exception_handler ();
13017 #endif
13018
13019         if (debug_options.handle_sigint)
13020                 add_signal_handler (SIGINT, sigint_signal_handler);
13021
13022         add_signal_handler (SIGFPE, sigfpe_signal_handler);
13023         add_signal_handler (SIGQUIT, sigquit_signal_handler);
13024         add_signal_handler (SIGILL, sigill_signal_handler);
13025         add_signal_handler (SIGBUS, sigsegv_signal_handler);
13026         if (mono_jit_trace_calls != NULL)
13027                 add_signal_handler (SIGUSR2, sigusr2_signal_handler);
13028
13029         add_signal_handler (mono_thread_get_abort_signal (), sigusr1_signal_handler);
13030         signal (SIGPIPE, SIG_IGN);
13031
13032         add_signal_handler (SIGABRT, sigabrt_signal_handler);
13033
13034         /* catch SIGSEGV */
13035         add_signal_handler (SIGSEGV, sigsegv_signal_handler);
13036 #endif /* PLATFORM_WIN32 */
13037 }
13038
13039 static void
13040 mono_runtime_cleanup_handlers (void)
13041 {
13042 #ifdef PLATFORM_WIN32
13043         win32_seh_cleanup();
13044 #else
13045         if (debug_options.handle_sigint)
13046                 remove_signal_handler (SIGINT);
13047
13048         remove_signal_handler (SIGFPE);
13049         remove_signal_handler (SIGQUIT);
13050         remove_signal_handler (SIGILL);
13051         remove_signal_handler (SIGBUS);
13052         if (mono_jit_trace_calls != NULL)
13053                 remove_signal_handler (SIGUSR2);
13054
13055         remove_signal_handler (mono_thread_get_abort_signal ());
13056
13057         remove_signal_handler (SIGABRT);
13058
13059         remove_signal_handler (SIGSEGV);
13060 #endif /* PLATFORM_WIN32 */
13061 }
13062
13063
13064 #ifdef HAVE_LINUX_RTC_H
13065 #include <linux/rtc.h>
13066 #include <sys/ioctl.h>
13067 #include <fcntl.h>
13068 static int rtc_fd = -1;
13069
13070 static int
13071 enable_rtc_timer (gboolean enable)
13072 {
13073         int flags;
13074         flags = fcntl (rtc_fd, F_GETFL);
13075         if (flags < 0) {
13076                 perror ("getflags");
13077                 return 0;
13078         }
13079         if (enable)
13080                 flags |= FASYNC;
13081         else
13082                 flags &= ~FASYNC;
13083         if (fcntl (rtc_fd, F_SETFL, flags) == -1) {
13084                 perror ("setflags");
13085                 return 0;
13086         }
13087         return 1;
13088 }
13089 #endif
13090
13091 #ifdef PLATFORM_WIN32
13092 static HANDLE win32_main_thread;
13093 static MMRESULT win32_timer;
13094
13095 static void CALLBACK
13096 win32_time_proc (UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2)
13097 {
13098         CONTEXT context;
13099
13100         context.ContextFlags = CONTEXT_CONTROL;
13101         if (GetThreadContext (win32_main_thread, &context)) {
13102 #ifdef _WIN64
13103                 mono_profiler_stat_hit ((guchar *) context.Rip, &context);
13104 #else
13105                 mono_profiler_stat_hit ((guchar *) context.Eip, &context);
13106 #endif
13107         }
13108 }
13109 #endif
13110
13111 static void
13112 setup_stat_profiler (void)
13113 {
13114 #ifdef ITIMER_PROF
13115         struct itimerval itval;
13116         static int inited = 0;
13117 #ifdef HAVE_LINUX_RTC_H
13118         const char *rtc_freq;
13119         if (!inited && (rtc_freq = g_getenv ("MONO_RTC"))) {
13120                 int freq = 0;
13121                 inited = 1;
13122                 if (*rtc_freq)
13123                         freq = atoi (rtc_freq);
13124                 if (!freq)
13125                         freq = 1024;
13126                 rtc_fd = open ("/dev/rtc", O_RDONLY);
13127                 if (rtc_fd == -1) {
13128                         perror ("open /dev/rtc");
13129                         return;
13130                 }
13131                 add_signal_handler (SIGPROF, sigprof_signal_handler);
13132                 if (ioctl (rtc_fd, RTC_IRQP_SET, freq) == -1) {
13133                         perror ("set rtc freq");
13134                         return;
13135                 }
13136                 if (ioctl (rtc_fd, RTC_PIE_ON, 0) == -1) {
13137                         perror ("start rtc");
13138                         return;
13139                 }
13140                 if (fcntl (rtc_fd, F_SETSIG, SIGPROF) == -1) {
13141                         perror ("setsig");
13142                         return;
13143                 }
13144                 if (fcntl (rtc_fd, F_SETOWN, getpid ()) == -1) {
13145                         perror ("setown");
13146                         return;
13147                 }
13148                 enable_rtc_timer (TRUE);
13149                 return;
13150         }
13151         if (rtc_fd >= 0)
13152                 return;
13153 #endif
13154
13155         itval.it_interval.tv_usec = 999;
13156         itval.it_interval.tv_sec = 0;
13157         itval.it_value = itval.it_interval;
13158         setitimer (ITIMER_PROF, &itval, NULL);
13159         if (inited)
13160                 return;
13161         inited = 1;
13162         add_signal_handler (SIGPROF, sigprof_signal_handler);
13163 #elif defined (PLATFORM_WIN32)
13164         static int inited = 0;
13165         TIMECAPS timecaps;
13166
13167         if (inited)
13168                 return;
13169
13170         inited = 1;
13171         if (timeGetDevCaps (&timecaps, sizeof (timecaps)) != TIMERR_NOERROR)
13172                 return;
13173
13174         if ((win32_main_thread = OpenThread (READ_CONTROL | THREAD_GET_CONTEXT, FALSE, GetCurrentThreadId ())) == NULL)
13175                 return;
13176
13177         if (timeBeginPeriod (1) != TIMERR_NOERROR)
13178                 return;
13179
13180         if ((win32_timer = timeSetEvent (1, 0, win32_time_proc, 0, TIME_PERIODIC)) == 0) {
13181                 timeEndPeriod (1);
13182                 return;
13183         }
13184 #endif
13185 }
13186
13187 /* mono_jit_create_remoting_trampoline:
13188  * @method: pointer to the method info
13189  *
13190  * Creates a trampoline which calls the remoting functions. This
13191  * is used in the vtable of transparent proxies.
13192  * 
13193  * Returns: a pointer to the newly created code 
13194  */
13195 static gpointer
13196 mono_jit_create_remoting_trampoline (MonoMethod *method, MonoRemotingTarget target)
13197 {
13198         MonoMethod *nm;
13199         guint8 *addr = NULL;
13200
13201         if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) || 
13202             (mono_method_signature (method)->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class))) {
13203                 nm = mono_marshal_get_remoting_invoke_for_target (method, target);
13204                 addr = mono_compile_method (nm);
13205         } else {
13206                 addr = mono_compile_method (method);
13207         }
13208         return mono_get_addr_from_ftnptr (addr);
13209 }
13210
13211 #ifdef MONO_ARCH_HAVE_IMT
13212 static gpointer
13213 mini_get_imt_trampoline (void)
13214 {
13215         static gpointer tramp = NULL;
13216         if (!tramp)
13217                 tramp =  mono_arch_create_specific_trampoline (MONO_FAKE_IMT_METHOD, MONO_TRAMPOLINE_GENERIC, mono_get_root_domain (), NULL);
13218         return tramp;
13219 }
13220 #endif
13221
13222 #ifdef MONO_ARCH_COMMON_VTABLE_TRAMPOLINE
13223 gpointer
13224 mini_get_vtable_trampoline (void)
13225 {
13226         static gpointer tramp = NULL;
13227         if (!tramp)
13228                 tramp =  mono_arch_create_specific_trampoline (MONO_FAKE_VTABLE_METHOD, MONO_TRAMPOLINE_GENERIC, mono_get_root_domain (), NULL);
13229         return tramp;
13230 }
13231 #endif
13232
13233 static void
13234 mini_parse_debug_options (void)
13235 {
13236         char *options = getenv ("MONO_DEBUG");
13237         gchar **args, **ptr;
13238         
13239         if (!options)
13240                 return;
13241
13242         args = g_strsplit (options, ",", -1);
13243
13244         for (ptr = args; ptr && *ptr; ptr++) {
13245                 const char *arg = *ptr;
13246
13247                 if (!strcmp (arg, "handle-sigint"))
13248                         debug_options.handle_sigint = TRUE;
13249                 else if (!strcmp (arg, "keep-delegates"))
13250                         debug_options.keep_delegates = TRUE;
13251                 else if (!strcmp (arg, "collect-pagefault-stats"))
13252                         debug_options.collect_pagefault_stats = TRUE;
13253                 else if (!strcmp (arg, "break-on-unverified"))
13254                         debug_options.break_on_unverified = TRUE;
13255                 else if (!strcmp (arg, "no-gdb-backtrace"))
13256                         debug_options.no_gdb_backtrace = TRUE;
13257                 else {
13258                         fprintf (stderr, "Invalid option for the MONO_DEBUG env variable: %s\n", arg);
13259                         fprintf (stderr, "Available options: 'handle-sigint', 'keep-delegates', 'collect-pagefault-stats', 'break-on-unverified', 'no-gdb-backtrace'\n");
13260                         exit (1);
13261                 }
13262         }
13263 }
13264
13265 MonoDebugOptions *
13266 mini_get_debug_options (void)
13267 {
13268         return &debug_options;
13269 }
13270
13271 MonoDomain *
13272 mini_init (const char *filename, const char *runtime_version)
13273 {
13274         MonoDomain *domain;
13275
13276 #ifdef __linux__
13277         if (access ("/proc/self/maps", F_OK) != 0) {
13278                 g_print ("Mono requires /proc to be mounted.\n");
13279                 exit (1);
13280         }
13281 #endif
13282
13283         /* Happens when using the embedding interface */
13284         if (!default_opt_set)
13285                 default_opt = mono_parse_default_optimizations (NULL);
13286
13287         InitializeCriticalSection (&jit_mutex);
13288
13289         if (!global_codeman)
13290                 global_codeman = mono_code_manager_new ();
13291         jit_icall_name_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
13292
13293         mono_arch_cpu_init ();
13294
13295         mono_arch_init ();
13296
13297         mono_trampolines_init ();
13298
13299         mono_exceptions_init ();
13300
13301         if (!g_thread_supported ())
13302                 g_thread_init (NULL);
13303
13304         if (getenv ("MONO_DEBUG") != NULL)
13305                 mini_parse_debug_options ();
13306
13307         mono_gc_base_init ();
13308
13309         mono_jit_tls_id = TlsAlloc ();
13310         setup_jit_tls_data ((gpointer)-1, mono_thread_abort);
13311
13312         mono_burg_init ();
13313
13314         if (default_opt & MONO_OPT_AOT)
13315                 mono_aot_init ();
13316
13317         mono_runtime_install_handlers ();
13318         mono_threads_install_cleanup (mini_thread_cleanup);
13319
13320 #ifdef MONO_ARCH_HAVE_NOTIFY_PENDING_EXC
13321         // This is experimental code so provide an env var to switch it off
13322         if (getenv ("MONO_DISABLE_PENDING_EXCEPTIONS")) {
13323                 printf ("MONO_DISABLE_PENDING_EXCEPTIONS env var set.\n");
13324         } else {
13325                 check_for_pending_exc = FALSE;
13326                 mono_threads_install_notify_pending_exc (mono_arch_notify_pending_exc);
13327         }
13328 #endif
13329
13330 #define JIT_TRAMPOLINES_WORK
13331 #ifdef JIT_TRAMPOLINES_WORK
13332         mono_install_compile_method (mono_jit_compile_method);
13333         mono_install_free_method (mono_jit_free_method);
13334         mono_install_trampoline (mono_create_jit_trampoline);
13335         mono_install_jump_trampoline (mono_create_jump_trampoline);
13336         mono_install_remoting_trampoline (mono_jit_create_remoting_trampoline);
13337         mono_install_delegate_trampoline (mono_create_delegate_trampoline);
13338 #endif
13339 #define JIT_INVOKE_WORKS
13340 #ifdef JIT_INVOKE_WORKS
13341         mono_install_runtime_invoke (mono_jit_runtime_invoke);
13342         mono_install_handler (mono_arch_get_throw_exception ());
13343 #endif
13344         mono_install_stack_walk (mono_jit_walk_stack);
13345         mono_install_init_vtable (mono_aot_init_vtable);
13346         mono_install_get_cached_class_info (mono_aot_get_cached_class_info);
13347         mono_install_get_class_from_name (mono_aot_get_class_from_name);
13348         mono_install_jit_info_find_in_aot (mono_aot_find_jit_info);
13349
13350         if (debug_options.collect_pagefault_stats) {
13351                 mono_raw_buffer_set_make_unreadable (TRUE);
13352                 mono_aot_set_make_unreadable (TRUE);
13353         }
13354
13355         if (runtime_version)
13356                 domain = mono_init_version (filename, runtime_version);
13357         else
13358                 domain = mono_init_from_assembly (filename, filename);
13359 #ifdef MONO_ARCH_HAVE_IMT
13360         mono_install_imt_thunk_builder (mono_arch_build_imt_thunk);
13361         mono_install_imt_trampoline (mini_get_imt_trampoline ());
13362 #if MONO_ARCH_COMMON_VTABLE_TRAMPOLINE
13363         mono_install_vtable_trampoline (mini_get_vtable_trampoline ());
13364 #endif
13365 #endif
13366         mono_icall_init ();
13367
13368         mono_add_internal_call ("System.Diagnostics.StackFrame::get_frame_info", 
13369                                 ves_icall_get_frame_info);
13370         mono_add_internal_call ("System.Diagnostics.StackTrace::get_trace", 
13371                                 ves_icall_get_trace);
13372         mono_add_internal_call ("System.Exception::get_trace", 
13373                                 ves_icall_System_Exception_get_trace);
13374         mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityFrame",
13375                                 ves_icall_System_Security_SecurityFrame_GetSecurityFrame);
13376         mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityStack",
13377                                 ves_icall_System_Security_SecurityFrame_GetSecurityStack);
13378         mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers", 
13379                                 mono_runtime_install_handlers);
13380
13381
13382         create_helper_signature ();
13383
13384 #define JIT_CALLS_WORK
13385 #ifdef JIT_CALLS_WORK
13386         /* Needs to be called here since register_jit_icall depends on it */
13387         mono_marshal_init ();
13388
13389         mono_arch_register_lowlevel_calls ();
13390         register_icall (mono_profiler_method_enter, "mono_profiler_method_enter", NULL, TRUE);
13391         register_icall (mono_profiler_method_leave, "mono_profiler_method_leave", NULL, TRUE);
13392         register_icall (mono_trace_enter_method, "mono_trace_enter_method", NULL, TRUE);
13393         register_icall (mono_trace_leave_method, "mono_trace_leave_method", NULL, TRUE);
13394         register_icall (mono_get_lmf_addr, "mono_get_lmf_addr", "ptr", TRUE);
13395         register_icall (mono_jit_thread_attach, "mono_jit_thread_attach", "void", TRUE);
13396         register_icall (mono_domain_get, "mono_domain_get", "ptr", TRUE);
13397
13398         register_icall (mono_arch_get_throw_exception (), "mono_arch_throw_exception", "void object", TRUE);
13399         register_icall (mono_arch_get_rethrow_exception (), "mono_arch_rethrow_exception", "void object", TRUE);
13400         register_icall (mono_arch_get_throw_exception_by_name (), "mono_arch_throw_exception_by_name", "void ptr", TRUE); 
13401 #if MONO_ARCH_HAVE_THROW_CORLIB_EXCEPTION
13402         register_icall (mono_arch_get_throw_corlib_exception (), "mono_arch_throw_corlib_exception", 
13403                                  "void ptr", TRUE);
13404 #endif
13405         register_icall (mono_thread_get_undeniable_exception, "mono_thread_get_undeniable_exception", "object", FALSE);
13406         register_icall (mono_thread_interruption_checkpoint, "mono_thread_interruption_checkpoint", "void", FALSE);
13407         register_icall (mono_thread_force_interruption_checkpoint, "mono_thread_force_interruption_checkpoint", "void", FALSE);
13408         register_icall (mono_load_remote_field_new, "mono_load_remote_field_new", "object object ptr ptr", FALSE);
13409         register_icall (mono_store_remote_field_new, "mono_store_remote_field_new", "void object ptr ptr object", FALSE);
13410
13411         /* 
13412          * NOTE, NOTE, NOTE, NOTE:
13413          * when adding emulation for some opcodes, remember to also add a dummy
13414          * rule to the burg files, because we need the arity information to be correct.
13415          */
13416 #ifndef MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS
13417         mono_register_opcode_emulation (OP_LMUL, "__emul_lmul", "long long long", mono_llmult, TRUE);
13418         mono_register_opcode_emulation (OP_LDIV, "__emul_ldiv", "long long long", mono_lldiv, FALSE);
13419         mono_register_opcode_emulation (OP_LDIV_UN, "__emul_ldiv_un", "long long long", mono_lldiv_un, FALSE);
13420         mono_register_opcode_emulation (OP_LREM, "__emul_lrem", "long long long", mono_llrem, FALSE);
13421         mono_register_opcode_emulation (OP_LREM_UN, "__emul_lrem_un", "long long long", mono_llrem_un, FALSE);
13422         mono_register_opcode_emulation (OP_LMUL_OVF_UN, "__emul_lmul_ovf_un", "long long long", mono_llmult_ovf_un, FALSE);
13423         mono_register_opcode_emulation (OP_LMUL_OVF, "__emul_lmul_ovf", "long long long", mono_llmult_ovf, FALSE);
13424 #endif
13425
13426 #ifndef MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS
13427         mono_register_opcode_emulation (OP_LSHL, "__emul_lshl", "long long int32", mono_lshl, TRUE);
13428         mono_register_opcode_emulation (OP_LSHR, "__emul_lshr", "long long int32", mono_lshr, TRUE);
13429         mono_register_opcode_emulation (OP_LSHR_UN, "__emul_lshr_un", "long long int32", mono_lshr_un, TRUE);
13430 #endif
13431
13432 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
13433         mono_register_opcode_emulation (CEE_DIV, "__emul_idiv", "int32 int32 int32", mono_idiv, FALSE);
13434         mono_register_opcode_emulation (CEE_DIV_UN, "__emul_idiv_un", "int32 int32 int32", mono_idiv_un, FALSE);
13435         mono_register_opcode_emulation (CEE_REM, "__emul_irem", "int32 int32 int32", mono_irem, FALSE);
13436         mono_register_opcode_emulation (CEE_REM_UN, "__emul_irem_un", "int32 int32 int32", mono_irem_un, FALSE);
13437 #endif
13438
13439 #ifdef MONO_ARCH_EMULATE_MUL_DIV
13440         mono_register_opcode_emulation (CEE_MUL_OVF, "__emul_imul_ovf", "int32 int32 int32", mono_imul_ovf, FALSE);
13441         mono_register_opcode_emulation (CEE_MUL_OVF_UN, "__emul_imul_ovf_un", "int32 int32 int32", mono_imul_ovf_un, FALSE);
13442         mono_register_opcode_emulation (CEE_MUL, "__emul_imul", "int32 int32 int32", mono_imul, TRUE);
13443 #endif
13444 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_SOFT_FLOAT)
13445         mono_register_opcode_emulation (OP_FDIV, "__emul_fdiv", "double double double", mono_fdiv, FALSE);
13446 #endif
13447
13448         mono_register_opcode_emulation (OP_FCONV_TO_U8, "__emul_fconv_to_u8", "ulong double", mono_fconv_u8, FALSE);
13449         mono_register_opcode_emulation (OP_FCONV_TO_U4, "__emul_fconv_to_u4", "uint32 double", mono_fconv_u4, FALSE);
13450         mono_register_opcode_emulation (OP_FCONV_TO_OVF_I8, "__emul_fconv_to_ovf_i8", "long double", mono_fconv_ovf_i8, FALSE);
13451         mono_register_opcode_emulation (OP_FCONV_TO_OVF_U8, "__emul_fconv_to_ovf_u8", "ulong double", mono_fconv_ovf_u8, FALSE);
13452
13453 #ifdef MONO_ARCH_EMULATE_FCONV_TO_I8
13454         mono_register_opcode_emulation (OP_FCONV_TO_I8, "__emul_fconv_to_i8", "long double", mono_fconv_i8, FALSE);
13455 #endif
13456 #ifdef MONO_ARCH_EMULATE_CONV_R8_UN
13457         mono_register_opcode_emulation (CEE_CONV_R_UN, "__emul_conv_r_un", "double int32", mono_conv_to_r8_un, FALSE);
13458 #endif
13459 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8
13460         mono_register_opcode_emulation (OP_LCONV_TO_R8, "__emul_lconv_to_r8", "double long", mono_lconv_to_r8, FALSE);
13461 #endif
13462 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R4
13463         mono_register_opcode_emulation (OP_LCONV_TO_R4, "__emul_lconv_to_r4", "float long", mono_lconv_to_r4, FALSE);
13464 #endif
13465 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8_UN
13466         mono_register_opcode_emulation (OP_LCONV_TO_R_UN, "__emul_lconv_to_r8_un", "double long", mono_lconv_to_r8_un, FALSE);
13467 #endif
13468 #ifdef MONO_ARCH_EMULATE_FREM
13469         mono_register_opcode_emulation (OP_FREM, "__emul_frem", "double double double", fmod, FALSE);
13470 #endif
13471
13472 #ifdef MONO_ARCH_SOFT_FLOAT
13473         mono_register_opcode_emulation (OP_FSUB, "__emul_fsub", "double double double", mono_fsub, FALSE);
13474         mono_register_opcode_emulation (OP_FADD, "__emul_fadd", "double double double", mono_fadd, FALSE);
13475         mono_register_opcode_emulation (OP_FMUL, "__emul_fmul", "double double double", mono_fmul, FALSE);
13476         mono_register_opcode_emulation (OP_FNEG, "__emul_fneg", "double double", mono_fneg, FALSE);
13477         mono_register_opcode_emulation (CEE_CONV_R8, "__emul_conv_r8", "double int32", mono_conv_to_r8, FALSE);
13478         mono_register_opcode_emulation (CEE_CONV_R4, "__emul_conv_r4", "double int32", mono_conv_to_r4, FALSE);
13479         mono_register_opcode_emulation (OP_FCONV_TO_R4, "__emul_fconv_to_r4", "double double", mono_fconv_r4, FALSE);
13480         mono_register_opcode_emulation (OP_FCONV_TO_I1, "__emul_fconv_to_i1", "int8 double", mono_fconv_i1, FALSE);
13481         mono_register_opcode_emulation (OP_FCONV_TO_I2, "__emul_fconv_to_i2", "int16 double", mono_fconv_i2, FALSE);
13482         mono_register_opcode_emulation (OP_FCONV_TO_I4, "__emul_fconv_to_i4", "int32 double", mono_fconv_i4, FALSE);
13483         mono_register_opcode_emulation (OP_FCONV_TO_U1, "__emul_fconv_to_u1", "uint8 double", mono_fconv_u1, FALSE);
13484         mono_register_opcode_emulation (OP_FCONV_TO_U2, "__emul_fconv_to_u2", "uint16 double", mono_fconv_u2, FALSE);
13485
13486         mono_register_opcode_emulation (OP_FBEQ, "__emul_fcmp_eq", "uint32 double double", mono_fcmp_eq, FALSE);
13487         mono_register_opcode_emulation (OP_FBLT, "__emul_fcmp_lt", "uint32 double double", mono_fcmp_lt, FALSE);
13488         mono_register_opcode_emulation (OP_FBGT, "__emul_fcmp_gt", "uint32 double double", mono_fcmp_gt, FALSE);
13489         mono_register_opcode_emulation (OP_FBLE, "__emul_fcmp_le", "uint32 double double", mono_fcmp_le, FALSE);
13490         mono_register_opcode_emulation (OP_FBGE, "__emul_fcmp_ge", "uint32 double double", mono_fcmp_ge, FALSE);
13491         mono_register_opcode_emulation (OP_FBNE_UN, "__emul_fcmp_ne_un", "uint32 double double", mono_fcmp_ne_un, FALSE);
13492         mono_register_opcode_emulation (OP_FBLT_UN, "__emul_fcmp_lt_un", "uint32 double double", mono_fcmp_lt_un, FALSE);
13493         mono_register_opcode_emulation (OP_FBGT_UN, "__emul_fcmp_gt_un", "uint32 double double", mono_fcmp_gt_un, FALSE);
13494         mono_register_opcode_emulation (OP_FBLE_UN, "__emul_fcmp_le_un", "uint32 double double", mono_fcmp_le_un, FALSE);
13495         mono_register_opcode_emulation (OP_FBGE_UN, "__emul_fcmp_ge_un", "uint32 double double", mono_fcmp_ge_un, FALSE);
13496
13497         mono_register_opcode_emulation (OP_FCEQ, "__emul_fcmp_ceq", "uint32 double double", mono_fceq, FALSE);
13498         mono_register_opcode_emulation (OP_FCGT, "__emul_fcmp_cgt", "uint32 double double", mono_fcgt, FALSE);
13499         mono_register_opcode_emulation (OP_FCGT_UN, "__emul_fcmp_cgt_un", "uint32 double double", mono_fcgt_un, FALSE);
13500         mono_register_opcode_emulation (OP_FCLT, "__emul_fcmp_clt", "uint32 double double", mono_fclt, FALSE);
13501         mono_register_opcode_emulation (OP_FCLT_UN, "__emul_fcmp_clt_un", "uint32 double double", mono_fclt_un, FALSE);
13502
13503         register_icall (mono_fload_r4, "mono_fload_r4", "double ptr", FALSE);
13504         register_icall (mono_fstore_r4, "mono_fstore_r4", "void double ptr", FALSE);
13505         register_icall (mono_fload_r4_arg, "mono_fload_r4_arg", "uint32 double", FALSE);
13506 #endif
13507
13508 #if SIZEOF_VOID_P == 4
13509         mono_register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", "uint32 double", mono_fconv_u4, TRUE);
13510 #endif
13511
13512         /* other jit icalls */
13513         register_icall (mono_delegate_ctor, "mono_delegate_ctor", "void object object ptr", FALSE);
13514         register_icall (mono_class_static_field_address , "mono_class_static_field_address", 
13515                                  "ptr ptr ptr", FALSE);
13516         register_icall (mono_ldtoken_wrapper, "mono_ldtoken_wrapper", "ptr ptr ptr ptr", FALSE);
13517         register_icall (mono_get_special_static_data, "mono_get_special_static_data", "ptr int", FALSE);
13518         register_icall (mono_ldstr, "mono_ldstr", "object ptr ptr int32", FALSE);
13519         register_icall (mono_helper_stelem_ref_check, "helper_stelem_ref_check", "void object object", FALSE);
13520         register_icall (mono_object_new, "mono_object_new", "object ptr ptr", FALSE);
13521         register_icall (mono_object_new_specific, "mono_object_new_specific", "object ptr", FALSE);
13522         register_icall (mono_array_new, "mono_array_new", "object ptr ptr int32", FALSE);
13523         register_icall (mono_array_new_specific, "mono_array_new_specific", "object ptr int32", FALSE);
13524         register_icall (mono_runtime_class_init, "mono_runtime_class_init", "void ptr", FALSE);
13525         register_icall (mono_ldftn, "mono_ldftn", "ptr ptr", FALSE);
13526         register_icall (mono_ldftn_nosync, "mono_ldftn_nosync", "ptr ptr", FALSE);
13527         register_icall (mono_ldvirtfn, "mono_ldvirtfn", "ptr object ptr", FALSE);
13528         register_icall (mono_helper_compile_generic_method, "compile_generic_method", "ptr object ptr ptr ptr", FALSE);
13529         register_icall (mono_helper_ldstr, "helper_ldstr", "object ptr int", FALSE);
13530         register_icall (mono_helper_ldstr_mscorlib, "helper_ldstr_mscorlib", "object int", FALSE);
13531         register_icall (mono_helper_newobj_mscorlib, "helper_newobj_mscorlib", "object int", FALSE);
13532         register_icall (mono_value_copy, "mono_value_copy", "void ptr ptr ptr", FALSE);
13533         register_icall (mono_helper_get_rgctx_other_ptr, "get_rgctx_other_ptr", "ptr ptr ptr int32 int32 int32 int32", FALSE);
13534         register_icall (mono_break, "mono_break", NULL, TRUE);
13535         register_icall (mono_create_corlib_exception_0, "mono_create_corlib_exception_0", "object int", TRUE);
13536         register_icall (mono_create_corlib_exception_1, "mono_create_corlib_exception_1", "object int object", TRUE);
13537         register_icall (mono_create_corlib_exception_2, "mono_create_corlib_exception_2", "object int object object", TRUE);
13538 #endif
13539
13540 #define JIT_RUNTIME_WORKS
13541 #ifdef JIT_RUNTIME_WORKS
13542         mono_install_runtime_cleanup ((MonoDomainFunc)mini_cleanup);
13543         mono_runtime_init (domain, mono_thread_start_cb, mono_thread_attach_cb);
13544 #endif
13545
13546         mono_generic_sharing_init ();
13547
13548         mono_thread_attach (domain);
13549         return domain;
13550 }
13551
13552 MonoJitStats mono_jit_stats = {0};
13553
13554 static void 
13555 print_jit_stats (void)
13556 {
13557         if (mono_jit_stats.enabled) {
13558                 g_print ("Mono Jit statistics\n");
13559                 g_print ("Compiled methods:       %ld\n", mono_jit_stats.methods_compiled);
13560                 g_print ("Methods from AOT:       %ld\n", mono_jit_stats.methods_aot);
13561                 g_print ("Methods cache lookup:   %ld\n", mono_jit_stats.methods_lookups);
13562                 g_print ("Method trampolines:     %ld\n", mono_jit_stats.method_trampolines);
13563                 g_print ("Basic blocks:           %ld\n", mono_jit_stats.basic_blocks);
13564                 g_print ("Max basic blocks:       %ld\n", mono_jit_stats.max_basic_blocks);
13565                 g_print ("Allocated vars:         %ld\n", mono_jit_stats.allocate_var);
13566                 g_print ("Analyze stack repeat:   %ld\n", mono_jit_stats.analyze_stack_repeat);
13567                 g_print ("Compiled CIL code size: %ld\n", mono_jit_stats.cil_code_size);
13568                 g_print ("Native code size:       %ld\n", mono_jit_stats.native_code_size);
13569                 g_print ("Max code size ratio:    %.2f (%s::%s)\n", mono_jit_stats.max_code_size_ratio/100.0,
13570                                 mono_jit_stats.max_ratio_method->klass->name, mono_jit_stats.max_ratio_method->name);
13571                 g_print ("Biggest method:         %ld (%s::%s)\n", mono_jit_stats.biggest_method_size,
13572                                 mono_jit_stats.biggest_method->klass->name, mono_jit_stats.biggest_method->name);
13573                 g_print ("Code reallocs:          %ld\n", mono_jit_stats.code_reallocs);
13574                 g_print ("Allocated code size:    %ld\n", mono_jit_stats.allocated_code_size);
13575                 g_print ("Inlineable methods:     %ld\n", mono_jit_stats.inlineable_methods);
13576                 g_print ("Inlined methods:        %ld\n", mono_jit_stats.inlined_methods);
13577                 g_print ("Locals stack size:      %ld\n", mono_jit_stats.locals_stack_size);
13578
13579                 g_print ("\nCreated object count:   %ld\n", mono_stats.new_object_count);
13580                 g_print ("Delegates created:      %ld\n", mono_stats.delegate_creations);
13581                 g_print ("Initialized classes:    %ld\n", mono_stats.initialized_class_count);
13582                 g_print ("Used classes:           %ld\n", mono_stats.used_class_count);
13583                 g_print ("Generic vtables:        %ld\n", mono_stats.generic_vtable_count);
13584                 g_print ("Methods:                %ld\n", mono_stats.method_count);
13585                 g_print ("Static data size:       %ld\n", mono_stats.class_static_data_size);
13586                 g_print ("VTable data size:       %ld\n", mono_stats.class_vtable_size);
13587                 g_print ("Mscorlib mempool size:  %d\n", mono_mempool_get_allocated (mono_defaults.corlib->mempool));
13588
13589                 g_print ("\nGeneric instances:      %ld\n", mono_stats.generic_instance_count);
13590                 g_print ("Initialized classes:    %ld\n", mono_stats.generic_class_count);
13591                 g_print ("Inflated methods:       %ld / %ld\n", mono_stats.inflated_method_count_2,
13592                          mono_stats.inflated_method_count);
13593                 g_print ("Inflated types:         %ld\n", mono_stats.inflated_type_count);
13594                 g_print ("Generics metadata size: %ld\n", mono_stats.generics_metadata_size);
13595                 g_print ("Generics virtual invokes: %ld\n", mono_jit_stats.generic_virtual_invocations);
13596
13597                 g_print ("Sharable generic methods: %ld\n", mono_stats.generics_sharable_methods);
13598                 g_print ("Unsharable generic methods: %ld\n", mono_stats.generics_unsharable_methods);
13599                 g_print ("Shared generic methods: %ld\n", mono_stats.generics_shared_methods);
13600
13601                 g_print ("Dynamic code allocs:    %ld\n", mono_stats.dynamic_code_alloc_count);
13602                 g_print ("Dynamic code bytes:     %ld\n", mono_stats.dynamic_code_bytes_count);
13603                 g_print ("Dynamic code frees:     %ld\n", mono_stats.dynamic_code_frees_count);
13604
13605                 g_print ("IMT tables size:        %ld\n", mono_stats.imt_tables_size);
13606                 g_print ("IMT number of tables:   %ld\n", mono_stats.imt_number_of_tables);
13607                 g_print ("IMT number of methods:  %ld\n", mono_stats.imt_number_of_methods);
13608                 g_print ("IMT used slots:         %ld\n", mono_stats.imt_used_slots);
13609                 g_print ("IMT colliding slots:    %ld\n", mono_stats.imt_slots_with_collisions);
13610                 g_print ("IMT max collisions:     %ld\n", mono_stats.imt_max_collisions_in_slot);
13611                 g_print ("IMT methods at max col: %ld\n", mono_stats.imt_method_count_when_max_collisions);
13612                 g_print ("IMT thunks size:        %ld\n", mono_stats.imt_thunks_size);
13613
13614                 g_print ("JIT info table inserts: %ld\n", mono_stats.jit_info_table_insert_count);
13615                 g_print ("JIT info table removes: %ld\n", mono_stats.jit_info_table_remove_count);
13616                 g_print ("JIT info table lookups: %ld\n", mono_stats.jit_info_table_lookup_count);
13617
13618                 g_print ("Hazardous pointers:     %ld\n", mono_stats.hazardous_pointer_count);
13619 #ifdef HAVE_SGEN_GC
13620                 g_print ("Minor GC collections:   %ld\n", mono_stats.minor_gc_count);
13621                 g_print ("Major GC collections:   %ld\n", mono_stats.major_gc_count);
13622                 g_print ("Minor GC time in msecs: %lf\n", (double)mono_stats.minor_gc_time_usecs / 1000.0);
13623                 g_print ("Major GC time in msecs: %lf\n", (double)mono_stats.major_gc_time_usecs / 1000.0);
13624 #endif
13625                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
13626                         g_print ("\nDecl security check   : %ld\n", mono_jit_stats.cas_declsec_check);
13627                         g_print ("LinkDemand (user)     : %ld\n", mono_jit_stats.cas_linkdemand);
13628                         g_print ("LinkDemand (icall)    : %ld\n", mono_jit_stats.cas_linkdemand_icall);
13629                         g_print ("LinkDemand (pinvoke)  : %ld\n", mono_jit_stats.cas_linkdemand_pinvoke);
13630                         g_print ("LinkDemand (aptc)     : %ld\n", mono_jit_stats.cas_linkdemand_aptc);
13631                         g_print ("Demand (code gen)     : %ld\n", mono_jit_stats.cas_demand_generation);
13632                 }
13633                 if (debug_options.collect_pagefault_stats) {
13634                         g_print ("Metadata pagefaults   : %d\n", mono_raw_buffer_get_n_pagefaults ());
13635                         g_print ("AOT pagefaults        : %d\n", mono_aot_get_n_pagefaults ());
13636                 }
13637         }
13638 }
13639
13640 void
13641 mini_cleanup (MonoDomain *domain)
13642 {
13643 #ifdef HAVE_LINUX_RTC_H
13644         if (rtc_fd >= 0)
13645                 enable_rtc_timer (FALSE);
13646 #endif
13647
13648         /* 
13649          * mono_runtime_cleanup() and mono_domain_finalize () need to
13650          * be called early since they need the execution engine still
13651          * fully working (mono_domain_finalize may invoke managed finalizers
13652          * and mono_runtime_cleanup will wait for other threads to finish).
13653          */
13654         mono_domain_finalize (domain, 2000);
13655
13656         /* This accesses metadata so needs to be called before runtime shutdown */
13657         print_jit_stats ();
13658
13659         mono_runtime_cleanup (domain);
13660
13661         mono_profiler_shutdown ();
13662
13663         mono_icall_cleanup ();
13664
13665         mono_runtime_cleanup_handlers ();
13666
13667         mono_domain_free (domain, TRUE);
13668
13669         mono_debugger_cleanup ();
13670
13671         mono_trampolines_cleanup ();
13672
13673         mono_code_manager_destroy (global_codeman);
13674         g_hash_table_destroy (jit_icall_name_hash);
13675         g_free (emul_opcode_map);
13676
13677         mono_arch_cleanup ();
13678
13679         mono_cleanup ();
13680
13681         mono_trace_cleanup ();
13682
13683         mono_counters_dump (-1, stdout);
13684
13685         if (mono_inject_async_exc_method)
13686                 mono_method_desc_free (mono_inject_async_exc_method);
13687
13688         TlsFree(mono_jit_tls_id);
13689
13690         DeleteCriticalSection (&jit_mutex);
13691
13692         DeleteCriticalSection (&mono_delegate_section);
13693 }
13694
13695 void
13696 mono_set_defaults (int verbose_level, guint32 opts)
13697 {
13698         mini_verbose = verbose_level;
13699         default_opt = opts;
13700         default_opt_set = TRUE;
13701 }
13702
13703 static void
13704 mono_precompile_assembly (MonoAssembly *ass, void *user_data)
13705 {
13706         GHashTable *assemblies = (GHashTable*)user_data;
13707         MonoImage *image = mono_assembly_get_image (ass);
13708         MonoMethod *method, *invoke;
13709         int i, count = 0;
13710
13711         if (g_hash_table_lookup (assemblies, ass))
13712                 return;
13713
13714         g_hash_table_insert (assemblies, ass, ass);
13715
13716         if (mini_verbose > 0)
13717                 printf ("PRECOMPILE: %s.\n", mono_image_get_filename (image));
13718
13719         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
13720                 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
13721                 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
13722                         continue;
13723
13724                 count++;
13725                 if (mini_verbose > 1) {
13726                         char * desc = mono_method_full_name (method, TRUE);
13727                         g_print ("Compiling %d %s\n", count, desc);
13728                         g_free (desc);
13729                 }
13730                 mono_compile_method (method);
13731                 if (strcmp (method->name, "Finalize") == 0) {
13732                         invoke = mono_marshal_get_runtime_invoke (method);
13733                         mono_compile_method (invoke);
13734                 }
13735                 if (method->klass->marshalbyref && mono_method_signature (method)->hasthis) {
13736                         invoke = mono_marshal_get_remoting_invoke_with_check (method);
13737                         mono_compile_method (invoke);
13738                 }
13739         }
13740
13741         /* Load and precompile referenced assemblies as well */
13742         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_ASSEMBLYREF); ++i) {
13743                 mono_assembly_load_reference (image, i);
13744                 if (image->references [i])
13745                         mono_precompile_assembly (image->references [i], assemblies);
13746         }
13747 }
13748
13749 void mono_precompile_assemblies ()
13750 {
13751         GHashTable *assemblies = g_hash_table_new (NULL, NULL);
13752
13753         mono_assembly_foreach ((GFunc)mono_precompile_assembly, assemblies);
13754
13755         g_hash_table_destroy (assemblies);
13756 }