2008-02-14 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 PLATFORM_WIN32
30 #define _WIN32_WINNT 0x0500
31 #endif
32
33 #ifdef HAVE_VALGRIND_MEMCHECK_H
34 #include <valgrind/memcheck.h>
35 #endif
36
37 #include <mono/metadata/assembly.h>
38 #include <mono/metadata/loader.h>
39 #include <mono/metadata/tabledefs.h>
40 #include <mono/metadata/class.h>
41 #include <mono/metadata/object.h>
42 #include <mono/metadata/exception.h>
43 #include <mono/metadata/opcodes.h>
44 #include <mono/metadata/mono-endian.h>
45 #include <mono/metadata/tokentype.h>
46 #include <mono/metadata/tabledefs.h>
47 #include <mono/metadata/threads.h>
48 #include <mono/metadata/marshal.h>
49 #include <mono/metadata/socket-io.h>
50 #include <mono/metadata/appdomain.h>
51 #include <mono/metadata/debug-helpers.h>
52 #include <mono/io-layer/io-layer.h>
53 #include "mono/metadata/profiler.h"
54 #include <mono/metadata/profiler-private.h>
55 #include <mono/metadata/mono-config.h>
56 #include <mono/metadata/environment.h>
57 #include <mono/metadata/mono-debug.h>
58 #include <mono/metadata/monitor.h>
59 #include <mono/metadata/gc-internal.h>
60 #include <mono/metadata/security-manager.h>
61 #include <mono/metadata/threads-types.h>
62 #include <mono/metadata/rawbuffer.h>
63 #include <mono/metadata/security-core-clr.h>
64 #include <mono/utils/mono-math.h>
65 #include <mono/utils/mono-compiler.h>
66 #include <mono/utils/mono-counters.h>
67 #include <mono/utils/mono-logger.h>
68 #include <mono/utils/mono-mmap.h>
69
70 #include "mini.h"
71 #include <string.h>
72 #include <ctype.h>
73 #include "inssel.h"
74 #include "trace.h"
75
76 #include "jit-icalls.h"
77
78 #include "aliasing.h"
79
80 #include "debug-mini.h"
81
82 #define BRANCH_COST 100
83 #define INLINE_LENGTH_LIMIT 20
84 #define INLINE_FAILURE do {\
85                 if ((cfg->method != method) && (method->wrapper_type == MONO_WRAPPER_NONE))\
86                         goto inline_failure;\
87         } while (0)
88 #define CHECK_CFG_EXCEPTION do {\
89                 if (cfg->exception_type != MONO_EXCEPTION_NONE)\
90                         goto exception_exit;\
91         } while (0)
92 #define METHOD_ACCESS_FAILURE do {      \
93                 char *method_fname = mono_method_full_name (method, TRUE);      \
94                 char *cil_method_fname = mono_method_full_name (cil_method, TRUE);      \
95                 cfg->exception_type = MONO_EXCEPTION_METHOD_ACCESS;     \
96                 cfg->exception_message = g_strdup_printf ("Method `%s' is inaccessible from method `%s'\n", cil_method_fname, method_fname);    \
97                 g_free (method_fname);  \
98                 g_free (cil_method_fname);      \
99                 goto exception_exit;    \
100         } while (0)
101 #define FIELD_ACCESS_FAILURE do {       \
102                 char *method_fname = mono_method_full_name (method, TRUE);      \
103                 char *field_fname = mono_field_full_name (field);       \
104                 cfg->exception_type = MONO_EXCEPTION_FIELD_ACCESS;      \
105                 cfg->exception_message = g_strdup_printf ("Field `%s' is inaccessible from method `%s'\n", field_fname, method_fname);  \
106                 g_free (method_fname);  \
107                 g_free (field_fname);   \
108                 goto exception_exit;    \
109         } while (0)
110 #define GENERIC_SHARING_FAILURE(opcode) do {            \
111                 if (cfg->generic_sharing_context) {     \
112                         if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) \
113                                 /*g_print ("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__)*/; \
114                         cfg->exception_type = MONO_EXCEPTION_GENERIC_SHARING_FAILED;    \
115                         goto exception_exit;    \
116                 }                       \
117         } while (0)
118
119 #define MONO_CHECK_THIS(ins) (mono_method_signature (cfg->method)->hasthis && (ins)->ssa_op == MONO_SSA_LOAD && (ins)->inst_left->inst_c0 == 0)
120
121 static void setup_stat_profiler (void);
122 gboolean  mono_arch_print_tree(MonoInst *tree, int arity);
123 static gpointer mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt);
124 static gpointer mono_jit_compile_method (MonoMethod *method);
125 static gpointer mono_jit_find_compiled_method (MonoDomain *domain, MonoMethod *method);
126 static gpointer mono_create_jit_trampoline_in_domain (MonoDomain *domain, MonoMethod *method);
127 inline static int mono_emit_jit_icall (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoInst **args, const guint8 *ip);
128
129 static void handle_stobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, MonoInst *src, 
130                           const unsigned char *ip, MonoClass *klass, gboolean to_end, gboolean native, gboolean write_barrier);
131
132 static void dec_foreach (MonoInst *tree, MonoCompile *cfg);
133
134 static int mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
135                    int locals_offset, MonoInst *return_var, GList *dont_inline, MonoInst **inline_args, 
136                    guint inline_offset, gboolean is_virtual_call);
137
138 #ifdef MONO_ARCH_SOFT_FLOAT
139 static void
140 handle_store_float (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ptr, MonoInst *val, const unsigned char *ip);
141 #endif
142
143 /* helper methods signature */
144 static MonoMethodSignature *helper_sig_class_init_trampoline = NULL;
145 static MonoMethodSignature *helper_sig_generic_class_init_trampoline = NULL;
146 static MonoMethodSignature *helper_sig_domain_get = NULL;
147
148 static guint32 default_opt = 0;
149 static gboolean default_opt_set = FALSE;
150
151 guint32 mono_jit_tls_id = -1;
152 MonoTraceSpec *mono_jit_trace_calls = NULL;
153 gboolean mono_break_on_exc = FALSE;
154 #ifndef DISABLE_AOT
155 gboolean mono_compile_aot = FALSE;
156 #endif
157 MonoMethodDesc *mono_inject_async_exc_method = NULL;
158 int mono_inject_async_exc_pos;
159 MonoMethodDesc *mono_break_at_bb_method = NULL;
160 int mono_break_at_bb_bb_num;
161
162 static int mini_verbose = 0;
163
164 #define mono_jit_lock() EnterCriticalSection (&jit_mutex)
165 #define mono_jit_unlock() LeaveCriticalSection (&jit_mutex)
166 static CRITICAL_SECTION jit_mutex;
167
168 static GHashTable *class_init_hash_addr = NULL;
169 static GHashTable *delegate_trampoline_hash_addr = NULL;
170
171 static MonoCodeManager *global_codeman = NULL;
172
173 static GHashTable *jit_icall_name_hash = NULL;
174
175 static MonoDebugOptions debug_options;
176
177 #ifdef VALGRIND_JIT_REGISTER_MAP
178 static int valgrind_register = 0;
179 #endif
180
181 /*
182  * Address of the trampoline code.  This is used by the debugger to check
183  * whether a method is a trampoline.
184  */
185 guint8* mono_trampoline_code [MONO_TRAMPOLINE_NUM];
186
187 /*
188  * Table written to by the debugger with a 1-based index into the
189  * mono_breakpoint_info table, which contains changes made to
190  * the JIT instructions by the debugger.
191  */
192 gssize
193 mono_breakpoint_info_index [MONO_BREAKPOINT_ARRAY_SIZE];
194
195 /* Whenever to check for pending exceptions in managed-to-native wrappers */
196 gboolean check_for_pending_exc = TRUE;
197
198 gboolean
199 mono_running_on_valgrind (void)
200 {
201 #ifdef HAVE_VALGRIND_MEMCHECK_H
202                 if (RUNNING_ON_VALGRIND){
203 #ifdef VALGRIND_JIT_REGISTER_MAP
204                         valgrind_register = TRUE;
205 #endif
206                         return TRUE;
207                 } else
208                         return FALSE;
209 #else
210                 return FALSE;
211 #endif
212 }
213
214 typedef struct {
215         void *ip;
216         MonoMethod *method;
217 } FindTrampUserData;
218
219 static void
220 find_tramp (gpointer key, gpointer value, gpointer user_data)
221 {
222         FindTrampUserData *ud = (FindTrampUserData*)user_data;
223
224         if (value == ud->ip)
225                 ud->method = (MonoMethod*)key;
226 }
227
228 /* debug function */
229 G_GNUC_UNUSED static char*
230 get_method_from_ip (void *ip)
231 {
232         MonoJitInfo *ji;
233         char *method;
234         char *res;
235         MonoDomain *domain = mono_domain_get ();
236         MonoDebugSourceLocation *location;
237         FindTrampUserData user_data;
238         
239         ji = mono_jit_info_table_find (domain, ip);
240         if (!ji) {
241                 user_data.ip = ip;
242                 user_data.method = NULL;
243                 mono_domain_lock (domain);
244                 g_hash_table_foreach (domain->jit_trampoline_hash, find_tramp, &user_data);
245                 mono_domain_unlock (domain);
246                 if (user_data.method) {
247                         char *mname = mono_method_full_name (user_data.method, TRUE);
248                         res = g_strdup_printf ("<%p - JIT trampoline for %s>", ip, mname);
249                         g_free (mname);
250                         return res;
251                 }
252                 else
253                         return NULL;
254         }
255         method = mono_method_full_name (ji->method, TRUE);
256         /* FIXME: unused ? */
257         location = mono_debug_lookup_source_location (ji->method, (guint32)((guint8*)ip - (guint8*)ji->code_start), domain);
258
259         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);
260
261         mono_debug_free_source_location (location);
262         g_free (method);
263
264         return res;
265 }
266
267 /** 
268  * mono_pmip:
269  * @ip: an instruction pointer address
270  *
271  * This method is used from a debugger to get the name of the
272  * method at address @ip.   This routine is typically invoked from
273  * a debugger like this:
274  *
275  * (gdb) print mono_pmip ($pc)
276  *
277  * Returns: the name of the method at address @ip.
278  */
279 G_GNUC_UNUSED char *
280 mono_pmip (void *ip)
281 {
282         return get_method_from_ip (ip);
283 }
284
285 /** 
286  * mono_print_method_from_ip
287  * @ip: an instruction pointer address
288  *
289  * This method is used from a debugger to get the name of the
290  * method at address @ip.
291  *
292  * This prints the name of the method at address @ip in the standard
293  * output.  Unlike mono_pmip which returns a string, this routine
294  * prints the value on the standard output. 
295  */
296 void
297 mono_print_method_from_ip (void *ip)
298 {
299         MonoJitInfo *ji;
300         char *method;
301         MonoDebugSourceLocation *source;
302         MonoDomain *domain = mono_domain_get ();
303         FindTrampUserData user_data;
304         
305         ji = mono_jit_info_table_find (domain, ip);
306         if (!ji) {
307                 user_data.ip = ip;
308                 user_data.method = NULL;
309                 mono_domain_lock (domain);
310                 g_hash_table_foreach (domain->jit_trampoline_hash, find_tramp, &user_data);
311                 mono_domain_unlock (domain);
312                 if (user_data.method) {
313                         char *mname = mono_method_full_name (user_data.method, TRUE);
314                         printf ("IP %p is a JIT trampoline for %s\n", ip, mname);
315                         g_free (mname);
316                 }
317                 else
318                         g_print ("No method at %p\n", ip);
319                 return;
320         }
321         method = mono_method_full_name (ji->method, TRUE);
322         source = mono_debug_lookup_source_location (ji->method, (guint32)((guint8*)ip - (guint8*)ji->code_start), domain);
323
324         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);
325
326         if (source)
327                 g_print ("%s:%d\n", source->source_file, source->row);
328
329         mono_debug_free_source_location (source);
330         g_free (method);
331 }
332         
333 /* 
334  * mono_method_same_domain:
335  *
336  * Determine whenever two compiled methods are in the same domain, thus
337  * the address of the callee can be embedded in the caller.
338  */
339 gboolean mono_method_same_domain (MonoJitInfo *caller, MonoJitInfo *callee)
340 {
341         if (!caller || !callee)
342                 return FALSE;
343
344         /*
345          * If the call was made from domain-neutral to domain-specific 
346          * code, we can't patch the call site.
347          */
348         if (caller->domain_neutral && !callee->domain_neutral)
349                 return FALSE;
350
351         if ((caller->method->klass == mono_defaults.appdomain_class) &&
352                 (strstr (caller->method->name, "InvokeInDomain"))) {
353                  /* The InvokeInDomain methods change the current appdomain */
354                 return FALSE;
355         }
356
357         return TRUE;
358 }
359
360 /*
361  * mono_global_codeman_reserve:
362  *
363  *  Allocate code memory from the global code manager.
364  */
365 void *mono_global_codeman_reserve (int size)
366 {
367         void *ptr;
368
369         if (!global_codeman) {
370                 /* This can happen during startup */
371                 global_codeman = mono_code_manager_new ();
372                 return mono_code_manager_reserve (global_codeman, size);
373         }
374         else {
375                 mono_jit_lock ();
376                 ptr = mono_code_manager_reserve (global_codeman, size);
377                 mono_jit_unlock ();
378                 return ptr;
379         }
380 }
381
382 MonoJumpInfoToken *
383 mono_jump_info_token_new (MonoMemPool *mp, MonoImage *image, guint32 token)
384 {
385         MonoJumpInfoToken *res = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoToken));
386         res->image = image;
387         res->token = token;
388
389         return res;
390 }
391
392 #define MONO_INIT_VARINFO(vi,id) do { \
393         (vi)->range.first_use.pos.bid = 0xffff; \
394         (vi)->reg = -1; \
395         (vi)->idx = (id); \
396 } while (0)
397
398 //#define UNVERIFIED do { G_BREAKPOINT (); goto unverified; } while (0)
399 #define UNVERIFIED do { if (debug_options.break_on_unverified) G_BREAKPOINT (); else goto unverified; } while (0)
400
401 /*
402  * Basic blocks have two numeric identifiers:
403  * dfn: Depth First Number
404  * block_num: unique ID assigned at bblock creation
405  */
406 #define NEW_BBLOCK(cfg,new_bb) do {     \
407                 new_bb = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock)); \
408                 MONO_INST_LIST_INIT (&new_bb->ins_list); \
409         } while (0)
410
411 #define ADD_BBLOCK(cfg,b) do {  \
412                 cfg->cil_offset_to_bb [(b)->cil_code - cfg->cil_start] = (b);   \
413                 (b)->block_num = cfg->num_bblocks++;    \
414                 (b)->real_offset = real_offset; \
415         } while (0)
416
417 #define GET_BBLOCK(cfg,tblock,ip) do {  \
418                 (tblock) = cfg->cil_offset_to_bb [(ip) - cfg->cil_start]; \
419                 if (!(tblock)) {        \
420                         if ((ip) >= end || (ip) < header->code) UNVERIFIED; \
421                         NEW_BBLOCK (cfg, (tblock));     \
422                         (tblock)->cil_code = (ip);      \
423                         ADD_BBLOCK (cfg, (tblock));     \
424                 } \
425         } while (0)
426
427 #define CHECK_BBLOCK(target,ip,tblock) do {     \
428                 if ((target) < (ip) && \
429                                 MONO_INST_LIST_EMPTY (&(tblock)->ins_list)) { \
430                         bb_recheck = g_list_prepend (bb_recheck, (tblock)); \
431                         if (cfg->verbose_level > 2) \
432                                 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)); \
433                 } \
434         } while (0)
435
436 #define NEW_ICONST(cfg,dest,val) do {   \
437                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
438                 (dest)->opcode = OP_ICONST;     \
439                 (dest)->inst_c0 = (val);        \
440                 (dest)->type = STACK_I4;        \
441         } while (0)
442
443 #define NEW_PCONST(cfg,dest,val) do {   \
444                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
445                 (dest)->opcode = OP_PCONST;     \
446                 (dest)->inst_p0 = (val);        \
447                 (dest)->type = STACK_PTR;       \
448         } while (0)
449
450
451 #ifdef MONO_ARCH_NEED_GOT_VAR
452
453 #define NEW_PATCH_INFO(cfg,dest,el1,el2) do {   \
454                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
455                 (dest)->opcode = OP_PATCH_INFO; \
456                 (dest)->inst_left = (gpointer)(el1);    \
457                 (dest)->inst_right = (gpointer)(el2);   \
458         } while (0)
459
460 #define NEW_AOTCONST(cfg,dest,patch_type,cons) do {                     \
461                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
462                 (dest)->opcode = cfg->compile_aot ? OP_GOT_ENTRY : OP_PCONST; \
463                 if (cfg->compile_aot) {                                 \
464                         MonoInst *group, *got_var, *got_loc;            \
465                         got_loc = mono_get_got_var (cfg);               \
466                         NEW_TEMPLOAD ((cfg), got_var, got_loc->inst_c0); \
467                         NEW_PATCH_INFO ((cfg), group, cons, patch_type); \
468                         (dest)->inst_p0 = got_var;                      \
469                         (dest)->inst_p1 = group;                        \
470                 } else {                                                \
471                         (dest)->inst_p0 = (cons);                       \
472                         (dest)->inst_i1 = (gpointer)(patch_type);       \
473                 }                                                       \
474                 (dest)->type = STACK_PTR;                               \
475         } while (0)
476
477 #define NEW_AOTCONST_TOKEN(cfg,dest,patch_type,image,token,stack_type,stack_class) do { \
478                 MonoInst *group, *got_var, *got_loc;                    \
479                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
480                 (dest)->opcode = OP_GOT_ENTRY;                          \
481                 got_loc = mono_get_got_var (cfg);                       \
482                 NEW_TEMPLOAD ((cfg), got_var, got_loc->inst_c0);        \
483                 NEW_PATCH_INFO ((cfg), group, NULL, patch_type);        \
484                 group->inst_p0 = mono_jump_info_token_new ((cfg)->mempool, (image), (token)); \
485                 (dest)->inst_p0 = got_var;                              \
486                 (dest)->inst_p1 = group;                                \
487                 (dest)->type = (stack_type);                    \
488         (dest)->klass = (stack_class);          \
489         } while (0)
490
491 #else
492
493 #define NEW_AOTCONST(cfg,dest,patch_type,cons) do {    \
494                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
495                 (dest)->opcode = cfg->compile_aot ? OP_AOTCONST : OP_PCONST;    \
496                 (dest)->inst_p0 = (cons);       \
497                 (dest)->inst_i1 = (gpointer)(patch_type); \
498                 (dest)->type = STACK_PTR;       \
499     } while (0)
500
501 #define NEW_AOTCONST_TOKEN(cfg,dest,patch_type,image,token,stack_type,stack_class) do { \
502                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
503                 (dest)->opcode = OP_AOTCONST;   \
504                 (dest)->inst_p0 = mono_jump_info_token_new ((cfg)->mempool, (image), (token));  \
505                 (dest)->inst_p1 = (gpointer)(patch_type); \
506                 (dest)->type = (stack_type);    \
507         (dest)->klass = (stack_class);          \
508     } while (0)
509
510 #endif
511
512 #define NEW_CLASSCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_CLASS, (val))
513
514 #define NEW_IMAGECONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_IMAGE, (val))
515
516 #define NEW_FIELDCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_FIELD, (val))
517
518 #define NEW_METHODCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_METHODCONST, (val))
519
520 #define NEW_VTABLECONST(cfg,dest,vtable) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_VTABLE, cfg->compile_aot ? (gpointer)((vtable)->klass) : (vtable))
521
522 #define NEW_SFLDACONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_SFLDA, (val))
523
524 #define NEW_LDSTRCONST(cfg,dest,image,token) NEW_AOTCONST_TOKEN ((cfg), (dest), MONO_PATCH_INFO_LDSTR, (image), (token), STACK_OBJ, mono_defaults.string_class)
525
526 #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)
527
528 #define NEW_LDTOKENCONST(cfg,dest,image,token) NEW_AOTCONST_TOKEN ((cfg), (dest), MONO_PATCH_INFO_LDTOKEN, (image), (token), STACK_PTR, NULL)
529
530 #define NEW_DECLSECCONST(cfg,dest,image,entry) do { \
531                 if (cfg->compile_aot) { \
532                         NEW_AOTCONST_TOKEN (cfg, dest, MONO_PATCH_INFO_DECLSEC, image, (entry).index, STACK_OBJ, NULL); \
533                 } else { \
534                         NEW_PCONST (cfg, args [0], (entry).blob); \
535                 } \
536         } while (0)
537
538 #define NEW_DOMAINCONST(cfg,dest) do { \
539                 if (cfg->opt & MONO_OPT_SHARED) { \
540                         /* avoid depending on undefined C behavior in sequence points */ \
541                         MonoInst* __domain_var = mono_get_domainvar (cfg); \
542                         NEW_TEMPLOAD (cfg, dest, __domain_var->inst_c0); \
543                 } else { \
544                         NEW_PCONST (cfg, dest, (cfg)->domain); \
545                 } \
546         } while (0)
547
548 #define GET_VARINFO_INST(cfg,num) ((cfg)->varinfo [(num)]->inst)
549
550 #define NEW_ARGLOAD(cfg,dest,num) do {  \
551                 if (arg_array [(num)]->opcode == OP_ICONST) (dest) = arg_array [(num)]; else { \
552                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
553                 (dest)->ssa_op = MONO_SSA_LOAD; \
554                 (dest)->inst_i0 = arg_array [(num)];    \
555                 (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
556                 type_to_eval_stack_type ((cfg), param_types [(num)], (dest));   \
557                 (dest)->klass = (dest)->inst_i0->klass; \
558         }} while (0)
559
560 #define NEW_LOCLOAD(cfg,dest,num) do {  \
561                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
562                 (dest)->ssa_op = MONO_SSA_LOAD; \
563                 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)];       \
564                 (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
565                 type_to_eval_stack_type ((cfg), header->locals [(num)], (dest));        \
566                 (dest)->klass = (dest)->inst_i0->klass; \
567         } while (0)
568
569 #define NEW_LOCLOADA(cfg,dest,num) do { \
570                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
571                 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN;        \
572                 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)];       \
573                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
574                 (dest)->opcode = OP_LDADDR;     \
575                 (dest)->type = STACK_MP;        \
576                 (dest)->klass = (dest)->inst_i0->klass; \
577         if (!MONO_TYPE_ISSTRUCT (header->locals [(num)])) \
578            (cfg)->disable_ssa = TRUE; \
579         } while (0)
580
581 #define NEW_RETLOADA(cfg,dest) do {     \
582                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
583                 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN;        \
584                 (dest)->inst_i0 = (cfg)->ret;   \
585                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
586                 (dest)->opcode = cfg->ret_var_is_local ? OP_LDADDR : CEE_LDIND_I;       \
587                 (dest)->type = STACK_MP;        \
588                 (dest)->klass = (dest)->inst_i0->klass; \
589                 (cfg)->disable_ssa = TRUE; \
590         } while (0)
591
592 #define NEW_ARGLOADA(cfg,dest,num) do { \
593                 if (arg_array [(num)]->opcode == OP_ICONST) goto inline_failure; \
594                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
595                 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN;        \
596                 (dest)->inst_i0 = arg_array [(num)];    \
597                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
598                 (dest)->opcode = OP_LDADDR;     \
599                 (dest)->type = STACK_MP;        \
600                 (dest)->klass = (dest)->inst_i0->klass; \
601                 (cfg)->disable_ssa = TRUE; \
602         } while (0)
603
604 #define NEW_TEMPLOAD(cfg,dest,num) do { \
605                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
606                 (dest)->ssa_op = MONO_SSA_LOAD; \
607                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
608                 (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
609                 type_to_eval_stack_type ((cfg), (dest)->inst_i0->inst_vtype, (dest));   \
610                 (dest)->klass = (dest)->inst_i0->klass; \
611         } while (0)
612
613 #define NEW_TEMPLOADA(cfg,dest,num) do {        \
614                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
615                 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN;        \
616                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
617                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
618                 (dest)->opcode = OP_LDADDR;     \
619                 (dest)->type = STACK_MP;        \
620                 (dest)->klass = (dest)->inst_i0->klass; \
621         if (!MONO_TYPE_ISSTRUCT (cfg->varinfo [(num)]->inst_vtype)) \
622            (cfg)->disable_ssa = TRUE; \
623         } while (0)
624
625
626 #define NEW_INDLOAD(cfg,dest,addr,vtype) do {   \
627                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
628                 (dest)->inst_left = addr;       \
629                 (dest)->opcode = mini_type_to_ldind ((cfg), vtype);     \
630                 type_to_eval_stack_type ((cfg), vtype, (dest)); \
631                 /* FIXME: (dest)->klass = (dest)->inst_i0->klass;*/     \
632         } while (0)
633
634 #define NEW_INDSTORE(cfg,dest,addr,value,vtype) do {    \
635                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
636                 (dest)->inst_i0 = addr; \
637                 (dest)->opcode = mini_type_to_stind ((cfg), vtype);     \
638                 (dest)->inst_i1 = (value);      \
639                 /* FIXME: (dest)->klass = (dest)->inst_i0->klass;*/     \
640         } while (0)
641
642 #define NEW_TEMPSTORE(cfg,dest,num,inst) do {   \
643                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
644                 (dest)->ssa_op = MONO_SSA_STORE;        \
645                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
646                 (dest)->opcode = mini_type_to_stind ((cfg), (dest)->inst_i0->inst_vtype); \
647                 (dest)->inst_i1 = (inst);       \
648                 (dest)->klass = (dest)->inst_i0->klass; \
649         } while (0)
650
651 #define NEW_LOCSTORE(cfg,dest,num,inst) do {    \
652                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
653                 (dest)->opcode = mini_type_to_stind ((cfg), header->locals [(num)]); \
654                 (dest)->ssa_op = MONO_SSA_STORE;        \
655                 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)];       \
656                 (dest)->inst_i1 = (inst);       \
657                 (dest)->klass = (dest)->inst_i0->klass; \
658         } while (0)
659
660 #define NEW_ARGSTORE(cfg,dest,num,inst) do {    \
661                 if (arg_array [(num)]->opcode == OP_ICONST) goto inline_failure; \
662                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
663                 (dest)->opcode = mini_type_to_stind ((cfg), param_types [(num)]); \
664                 (dest)->ssa_op = MONO_SSA_STORE;        \
665                 (dest)->inst_i0 = arg_array [(num)];    \
666                 (dest)->inst_i1 = (inst);       \
667                 (dest)->klass = (dest)->inst_i0->klass; \
668         } while (0)
669
670 #define NEW_MEMCPY(cfg,dest,dst,src,memcpy_size,memcpy_align) do { \
671                 MONO_INST_NEW (cfg, dest, OP_MEMCPY); \
672         (dest)->inst_left = (dst); \
673                 (dest)->inst_right = (src); \
674                 (dest)->cil_code = ip; \
675         (dest)->backend.memcpy_args = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoMemcpyArgs)); \
676                 (dest)->backend.memcpy_args->size = (memcpy_size); \
677                 (dest)->backend.memcpy_args->align = (memcpy_align); \
678     } while (0)
679
680 #define NEW_MEMSET(cfg,dest,dst,imm,memcpy_size,memcpy_align) do { \
681                 MONO_INST_NEW (cfg, dest, OP_MEMSET); \
682         (dest)->inst_left = (dst); \
683                 (dest)->inst_imm = (imm); \
684                 (dest)->cil_code = ip; \
685         (dest)->backend.memcpy_args = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoMemcpyArgs)); \
686                 (dest)->backend.memcpy_args->size = (memcpy_size); \
687                 (dest)->backend.memcpy_args->align = (memcpy_align); \
688     } while (0)
689
690 #define NEW_DUMMY_USE(cfg,dest,load) do { \
691                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
692                 (dest)->opcode = OP_DUMMY_USE; \
693                 (dest)->inst_left = (load); \
694     } while (0)
695
696 #define NEW_DUMMY_STORE(cfg,dest,num) do { \
697                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
698                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
699                 (dest)->opcode = OP_DUMMY_STORE; \
700                 (dest)->klass = (dest)->inst_i0->klass; \
701         } while (0)
702
703 #define ADD_BINOP(op) do {      \
704                 MONO_INST_NEW (cfg, ins, (op)); \
705                 ins->cil_code = ip;     \
706                 sp -= 2;        \
707                 ins->inst_i0 = sp [0];  \
708                 ins->inst_i1 = sp [1];  \
709                 *sp++ = ins;    \
710                 type_from_op (ins);     \
711                 CHECK_TYPE (ins);       \
712         } while (0)
713
714 #define ADD_UNOP(op) do {       \
715                 MONO_INST_NEW (cfg, ins, (op)); \
716                 ins->cil_code = ip;     \
717                 sp--;   \
718                 ins->inst_i0 = sp [0];  \
719                 *sp++ = ins;    \
720                 type_from_op (ins);     \
721                 CHECK_TYPE (ins);       \
722         } while (0)
723
724 #define ADD_BINCOND(next_block) do {    \
725                 MonoInst *cmp;  \
726                 sp -= 2;                \
727                 MONO_INST_NEW(cfg, cmp, OP_COMPARE);    \
728                 cmp->inst_i0 = sp [0];  \
729                 cmp->inst_i1 = sp [1];  \
730                 cmp->cil_code = ins->cil_code;  \
731                 type_from_op (cmp);     \
732                 CHECK_TYPE (cmp);       \
733                 ins->inst_i0 = cmp;     \
734                 MONO_ADD_INS (bblock, ins);     \
735                 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);      \
736                 GET_BBLOCK (cfg, tblock, target);               \
737                 link_bblock (cfg, bblock, tblock);      \
738                 ins->inst_true_bb = tblock;     \
739                 CHECK_BBLOCK (target, ip, tblock);      \
740                 if ((next_block)) {     \
741                         link_bblock (cfg, bblock, (next_block));        \
742                         ins->inst_false_bb = (next_block);      \
743                         start_new_bblock = 1;   \
744                 } else {        \
745                         GET_BBLOCK (cfg, tblock, ip);           \
746                         link_bblock (cfg, bblock, tblock);      \
747                         ins->inst_false_bb = tblock;    \
748                         start_new_bblock = 2;   \
749                 }       \
750         } while (0)
751
752 /* FIXME: handle float, long ... */
753 #define ADD_UNCOND(istrue) do { \
754                 MonoInst *cmp;  \
755                 sp--;           \
756                 MONO_INST_NEW(cfg, cmp, OP_COMPARE);    \
757                 cmp->inst_i0 = sp [0];  \
758                 switch (cmp->inst_i0->type) { \
759                 case STACK_I8: \
760                         cmp->inst_i1 = zero_int64; break; \
761                 case STACK_R8: \
762                         cmp->inst_i1 = zero_r8; break; \
763                 case STACK_PTR: \
764                 case STACK_MP: \
765                         cmp->inst_i1 = zero_ptr; break; \
766                 case STACK_OBJ: \
767                         cmp->inst_i1 = zero_obj; break; \
768                 default: \
769                         cmp->inst_i1 = zero_int32;  \
770                 }  \
771                 cmp->cil_code = ins->cil_code;  \
772                 type_from_op (cmp);     \
773                 CHECK_TYPE (cmp);       \
774                 ins->inst_i0 = cmp;     \
775                 ins->opcode = (istrue)? CEE_BNE_UN: CEE_BEQ;    \
776                 MONO_ADD_INS (bblock, ins);     \
777                 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);      \
778                 GET_BBLOCK (cfg, tblock, target);               \
779                 link_bblock (cfg, bblock, tblock);      \
780                 ins->inst_true_bb = tblock;     \
781                 CHECK_BBLOCK (target, ip, tblock);      \
782                 GET_BBLOCK (cfg, tblock, ip);           \
783                 link_bblock (cfg, bblock, tblock);      \
784                 ins->inst_false_bb = tblock;    \
785                 start_new_bblock = 2;   \
786         } while (0)
787
788 #define NEW_LDELEMA(cfg,dest,sp,k) do { \
789                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
790                 (dest)->opcode = CEE_LDELEMA;   \
791                 (dest)->inst_left = (sp) [0];   \
792                 (dest)->inst_right = (sp) [1];  \
793                 (dest)->type = STACK_MP;        \
794                 (dest)->klass = (k);    \
795                 (cfg)->flags |= MONO_CFG_HAS_LDELEMA; \
796         } while (0)
797
798 #define NEW_GROUP(cfg,dest,el1,el2) do {        \
799                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
800                 (dest)->opcode = OP_GROUP;      \
801                 (dest)->inst_left = (el1);      \
802                 (dest)->inst_right = (el2);     \
803         } while (0)
804
805 #if 0
806 static gint
807 compare_bblock (gconstpointer a, gconstpointer b)
808 {
809         const MonoBasicBlock *b1 = a;
810         const MonoBasicBlock *b2 = b;
811
812         return b2->cil_code - b1->cil_code;
813 }
814 #endif
815
816 /* *
817  * link_bblock: Links two basic blocks
818  *
819  * links two basic blocks in the control flow graph, the 'from'
820  * argument is the starting block and the 'to' argument is the block
821  * the control flow ends to after 'from'.
822  */
823 static void
824 link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
825 {
826         MonoBasicBlock **newa;
827         int i, found;
828
829 #if 0
830         if (from->cil_code) {
831                 if (to->cil_code)
832                         g_print ("edge from IL%04x to IL_%04x\n", from->cil_code - cfg->cil_code, to->cil_code - cfg->cil_code);
833                 else
834                         g_print ("edge from IL%04x to exit\n", from->cil_code - cfg->cil_code);
835         } else {
836                 if (to->cil_code)
837                         g_print ("edge from entry to IL_%04x\n", to->cil_code - cfg->cil_code);
838                 else
839                         g_print ("edge from entry to exit\n");
840         }
841 #endif
842         found = FALSE;
843         for (i = 0; i < from->out_count; ++i) {
844                 if (to == from->out_bb [i]) {
845                         found = TRUE;
846                         break;
847                 }
848         }
849         if (!found) {
850                 newa = mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (from->out_count + 1));
851                 for (i = 0; i < from->out_count; ++i) {
852                         newa [i] = from->out_bb [i];
853                 }
854                 newa [i] = to;
855                 from->out_count++;
856                 from->out_bb = newa;
857         }
858
859         found = FALSE;
860         for (i = 0; i < to->in_count; ++i) {
861                 if (from == to->in_bb [i]) {
862                         found = TRUE;
863                         break;
864                 }
865         }
866         if (!found) {
867                 newa = mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (to->in_count + 1));
868                 for (i = 0; i < to->in_count; ++i) {
869                         newa [i] = to->in_bb [i];
870                 }
871                 newa [i] = from;
872                 to->in_count++;
873                 to->in_bb = newa;
874         }
875 }
876
877 /**
878  * mono_unlink_bblock:
879  *
880  *   Unlink two basic blocks.
881  */
882 static void
883 mono_unlink_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
884 {
885         int i, pos;
886         gboolean found;
887
888         found = FALSE;
889         for (i = 0; i < from->out_count; ++i) {
890                 if (to == from->out_bb [i]) {
891                         found = TRUE;
892                         break;
893                 }
894         }
895         if (found) {
896                 pos = 0;
897                 for (i = 0; i < from->out_count; ++i) {
898                         if (from->out_bb [i] != to)
899                                 from->out_bb [pos ++] = from->out_bb [i];
900                 }
901                 g_assert (pos == from->out_count - 1);
902                 from->out_count--;
903         }
904
905         found = FALSE;
906         for (i = 0; i < to->in_count; ++i) {
907                 if (from == to->in_bb [i]) {
908                         found = TRUE;
909                         break;
910                 }
911         }
912         if (found) {
913                 pos = 0;
914                 for (i = 0; i < to->in_count; ++i) {
915                         if (to->in_bb [i] != from)
916                                 to->in_bb [pos ++] = to->in_bb [i];
917                 }
918                 g_assert (pos == to->in_count - 1);
919                 to->in_count--;
920         }
921 }
922
923 /**
924  * mono_find_block_region:
925  *
926  *   We mark each basic block with a region ID. We use that to avoid BB
927  *   optimizations when blocks are in different regions.
928  *
929  * Returns:
930  *   A region token that encodes where this region is, and information
931  *   about the clause owner for this block.
932  *
933  *   The region encodes the try/catch/filter clause that owns this block
934  *   as well as the type.  -1 is a special value that represents a block
935  *   that is in none of try/catch/filter.
936  */
937 static int
938 mono_find_block_region (MonoCompile *cfg, int offset)
939 {
940         MonoMethod *method = cfg->method;
941         MonoMethodHeader *header = mono_method_get_header (method);
942         MonoExceptionClause *clause;
943         int i;
944
945         /* first search for handlers and filters */
946         for (i = 0; i < header->num_clauses; ++i) {
947                 clause = &header->clauses [i];
948                 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->data.filter_offset) &&
949                     (offset < (clause->handler_offset)))
950                         return ((i + 1) << 8) | MONO_REGION_FILTER | clause->flags;
951                            
952                 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
953                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
954                                 return ((i + 1) << 8) | MONO_REGION_FINALLY | clause->flags;
955                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
956                                 return ((i + 1) << 8) | MONO_REGION_FAULT | clause->flags;
957                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
958                                 return ((i + 1) << 8) | MONO_REGION_CATCH | clause->flags;
959                 }
960         }
961
962         /* search the try blocks */
963         for (i = 0; i < header->num_clauses; ++i) {
964                 clause = &header->clauses [i];
965                 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
966                         return ((i + 1) << 8) | clause->flags;
967         }
968
969         return -1;
970 }
971
972 static GList*
973 mono_find_final_block (MonoCompile *cfg, unsigned char *ip, unsigned char *target, int type)
974 {
975         MonoMethod *method = cfg->method;
976         MonoMethodHeader *header = mono_method_get_header (method);
977         MonoExceptionClause *clause;
978         MonoBasicBlock *handler;
979         int i;
980         GList *res = NULL;
981
982         for (i = 0; i < header->num_clauses; ++i) {
983                 clause = &header->clauses [i];
984                 if (MONO_OFFSET_IN_CLAUSE (clause, (ip - header->code)) && 
985                     (!MONO_OFFSET_IN_CLAUSE (clause, (target - header->code)))) {
986                         if (clause->flags == type) {
987                                 handler = cfg->cil_offset_to_bb [clause->handler_offset];
988                                 g_assert (handler);
989                                 res = g_list_append (res, handler);
990                         }
991                 }
992         }
993         return res;
994 }
995
996 MonoInst *
997 mono_find_spvar_for_region (MonoCompile *cfg, int region)
998 {
999         return g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
1000 }
1001
1002 static void
1003 mono_create_spvar_for_region (MonoCompile *cfg, int region)
1004 {
1005         MonoInst *var;
1006
1007         var = g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
1008         if (var)
1009                 return;
1010
1011         var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1012         /* prevent it from being register allocated */
1013         var->flags |= MONO_INST_INDIRECT;
1014
1015         g_hash_table_insert (cfg->spvars, GINT_TO_POINTER (region), var);
1016 }
1017
1018 static MonoInst *
1019 mono_find_exvar_for_offset (MonoCompile *cfg, int offset)
1020 {
1021         return g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
1022 }
1023
1024 static MonoInst*
1025 mono_create_exvar_for_offset (MonoCompile *cfg, int offset)
1026 {
1027         MonoInst *var;
1028
1029         var = g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
1030         if (var)
1031                 return var;
1032
1033         var = mono_compile_create_var (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL);
1034         /* prevent it from being register allocated */
1035         var->flags |= MONO_INST_INDIRECT;
1036
1037         g_hash_table_insert (cfg->exvars, GINT_TO_POINTER (offset), var);
1038
1039         return var;
1040 }
1041
1042 static void
1043 df_visit (MonoBasicBlock *start, int *dfn, MonoBasicBlock **array)
1044 {
1045         int i;
1046
1047         array [*dfn] = start;
1048         /*g_print ("visit %d at %p (BB%ld)\n", *dfn, start->cil_code, start->block_num);*/
1049         for (i = 0; i < start->out_count; ++i) {
1050                 if (start->out_bb [i]->dfn)
1051                         continue;
1052                 (*dfn)++;
1053                 start->out_bb [i]->dfn = *dfn;
1054                 start->out_bb [i]->df_parent = start;
1055                 array [*dfn] = start->out_bb [i];
1056                 df_visit (start->out_bb [i], dfn, array);
1057         }
1058 }
1059
1060 static MonoBasicBlock*
1061 find_previous (MonoBasicBlock **bblocks, guint32 n_bblocks, MonoBasicBlock *start, const guchar *code)
1062 {
1063         MonoBasicBlock *best = start;
1064         int i;
1065
1066         for (i = 0; i < n_bblocks; ++i) {
1067                 if (bblocks [i]) {
1068                         MonoBasicBlock *bb = bblocks [i];
1069
1070                         if (bb->cil_code && bb->cil_code < code && bb->cil_code > best->cil_code)
1071                                 best = bb;
1072                 }
1073         }
1074
1075         return best;
1076 }
1077
1078 static void
1079 split_bblock (MonoCompile *cfg, MonoBasicBlock *first, MonoBasicBlock *second) {
1080         int i, j;
1081         MonoInst *inst;
1082         MonoBasicBlock *bb;
1083
1084         if (!MONO_INST_LIST_EMPTY (&second->ins_list))
1085                 return;
1086         
1087         /* 
1088          * FIXME: take into account all the details:
1089          * second may have been the target of more than one bblock
1090          */
1091         second->out_count = first->out_count;
1092         second->out_bb = first->out_bb;
1093
1094         for (i = 0; i < first->out_count; ++i) {
1095                 bb = first->out_bb [i];
1096                 for (j = 0; j < bb->in_count; ++j) {
1097                         if (bb->in_bb [j] == first)
1098                                 bb->in_bb [j] = second;
1099                 }
1100         }
1101
1102         first->out_count = 0;
1103         first->out_bb = NULL;
1104         link_bblock (cfg, first, second);
1105
1106         /*g_print ("start search at %p for %p\n", first->cil_code, second->cil_code);*/
1107         MONO_BB_FOR_EACH_INS (first, inst) {
1108                 MonoInst *inst_next;
1109
1110                 /*char *code = mono_disasm_code_one (NULL, cfg->method, inst->next->cil_code, NULL);
1111                 g_print ("found %p: %s", inst->next->cil_code, code);
1112                 g_free (code);*/
1113                 if (inst->cil_code >= second->cil_code)
1114                         continue;
1115
1116                 inst_next = mono_inst_list_next (&inst->node, &first->ins_list);
1117                 if (!inst_next)
1118                         break;
1119
1120                 if (inst_next->cil_code < second->cil_code)
1121                         continue;
1122                         
1123                 second->ins_list.next = inst->node.next;
1124                 second->ins_list.prev = first->ins_list.prev;
1125                 inst->node.next = &first->ins_list;
1126                 first->ins_list.prev = &inst->node;
1127
1128                 second->next_bb = first->next_bb;
1129                 first->next_bb = second;
1130                 return;
1131         }
1132         if (MONO_INST_LIST_EMPTY (&second->ins_list)) {
1133                 g_warning ("bblock split failed in %s::%s\n", cfg->method->klass->name, cfg->method->name);
1134                 //G_BREAKPOINT ();
1135         }
1136 }
1137
1138 static guint32
1139 reverse_branch_op (guint32 opcode)
1140 {
1141         static const int reverse_map [] = {
1142                 CEE_BNE_UN, CEE_BLT, CEE_BLE, CEE_BGT, CEE_BGE,
1143                 CEE_BEQ, CEE_BLT_UN, CEE_BLE_UN, CEE_BGT_UN, CEE_BGE_UN
1144         };
1145         static const int reverse_fmap [] = {
1146                 OP_FBNE_UN, OP_FBLT, OP_FBLE, OP_FBGT, OP_FBGE,
1147                 OP_FBEQ, OP_FBLT_UN, OP_FBLE_UN, OP_FBGT_UN, OP_FBGE_UN
1148         };
1149         static const int reverse_lmap [] = {
1150                 OP_LBNE_UN, OP_LBLT, OP_LBLE, OP_LBGT, OP_LBGE,
1151                 OP_LBEQ, OP_LBLT_UN, OP_LBLE_UN, OP_LBGT_UN, OP_LBGE_UN
1152         };
1153         static const int reverse_imap [] = {
1154                 OP_IBNE_UN, OP_IBLT, OP_IBLE, OP_IBGT, OP_IBGE,
1155                 OP_IBEQ, OP_IBLT_UN, OP_IBLE_UN, OP_IBGT_UN, OP_IBGE_UN
1156         };
1157                                 
1158         if (opcode >= CEE_BEQ && opcode <= CEE_BLT_UN) {
1159                 opcode = reverse_map [opcode - CEE_BEQ];
1160         } else if (opcode >= OP_FBEQ && opcode <= OP_FBLT_UN) {
1161                 opcode = reverse_fmap [opcode - OP_FBEQ];
1162         } else if (opcode >= OP_LBEQ && opcode <= OP_LBLT_UN) {
1163                 opcode = reverse_lmap [opcode - OP_LBEQ];
1164         } else if (opcode >= OP_IBEQ && opcode <= OP_IBLT_UN) {
1165                 opcode = reverse_imap [opcode - OP_IBEQ];
1166         } else
1167                 g_assert_not_reached ();
1168
1169         return opcode;
1170 }
1171
1172 #ifdef MONO_ARCH_SOFT_FLOAT
1173 static int
1174 condbr_to_fp_br (int opcode)
1175 {
1176         switch (opcode) {
1177         case CEE_BEQ: return OP_FBEQ;
1178         case CEE_BGE: return OP_FBGE;
1179         case CEE_BGT: return OP_FBGT;
1180         case CEE_BLE: return OP_FBLE;
1181         case CEE_BLT: return OP_FBLT;
1182         case CEE_BNE_UN: return OP_FBNE_UN;
1183         case CEE_BGE_UN: return OP_FBGE_UN;
1184         case CEE_BGT_UN: return OP_FBGT_UN;
1185         case CEE_BLE_UN: return OP_FBLE_UN;
1186         case CEE_BLT_UN: return OP_FBLT_UN;
1187         }
1188         g_assert_not_reached ();
1189         return 0;
1190 }
1191 #endif
1192
1193 /*
1194  * Returns the type used in the eval stack when @type is loaded.
1195  * FIXME: return a MonoType/MonoClass for the byref and VALUETYPE cases.
1196  */
1197 static void
1198 type_to_eval_stack_type (MonoCompile *cfg, MonoType *type, MonoInst *inst)
1199 {
1200         MonoClass *klass;
1201
1202         inst->klass = klass = mono_class_from_mono_type (type);
1203         if (type->byref) {
1204                 inst->type = STACK_MP;
1205                 return;
1206         }
1207
1208 handle_enum:
1209         switch (type->type) {
1210         case MONO_TYPE_VOID:
1211                 inst->type = STACK_INV;
1212                 return;
1213         case MONO_TYPE_I1:
1214         case MONO_TYPE_U1:
1215         case MONO_TYPE_BOOLEAN:
1216         case MONO_TYPE_I2:
1217         case MONO_TYPE_U2:
1218         case MONO_TYPE_CHAR:
1219         case MONO_TYPE_I4:
1220         case MONO_TYPE_U4:
1221                 inst->type = STACK_I4;
1222                 return;
1223         case MONO_TYPE_I:
1224         case MONO_TYPE_U:
1225         case MONO_TYPE_PTR:
1226         case MONO_TYPE_FNPTR:
1227                 inst->type = STACK_PTR;
1228                 return;
1229         case MONO_TYPE_CLASS:
1230         case MONO_TYPE_STRING:
1231         case MONO_TYPE_OBJECT:
1232         case MONO_TYPE_SZARRAY:
1233         case MONO_TYPE_ARRAY:    
1234                 inst->type = STACK_OBJ;
1235                 return;
1236         case MONO_TYPE_I8:
1237         case MONO_TYPE_U8:
1238                 inst->type = STACK_I8;
1239                 return;
1240         case MONO_TYPE_R4:
1241         case MONO_TYPE_R8:
1242                 inst->type = STACK_R8;
1243                 return;
1244         case MONO_TYPE_VALUETYPE:
1245                 if (type->data.klass->enumtype) {
1246                         type = type->data.klass->enum_basetype;
1247                         goto handle_enum;
1248                 } else {
1249                         inst->klass = klass;
1250                         inst->type = STACK_VTYPE;
1251                         return;
1252                 }
1253         case MONO_TYPE_TYPEDBYREF:
1254                 inst->klass = mono_defaults.typed_reference_class;
1255                 inst->type = STACK_VTYPE;
1256                 return;
1257         case MONO_TYPE_GENERICINST:
1258                 type = &type->data.generic_class->container_class->byval_arg;
1259                 goto handle_enum;
1260         case MONO_TYPE_VAR :
1261         case MONO_TYPE_MVAR :
1262                 /* FIXME: all the arguments must be references for now,
1263                  * later look inside cfg and see if the arg num is
1264                  * really a reference
1265                  */
1266                 g_assert (cfg->generic_sharing_context);
1267                 inst->type = STACK_OBJ;
1268                 return;
1269         default:
1270                 g_error ("unknown type 0x%02x in eval stack type", type->type);
1271         }
1272 }
1273
1274 /*
1275  * The following tables are used to quickly validate the IL code in type_from_op ().
1276  */
1277 static const char
1278 bin_num_table [STACK_MAX] [STACK_MAX] = {
1279         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1280         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
1281         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1282         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
1283         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_R8,  STACK_INV, STACK_INV, STACK_INV},
1284         {STACK_INV, STACK_MP,  STACK_INV, STACK_MP,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV},
1285         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1286         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1287 };
1288
1289 static const char 
1290 neg_table [] = {
1291         STACK_INV, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_INV, STACK_INV, STACK_INV
1292 };
1293
1294 /* reduce the size of this table */
1295 static const char
1296 bin_int_table [STACK_MAX] [STACK_MAX] = {
1297         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1298         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1299         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1300         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1301         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1302         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1303         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1304         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1305 };
1306
1307 static const char
1308 bin_comp_table [STACK_MAX] [STACK_MAX] = {
1309 /*      Inv i  L  p  F  &  O  vt */
1310         {0},
1311         {0, 1, 0, 1, 0, 0, 0, 0}, /* i, int32 */
1312         {0, 0, 1, 0, 0, 0, 0, 0}, /* L, int64 */
1313         {0, 1, 0, 1, 0, 2, 4, 0}, /* p, ptr */
1314         {0, 0, 0, 0, 1, 0, 0, 0}, /* F, R8 */
1315         {0, 0, 0, 2, 0, 1, 0, 0}, /* &, managed pointer */
1316         {0, 0, 0, 4, 0, 0, 3, 0}, /* O, reference */
1317         {0, 0, 0, 0, 0, 0, 0, 0}, /* vt value type */
1318 };
1319
1320 /* reduce the size of this table */
1321 static const char
1322 shift_table [STACK_MAX] [STACK_MAX] = {
1323         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1324         {STACK_INV, STACK_I4,  STACK_INV, STACK_I4,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1325         {STACK_INV, STACK_I8,  STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1326         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1327         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1328         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1329         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1330         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1331 };
1332
1333 /*
1334  * Tables to map from the non-specific opcode to the matching
1335  * type-specific opcode.
1336  */
1337 /* handles from CEE_ADD to CEE_SHR_UN (CEE_REM_UN for floats) */
1338 static const guint16
1339 binops_op_map [STACK_MAX] = {
1340         0, 0, OP_LADD-CEE_ADD, OP_PADD-CEE_ADD, OP_FADD-CEE_ADD, OP_PADD-CEE_ADD
1341 };
1342
1343 /* handles from CEE_NEG to CEE_CONV_U8 */
1344 static const guint16
1345 unops_op_map [STACK_MAX] = {
1346         0, 0, OP_LNEG-CEE_NEG, OP_PNEG-CEE_NEG, OP_FNEG-CEE_NEG, OP_PNEG-CEE_NEG
1347 };
1348
1349 /* handles from CEE_CONV_U2 to CEE_SUB_OVF_UN */
1350 static const guint16
1351 ovfops_op_map [STACK_MAX] = {
1352         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
1353 };
1354
1355 /* handles from CEE_CONV_OVF_I1_UN to CEE_CONV_OVF_U_UN */
1356 static const guint16
1357 ovf2ops_op_map [STACK_MAX] = {
1358         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
1359 };
1360
1361 /* handles from CEE_CONV_OVF_I1 to CEE_CONV_OVF_U8 */
1362 static const guint16
1363 ovf3ops_op_map [STACK_MAX] = {
1364         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
1365 };
1366
1367 /* handles from CEE_CEQ to CEE_CLT_UN */
1368 static const guint16
1369 ceqops_op_map [STACK_MAX] = {
1370         0, 0, OP_LCEQ-OP_CEQ, OP_PCEQ-OP_CEQ, OP_FCEQ-OP_CEQ, OP_LCEQ-OP_CEQ
1371 };
1372
1373 /*
1374  * Sets ins->type (the type on the eval stack) according to the
1375  * type of the opcode and the arguments to it.
1376  * Invalid IL code is marked by setting ins->type to the invalid value STACK_INV.
1377  *
1378  * FIXME: this function sets ins->type unconditionally in some cases, but
1379  * it should set it to invalid for some types (a conv.x on an object)
1380  */
1381 static void
1382 type_from_op (MonoInst *ins) {
1383         switch (ins->opcode) {
1384         /* binops */
1385         case CEE_ADD:
1386         case CEE_SUB:
1387         case CEE_MUL:
1388         case CEE_DIV:
1389         case CEE_REM:
1390                 /* FIXME: check unverifiable args for STACK_MP */
1391                 ins->type = bin_num_table [ins->inst_i0->type] [ins->inst_i1->type];
1392                 ins->opcode += binops_op_map [ins->type];
1393                 return;
1394         case CEE_DIV_UN:
1395         case CEE_REM_UN:
1396         case CEE_AND:
1397         case CEE_OR:
1398         case CEE_XOR:
1399                 ins->type = bin_int_table [ins->inst_i0->type] [ins->inst_i1->type];
1400                 ins->opcode += binops_op_map [ins->type];
1401                 return;
1402         case CEE_SHL:
1403         case CEE_SHR:
1404         case CEE_SHR_UN:
1405                 ins->type = shift_table [ins->inst_i0->type] [ins->inst_i1->type];
1406                 ins->opcode += binops_op_map [ins->type];
1407                 return;
1408         case OP_COMPARE:
1409         case OP_LCOMPARE:
1410                 /* FIXME: handle some specifics with ins->next->type */
1411                 ins->type = bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] ? STACK_I4: STACK_INV;
1412                 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))))
1413                         ins->opcode = OP_LCOMPARE;
1414                 return;
1415         case OP_CEQ:
1416                 ins->type = bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] ? STACK_I4: STACK_INV;
1417                 ins->opcode += ceqops_op_map [ins->inst_i0->type];
1418                 return;
1419                 
1420         case OP_CGT:
1421         case OP_CGT_UN:
1422         case OP_CLT:
1423         case OP_CLT_UN:
1424                 ins->type = (bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] & 1) ? STACK_I4: STACK_INV;
1425                 ins->opcode += ceqops_op_map [ins->inst_i0->type];
1426                 return;
1427         /* unops */
1428         case CEE_NEG:
1429                 ins->type = neg_table [ins->inst_i0->type];
1430                 ins->opcode += unops_op_map [ins->type];
1431                 return;
1432         case CEE_NOT:
1433                 if (ins->inst_i0->type >= STACK_I4 && ins->inst_i0->type <= STACK_PTR)
1434                         ins->type = ins->inst_i0->type;
1435                 else
1436                         ins->type = STACK_INV;
1437                 ins->opcode += unops_op_map [ins->type];
1438                 return;
1439         case CEE_CONV_I1:
1440         case CEE_CONV_I2:
1441         case CEE_CONV_I4:
1442         case CEE_CONV_U4:
1443                 ins->type = STACK_I4;
1444                 ins->opcode += unops_op_map [ins->inst_i0->type];
1445                 return;
1446         case CEE_CONV_R_UN:
1447                 ins->type = STACK_R8;
1448                 switch (ins->inst_i0->type) {
1449                 case STACK_I4:
1450                 case STACK_PTR:
1451                         break;
1452                 case STACK_I8:
1453                         ins->opcode = OP_LCONV_TO_R_UN; 
1454                         break;
1455                 }
1456                 return;
1457         case CEE_CONV_OVF_I1:
1458         case CEE_CONV_OVF_U1:
1459         case CEE_CONV_OVF_I2:
1460         case CEE_CONV_OVF_U2:
1461         case CEE_CONV_OVF_I4:
1462         case CEE_CONV_OVF_U4:
1463                 ins->type = STACK_I4;
1464                 ins->opcode += ovf3ops_op_map [ins->inst_i0->type];
1465                 return;
1466         case CEE_CONV_OVF_I_UN:
1467         case CEE_CONV_OVF_U_UN:
1468                 ins->type = STACK_PTR;
1469                 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1470                 return;
1471         case CEE_CONV_OVF_I1_UN:
1472         case CEE_CONV_OVF_I2_UN:
1473         case CEE_CONV_OVF_I4_UN:
1474         case CEE_CONV_OVF_U1_UN:
1475         case CEE_CONV_OVF_U2_UN:
1476         case CEE_CONV_OVF_U4_UN:
1477                 ins->type = STACK_I4;
1478                 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1479                 return;
1480         case CEE_CONV_U:
1481                 ins->type = STACK_PTR;
1482                 switch (ins->inst_i0->type) {
1483                 case STACK_I4:
1484                         break;
1485                 case STACK_PTR:
1486                 case STACK_MP:
1487 #if SIZEOF_VOID_P == 8
1488                         ins->opcode = OP_LCONV_TO_U;
1489 #endif
1490                         break;
1491                 case STACK_I8:
1492                         ins->opcode = OP_LCONV_TO_U;
1493                         break;
1494                 case STACK_R8:
1495                         ins->opcode = OP_FCONV_TO_U;
1496                         break;
1497                 }
1498                 return;
1499         case CEE_CONV_I8:
1500         case CEE_CONV_U8:
1501                 ins->type = STACK_I8;
1502                 ins->opcode += unops_op_map [ins->inst_i0->type];
1503                 return;
1504         case CEE_CONV_OVF_I8:
1505         case CEE_CONV_OVF_U8:
1506                 ins->type = STACK_I8;
1507                 ins->opcode += ovf3ops_op_map [ins->inst_i0->type];
1508                 return;
1509         case CEE_CONV_OVF_U8_UN:
1510         case CEE_CONV_OVF_I8_UN:
1511                 ins->type = STACK_I8;
1512                 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1513                 return;
1514         case CEE_CONV_R4:
1515         case CEE_CONV_R8:
1516                 ins->type = STACK_R8;
1517                 ins->opcode += unops_op_map [ins->inst_i0->type];
1518                 return;
1519         case OP_CKFINITE:
1520                 ins->type = STACK_R8;           
1521                 return;
1522         case CEE_CONV_U2:
1523         case CEE_CONV_U1:
1524                 ins->type = STACK_I4;
1525                 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1526                 break;
1527         case CEE_CONV_I:
1528         case CEE_CONV_OVF_I:
1529         case CEE_CONV_OVF_U:
1530                 ins->type = STACK_PTR;
1531                 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1532                 return;
1533         case CEE_ADD_OVF:
1534         case CEE_ADD_OVF_UN:
1535         case CEE_MUL_OVF:
1536         case CEE_MUL_OVF_UN:
1537         case CEE_SUB_OVF:
1538         case CEE_SUB_OVF_UN:
1539                 ins->type = bin_num_table [ins->inst_i0->type] [ins->inst_i1->type];
1540                 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1541                 if (ins->type == STACK_R8)
1542                         ins->type = STACK_INV;
1543                 return;
1544         default:
1545                 g_error ("opcode 0x%04x not handled in type from op", ins->opcode);
1546                 break;
1547         }
1548 }
1549
1550 static const char 
1551 ldind_type [] = {
1552         STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_R8, STACK_OBJ
1553 };
1554
1555 /* map ldelem.x to the matching ldind.x opcode */
1556 static const guchar
1557 ldelem_to_ldind [] = {
1558         CEE_LDIND_I1,
1559         CEE_LDIND_U1,
1560         CEE_LDIND_I2,
1561         CEE_LDIND_U2,
1562         CEE_LDIND_I4,
1563         CEE_LDIND_U4,
1564         CEE_LDIND_I8,
1565         CEE_LDIND_I,
1566         CEE_LDIND_R4,
1567         CEE_LDIND_R8,
1568         CEE_LDIND_REF
1569 };
1570
1571 /* map stelem.x to the matching stind.x opcode */
1572 static const guchar
1573 stelem_to_stind [] = {
1574         CEE_STIND_I,
1575         CEE_STIND_I1,
1576         CEE_STIND_I2,
1577         CEE_STIND_I4,
1578         CEE_STIND_I8,
1579         CEE_STIND_R4,
1580         CEE_STIND_R8,
1581         CEE_STIND_REF
1582 };
1583
1584 #if 0
1585
1586 static const char
1587 param_table [STACK_MAX] [STACK_MAX] = {
1588         {0},
1589 };
1590
1591 static int
1592 check_values_to_signature (MonoInst *args, MonoType *this, MonoMethodSignature *sig) {
1593         int i;
1594
1595         if (sig->hasthis) {
1596                 switch (args->type) {
1597                 case STACK_I4:
1598                 case STACK_I8:
1599                 case STACK_R8:
1600                 case STACK_VTYPE:
1601                 case STACK_INV:
1602                         return 0;
1603                 }
1604                 args++;
1605         }
1606         for (i = 0; i < sig->param_count; ++i) {
1607                 switch (args [i].type) {
1608                 case STACK_INV:
1609                         return 0;
1610                 case STACK_MP:
1611                         if (!sig->params [i]->byref)
1612                                 return 0;
1613                         continue;
1614                 case STACK_OBJ:
1615                         if (sig->params [i]->byref)
1616                                 return 0;
1617                         switch (sig->params [i]->type) {
1618                         case MONO_TYPE_CLASS:
1619                         case MONO_TYPE_STRING:
1620                         case MONO_TYPE_OBJECT:
1621                         case MONO_TYPE_SZARRAY:
1622                         case MONO_TYPE_ARRAY:
1623                                 break;
1624                         default:
1625                                 return 0;
1626                         }
1627                         continue;
1628                 case STACK_R8:
1629                         if (sig->params [i]->byref)
1630                                 return 0;
1631                         if (sig->params [i]->type != MONO_TYPE_R4 && sig->params [i]->type != MONO_TYPE_R8)
1632                                 return 0;
1633                         continue;
1634                 case STACK_PTR:
1635                 case STACK_I4:
1636                 case STACK_I8:
1637                 case STACK_VTYPE:
1638                         break;
1639                 }
1640                 /*if (!param_table [args [i].type] [sig->params [i]->type])
1641                         return 0;*/
1642         }
1643         return 1;
1644 }
1645 #endif
1646
1647 static guint
1648 mini_type_to_ldind (MonoCompile* cfg, MonoType *type)
1649 {
1650         if (cfg->generic_sharing_context && !type->byref) {
1651                 /* FIXME: all the arguments must be references for now,
1652                  * later look inside cfg and see if the arg num is
1653                  * really a reference
1654                  */
1655                 if (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)
1656                         return CEE_LDIND_REF;
1657         }
1658         return mono_type_to_ldind (type);
1659 }
1660
1661 static guint
1662 mini_type_to_stind (MonoCompile* cfg, MonoType *type)
1663 {
1664         if (cfg->generic_sharing_context && !type->byref) {
1665                 /* FIXME: all the arguments must be references for now,
1666                  * later look inside cfg and see if the arg num is
1667                  * really a reference
1668                  */
1669                 if (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)
1670                         return CEE_STIND_REF;
1671         }
1672         return mono_type_to_stind (type);
1673 }
1674
1675 int
1676 mono_op_imm_to_op (int opcode)
1677 {
1678         switch (opcode) {
1679         case OP_ADD_IMM:
1680                 return OP_PADD;
1681         case OP_IADD_IMM:
1682                 return OP_IADD;
1683         case OP_LADD_IMM:
1684                 return OP_LADD;
1685         case OP_ISUB_IMM:
1686                 return OP_ISUB;
1687         case OP_LSUB_IMM:
1688                 return OP_LSUB;
1689         case OP_AND_IMM:
1690 #if SIZEOF_VOID_P == 4
1691                 return OP_IAND;
1692 #else
1693                 return OP_LAND;
1694 #endif
1695         case OP_IAND_IMM:
1696                 return OP_IAND;
1697         case OP_LAND_IMM:
1698                 return OP_LAND;
1699         case OP_IOR_IMM:
1700                 return OP_IOR;
1701         case OP_LOR_IMM:
1702                 return OP_LOR;
1703         case OP_IXOR_IMM:
1704                 return OP_IXOR;
1705         case OP_LXOR_IMM:
1706                 return OP_LXOR;
1707         case OP_ISHL_IMM:
1708                 return OP_ISHL;
1709         case OP_LSHL_IMM:
1710                 return OP_LSHL;
1711         case OP_ISHR_IMM:
1712                 return OP_ISHR;
1713         case OP_LSHR_IMM:
1714                 return OP_LSHR;
1715         case OP_ISHR_UN_IMM:
1716                 return OP_ISHR_UN;
1717         case OP_LSHR_UN_IMM:
1718                 return OP_LSHR_UN;
1719         case OP_IDIV_IMM:
1720                 return OP_IDIV;
1721         case OP_IDIV_UN_IMM:
1722                 return OP_IDIV_UN;
1723         case OP_IREM_UN_IMM:
1724                 return OP_IREM_UN;
1725         case OP_IREM_IMM:
1726                 return OP_IREM;
1727         case OP_DIV_IMM:
1728 #if SIZEOF_VOID_P == 4
1729                 return OP_IDIV;
1730 #else
1731                 return OP_LDIV;
1732 #endif
1733         case OP_REM_IMM:
1734 #if SIZEOF_VOID_P == 4
1735                 return OP_IREM;
1736 #else
1737                 return OP_LREM;
1738 #endif
1739         case OP_ADDCC_IMM:
1740                 return OP_ADDCC;
1741         case OP_ADC_IMM:
1742                 return OP_ADC;
1743         case OP_SUBCC_IMM:
1744                 return OP_SUBCC;
1745         case OP_SBB_IMM:
1746                 return OP_SBB;
1747         case OP_IADC_IMM:
1748                 return OP_IADC;
1749         case OP_ISBB_IMM:
1750                 return OP_ISBB;
1751         case OP_COMPARE_IMM:
1752                 return OP_COMPARE;
1753         case OP_ICOMPARE_IMM:
1754                 return OP_ICOMPARE;
1755         default:
1756                 printf ("%s\n", mono_inst_name (opcode));
1757                 g_assert_not_reached ();
1758         }
1759 }
1760
1761 /*
1762  * When we need a pointer to the current domain many times in a method, we
1763  * call mono_domain_get() once and we store the result in a local variable.
1764  * This function returns the variable that represents the MonoDomain*.
1765  */
1766 inline static MonoInst *
1767 mono_get_domainvar (MonoCompile *cfg)
1768 {
1769         if (!cfg->domainvar)
1770                 cfg->domainvar = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1771         return cfg->domainvar;
1772 }
1773
1774 /*
1775  * The got_var contains the address of the Global Offset Table when AOT 
1776  * compiling.
1777  */
1778 inline static MonoInst *
1779 mono_get_got_var (MonoCompile *cfg)
1780 {
1781 #ifdef MONO_ARCH_NEED_GOT_VAR
1782         if (!cfg->compile_aot)
1783                 return NULL;
1784         if (!cfg->got_var) {
1785                 cfg->got_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1786         }
1787         return cfg->got_var;
1788 #else
1789         return NULL;
1790 #endif
1791 }
1792
1793 MonoInst*
1794 mono_compile_create_var (MonoCompile *cfg, MonoType *type, int opcode)
1795 {
1796         MonoInst *inst;
1797         int num = cfg->num_varinfo;
1798
1799         if ((num + 1) >= cfg->varinfo_count) {
1800                 int orig_count = cfg->varinfo_count;
1801                 cfg->varinfo_count = (cfg->varinfo_count + 2) * 2;
1802                 cfg->varinfo = (MonoInst **)g_realloc (cfg->varinfo, sizeof (MonoInst*) * cfg->varinfo_count);
1803                 cfg->vars = (MonoMethodVar *)g_realloc (cfg->vars, sizeof (MonoMethodVar) * cfg->varinfo_count);
1804                 memset (&cfg->vars [orig_count], 0, (cfg->varinfo_count - orig_count) * sizeof (MonoMethodVar));
1805         }
1806
1807         /*g_print ("created temp %d of type 0x%x\n", num, type->type);*/
1808         mono_jit_stats.allocate_var++;
1809
1810         MONO_INST_NEW (cfg, inst, opcode);
1811         inst->inst_c0 = num;
1812         inst->inst_vtype = type;
1813         inst->klass = mono_class_from_mono_type (type);
1814         /* if set to 1 the variable is native */
1815         inst->backend.is_pinvoke = 0;
1816
1817         cfg->varinfo [num] = inst;
1818
1819         MONO_INIT_VARINFO (&cfg->vars [num], num);
1820
1821         cfg->num_varinfo++;
1822         if (cfg->verbose_level > 2)
1823                 g_print ("created temp %d of type %s\n", num, mono_type_get_name (type));
1824         return inst;
1825 }
1826
1827 /*
1828  * Transform a MonoInst into a load from the variable of index var_index.
1829  */
1830 void
1831 mono_compile_make_var_load (MonoCompile *cfg, MonoInst *dest, gssize var_index) {
1832         memset (dest, 0, sizeof (MonoInst));
1833         dest->ssa_op = MONO_SSA_LOAD;
1834         dest->inst_i0 = cfg->varinfo [var_index];
1835         dest->opcode = mini_type_to_ldind (cfg, dest->inst_i0->inst_vtype);
1836         type_to_eval_stack_type (cfg, dest->inst_i0->inst_vtype, dest);
1837         dest->klass = dest->inst_i0->klass;
1838 }
1839
1840 /*
1841  * Create a MonoInst that is a load from the variable of index var_index.
1842  */
1843 MonoInst*
1844 mono_compile_create_var_load (MonoCompile *cfg, gssize var_index) {
1845         MonoInst *dest;
1846         NEW_TEMPLOAD (cfg,dest,var_index);
1847         return dest;
1848 }
1849
1850 /*
1851  * Create a MonoInst that is a store of the given value into the variable of index var_index.
1852  */
1853 MonoInst*
1854 mono_compile_create_var_store (MonoCompile *cfg, gssize var_index, MonoInst *value) {
1855         MonoInst *dest;
1856         NEW_TEMPSTORE (cfg, dest, var_index, value);
1857         return dest;
1858 }
1859
1860 static MonoType*
1861 type_from_stack_type (MonoInst *ins) {
1862         switch (ins->type) {
1863         case STACK_I4: return &mono_defaults.int32_class->byval_arg;
1864         case STACK_I8: return &mono_defaults.int64_class->byval_arg;
1865         case STACK_PTR: return &mono_defaults.int_class->byval_arg;
1866         case STACK_R8: return &mono_defaults.double_class->byval_arg;
1867         case STACK_MP:
1868                 /* 
1869                  * this if used to be commented without any specific reason, but
1870                  * it breaks #80235 when commented
1871                  */
1872                 if (ins->klass)
1873                         return &ins->klass->this_arg;
1874                 else
1875                         return &mono_defaults.object_class->this_arg;
1876         case STACK_OBJ:
1877                 /* ins->klass may not be set for ldnull.
1878                  * Also, if we have a boxed valuetype, we want an object lass,
1879                  * not the valuetype class
1880                  */
1881                 if (ins->klass && !ins->klass->valuetype)
1882                         return &ins->klass->byval_arg;
1883                 return &mono_defaults.object_class->byval_arg;
1884         case STACK_VTYPE: return &ins->klass->byval_arg;
1885         default:
1886                 g_error ("stack type %d to montype not handled\n", ins->type);
1887         }
1888         return NULL;
1889 }
1890
1891 MonoType*
1892 mono_type_from_stack_type (MonoInst *ins) {
1893         return type_from_stack_type (ins);
1894 }
1895
1896 static MonoClass*
1897 array_access_to_klass (int opcode, MonoInst *array_obj)
1898 {
1899         switch (opcode) {
1900         case CEE_LDELEM_U1:
1901                 return mono_defaults.byte_class;
1902         case CEE_LDELEM_U2:
1903                 return mono_defaults.uint16_class;
1904         case CEE_LDELEM_I:
1905         case CEE_STELEM_I:
1906                 return mono_defaults.int_class;
1907         case CEE_LDELEM_I1:
1908         case CEE_STELEM_I1:
1909                 return mono_defaults.sbyte_class;
1910         case CEE_LDELEM_I2:
1911         case CEE_STELEM_I2:
1912                 return mono_defaults.int16_class;
1913         case CEE_LDELEM_I4:
1914         case CEE_STELEM_I4:
1915                 return mono_defaults.int32_class;
1916         case CEE_LDELEM_U4:
1917                 return mono_defaults.uint32_class;
1918         case CEE_LDELEM_I8:
1919         case CEE_STELEM_I8:
1920                 return mono_defaults.int64_class;
1921         case CEE_LDELEM_R4:
1922         case CEE_STELEM_R4:
1923                 return mono_defaults.single_class;
1924         case CEE_LDELEM_R8:
1925         case CEE_STELEM_R8:
1926                 return mono_defaults.double_class;
1927         case CEE_LDELEM_REF:
1928         case CEE_STELEM_REF: {
1929                 MonoClass *klass = array_obj->klass;
1930                 /* FIXME: add assert */
1931                 if (klass && klass->rank)
1932                         return klass->element_class;
1933                 return mono_defaults.object_class;
1934         }
1935         default:
1936                 g_assert_not_reached ();
1937         }
1938         return NULL;
1939 }
1940
1941 void
1942 mono_add_ins_to_end (MonoBasicBlock *bb, MonoInst *inst)
1943 {
1944         MonoInst *last = mono_inst_list_last (&bb->ins_list);
1945
1946         if (last && ((last->opcode >= CEE_BEQ &&
1947                         last->opcode <= CEE_BLT_UN) ||
1948                         last->opcode == OP_BR ||
1949                         last->opcode == OP_SWITCH)) {
1950                 MONO_INST_LIST_ADD_TAIL (&inst->node, &last->node);
1951         } else {
1952                 MONO_ADD_INS (bb, inst);
1953         }
1954 }
1955
1956 void
1957 mono_add_varcopy_to_end (MonoCompile *cfg, MonoBasicBlock *bb, int src, int dest)
1958 {
1959         MonoInst *inst, *load;
1960
1961         NEW_TEMPLOAD (cfg, load, src);
1962
1963         NEW_TEMPSTORE (cfg, inst, dest, load);
1964         /* FIXME: handle CEE_STIND_R4 */
1965         if (inst->opcode == CEE_STOBJ) {
1966                 NEW_TEMPLOADA (cfg, inst, dest);
1967                 handle_stobj (cfg, bb, inst, load, NULL, inst->klass, TRUE, FALSE, FALSE);
1968         } else {
1969                 inst->cil_code = NULL;
1970                 mono_add_ins_to_end (bb, inst);
1971         }
1972 }
1973
1974 /*
1975  * merge_stacks:
1976  *
1977  * Merge stack state between two basic blocks according to Ecma 335, Partition III,
1978  * section 1.8.1.1. Store the resulting stack state into stack_2.
1979  * Returns: TRUE, if verification succeeds, FALSE otherwise.
1980  * FIXME: We should store the stack state in a dedicated structure instead of in
1981  * MonoInst's.
1982  */
1983 static gboolean
1984 merge_stacks (MonoCompile *cfg, MonoStackSlot *state_1, MonoStackSlot *state_2, guint32 size)
1985 {
1986         int i;
1987
1988         if (cfg->dont_verify_stack_merge)
1989                 return TRUE;
1990
1991         /* FIXME: Implement all checks from the spec */
1992
1993         for (i = 0; i < size; ++i) {
1994                 MonoStackSlot *slot1 = &state_1 [i];
1995                 MonoStackSlot *slot2 = &state_2 [i];
1996
1997                 if (slot1->type != slot2->type)
1998                         return FALSE;
1999
2000                 switch (slot1->type) {
2001                 case STACK_PTR:
2002                         /* FIXME: Perform merge ? */
2003                         /* klass == NULL means a native int */
2004                         if (slot1->klass && slot2->klass) {
2005                                 if (slot1->klass != slot2->klass)
2006                                         return FALSE;
2007                         }
2008                         break;
2009                 case STACK_MP:
2010                         /* FIXME: Change this to an assert and fix the JIT to allways fill this */
2011                         if (slot1->klass && slot2->klass) {
2012                                 if (slot1->klass != slot2->klass)
2013                                         return FALSE;
2014                         }
2015                         break;
2016                 case STACK_OBJ: {
2017                         MonoClass *klass1 = slot1->klass;
2018                         MonoClass *klass2 = slot2->klass;
2019
2020                         if (!klass1) {
2021                                 /* slot1 is ldnull */
2022                         } else if (!klass2) {
2023                                 /* slot2 is ldnull */
2024                                 slot2->klass = slot1->klass;
2025                         }
2026                         break;
2027                 }
2028                 }
2029         }
2030
2031         return TRUE;
2032 }
2033
2034 /*
2035  * This function is called to handle items that are left on the evaluation stack
2036  * at basic block boundaries. What happens is that we save the values to local variables
2037  * and we reload them later when first entering the target basic block (with the
2038  * handle_loaded_temps () function).
2039  * It is also used to handle items on the stack in store opcodes, since it is
2040  * possible that the variable to be stored into is already on the stack, in
2041  * which case its old value should be used.
2042  * A single joint point will use the same variables (stored in the array bb->out_stack or
2043  * bb->in_stack, if the basic block is before or after the joint point).
2044  * If the stack merge fails at a join point, cfg->unverifiable is set.
2045  */
2046 static int
2047 handle_stack_args (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst **sp, int count) {
2048         int i, bindex;
2049         MonoBasicBlock *outb;
2050         MonoInst *inst, **locals;
2051         MonoStackSlot *stack_state;
2052         gboolean found;
2053
2054         if (!count)
2055                 return 0;
2056         if (cfg->verbose_level > 3)
2057                 g_print ("%d item(s) on exit from B%d\n", count, bb->block_num);
2058
2059         stack_state = mono_mempool_alloc (cfg->mempool, sizeof (MonoStackSlot) * count);
2060         for (i = 0; i < count; ++i) {
2061                 stack_state [i].type = sp [i]->type;
2062                 stack_state [i].klass = sp [i]->klass;
2063
2064                 /* Check that instructions other than ldnull have ins->klass set */
2065                 if (!cfg->dont_verify_stack_merge && (sp [i]->type == STACK_OBJ) && !((sp [i]->opcode == OP_PCONST) && sp [i]->inst_c0 == 0))
2066                         g_assert (sp [i]->klass);
2067         }
2068
2069         /* Perform verification and stack state merge */
2070         for (i = 0; i < bb->out_count; ++i) {
2071                 outb = bb->out_bb [i];
2072
2073                 /* exception handlers are linked, but they should not be considered for stack args */
2074                 if (outb->flags & BB_EXCEPTION_HANDLER)
2075                         continue;
2076                 if (outb->stack_state) {
2077                         gboolean verified;
2078
2079                         if (count != outb->in_scount) {
2080                                 cfg->unverifiable = TRUE;
2081                                 return 0;
2082                         }
2083                         verified = merge_stacks (cfg, stack_state, outb->stack_state, count);
2084                         if (!verified) {
2085                                 cfg->unverifiable = TRUE;
2086                                 return 0;
2087                         }
2088
2089                         if (cfg->verbose_level > 3) {
2090                                 int j;
2091
2092                                 for (j = 0; j < count; ++j)
2093                                         printf ("\tStack state of BB%d, slot %d=%d\n", outb->block_num, j, outb->stack_state [j].type);
2094                         }
2095                 } else {
2096                         /* Make a copy of the stack state */
2097                         outb->stack_state = mono_mempool_alloc (cfg->mempool, sizeof (MonoStackSlot) * count);
2098                         memcpy (outb->stack_state, stack_state, sizeof (MonoStackSlot) * count);
2099                 }
2100         }
2101
2102         if (!bb->out_scount) {
2103                 bb->out_scount = count;
2104                 //g_print ("bblock %d has out:", bb->block_num);
2105                 found = FALSE;
2106                 for (i = 0; i < bb->out_count; ++i) {
2107                         outb = bb->out_bb [i];
2108                         /* exception handlers are linked, but they should not be considered for stack args */
2109                         if (outb->flags & BB_EXCEPTION_HANDLER)
2110                                 continue;
2111                         //g_print (" %d", outb->block_num);
2112                         if (outb->in_stack) {
2113                                 found = TRUE;
2114                                 bb->out_stack = outb->in_stack;
2115                                 break;
2116                         }
2117                 }
2118                 //g_print ("\n");
2119                 if (!found) {
2120                         bb->out_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * count);
2121                         for (i = 0; i < count; ++i) {
2122                                 /* 
2123                                  * try to reuse temps already allocated for this purpouse, if they occupy the same
2124                                  * stack slot and if they are of the same type.
2125                                  * This won't cause conflicts since if 'local' is used to 
2126                                  * store one of the values in the in_stack of a bblock, then
2127                                  * the same variable will be used for the same outgoing stack 
2128                                  * slot as well. 
2129                                  * This doesn't work when inlining methods, since the bblocks
2130                                  * in the inlined methods do not inherit their in_stack from
2131                                  * the bblock they are inlined to. See bug #58863 for an
2132                                  * example.
2133                                  * This hack is disabled since it also prevents proper tracking of types.
2134                                  */
2135 #if 1
2136                                 bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
2137 #else
2138                                 if (cfg->inlined_method)
2139                                         bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
2140                                 else
2141                                         bb->out_stack [i] = mono_compile_get_interface_var (cfg, i, sp [i]);
2142 #endif
2143                         }
2144                 }
2145         }
2146
2147         for (i = 0; i < bb->out_count; ++i) {
2148                 outb = bb->out_bb [i];
2149                 /* exception handlers are linked, but they should not be considered for stack args */
2150                 if (outb->flags & BB_EXCEPTION_HANDLER)
2151                         continue;
2152                 if (outb->in_scount) {
2153                         if (outb->in_scount != bb->out_scount)
2154                                 G_BREAKPOINT ();
2155                         continue; /* check they are the same locals */
2156                 }
2157                 outb->in_scount = count;
2158                 outb->in_stack = bb->out_stack;
2159         }
2160
2161         locals = bb->out_stack;
2162         for (i = 0; i < count; ++i) {
2163                 /* add store ops at the end of the bb, before the branch */
2164                 NEW_TEMPSTORE (cfg, inst, locals [i]->inst_c0, sp [i]);
2165                 if (inst->opcode == CEE_STOBJ) {
2166                         NEW_TEMPLOADA (cfg, inst, locals [i]->inst_c0);
2167                         handle_stobj (cfg, bb, inst, sp [i], sp [i]->cil_code, inst->klass, TRUE, FALSE, FALSE);
2168                 } else {
2169                         inst->cil_code = sp [i]->cil_code;
2170                         mono_add_ins_to_end (bb, inst);
2171                 }
2172                 if (cfg->verbose_level > 3)
2173                         g_print ("storing %d to temp %d\n", i, (int)locals [i]->inst_c0);
2174         }
2175
2176         /*
2177          * It is possible that the out bblocks already have in_stack assigned, and
2178          * the in_stacks differ. In this case, we will store to all the different 
2179          * in_stacks.
2180          */
2181
2182         found = TRUE;
2183         bindex = 0;
2184         while (found) {
2185                 /* Find a bblock which has a different in_stack */
2186                 found = FALSE;
2187                 while (bindex < bb->out_count) {
2188                         outb = bb->out_bb [bindex];
2189                         /* exception handlers are linked, but they should not be considered for stack args */
2190                         if (outb->flags & BB_EXCEPTION_HANDLER) {
2191                                 bindex++;
2192                                 continue;
2193                         }
2194                         if (outb->in_stack != locals) {
2195                                 /* 
2196                                  * Instead of storing sp [i] to locals [i], we need to store
2197                                  * locals [i] to <new locals>[i], since the sp [i] tree can't
2198                                  * be shared between trees.
2199                                  */
2200                                 for (i = 0; i < count; ++i)
2201                                         mono_add_varcopy_to_end (cfg, bb, locals [i]->inst_c0, outb->in_stack [i]->inst_c0);
2202                                 locals = outb->in_stack;
2203                                 found = TRUE;
2204                                 break;
2205                         }
2206                         bindex ++;
2207                 }
2208         }
2209         
2210         return 0;
2211 }
2212
2213 static int
2214 ret_type_to_call_opcode (MonoType *type, int calli, int virt, MonoGenericSharingContext *gsctx)
2215 {
2216         if (type->byref)
2217                 return calli? OP_CALL_REG: virt? OP_CALLVIRT: OP_CALL;
2218
2219 handle_enum:
2220         type = mini_get_basic_type_from_generic (gsctx, type);
2221         switch (type->type) {
2222         case MONO_TYPE_VOID:
2223                 return calli? OP_VOIDCALL_REG: virt? OP_VOIDCALLVIRT: OP_VOIDCALL;
2224         case MONO_TYPE_I1:
2225         case MONO_TYPE_U1:
2226         case MONO_TYPE_BOOLEAN:
2227         case MONO_TYPE_I2:
2228         case MONO_TYPE_U2:
2229         case MONO_TYPE_CHAR:
2230         case MONO_TYPE_I4:
2231         case MONO_TYPE_U4:
2232                 return calli? OP_CALL_REG: virt? OP_CALLVIRT: OP_CALL;
2233         case MONO_TYPE_I:
2234         case MONO_TYPE_U:
2235         case MONO_TYPE_PTR:
2236         case MONO_TYPE_FNPTR:
2237                 return calli? OP_CALL_REG: virt? OP_CALLVIRT: OP_CALL;
2238         case MONO_TYPE_CLASS:
2239         case MONO_TYPE_STRING:
2240         case MONO_TYPE_OBJECT:
2241         case MONO_TYPE_SZARRAY:
2242         case MONO_TYPE_ARRAY:    
2243                 return calli? OP_CALL_REG: virt? OP_CALLVIRT: OP_CALL;
2244         case MONO_TYPE_I8:
2245         case MONO_TYPE_U8:
2246                 return calli? OP_LCALL_REG: virt? OP_LCALLVIRT: OP_LCALL;
2247         case MONO_TYPE_R4:
2248         case MONO_TYPE_R8:
2249                 return calli? OP_FCALL_REG: virt? OP_FCALLVIRT: OP_FCALL;
2250         case MONO_TYPE_VALUETYPE:
2251                 if (type->data.klass->enumtype) {
2252                         type = type->data.klass->enum_basetype;
2253                         goto handle_enum;
2254                 } else
2255                         return calli? OP_VCALL_REG: virt? OP_VCALLVIRT: OP_VCALL;
2256         case MONO_TYPE_TYPEDBYREF:
2257                 return calli? OP_VCALL_REG: virt? OP_VCALLVIRT: OP_VCALL;
2258         case MONO_TYPE_GENERICINST:
2259                 type = &type->data.generic_class->container_class->byval_arg;
2260                 goto handle_enum;
2261         default:
2262                 g_error ("unknown type 0x%02x in ret_type_to_call_opcode", type->type);
2263         }
2264         return -1;
2265 }
2266
2267 void
2268 mono_create_jump_table (MonoCompile *cfg, MonoInst *label, MonoBasicBlock **bbs, int num_blocks)
2269 {
2270         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
2271         MonoJumpInfoBBTable *table;
2272
2273         table = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfoBBTable));
2274         table->table = bbs;
2275         table->table_size = num_blocks;
2276         
2277         ji->ip.label = label;
2278         ji->type = MONO_PATCH_INFO_SWITCH;
2279         ji->data.table = table;
2280         ji->next = cfg->patch_info;
2281         cfg->patch_info = ji;
2282 }
2283
2284 static void
2285 mono_save_token_info (MonoCompile *cfg, MonoImage *image, guint32 token, gpointer key)
2286 {
2287         if (cfg->compile_aot) {
2288                 MonoJumpInfoToken *jump_info_token = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoToken));
2289                 jump_info_token->image = image;
2290                 jump_info_token->token = token;
2291                 g_hash_table_insert (cfg->token_info_hash, key, jump_info_token);
2292         }
2293 }
2294
2295 /*
2296  * When we add a tree of instructions, we need to ensure the instructions currently
2297  * on the stack are executed before (like, if we load a value from a local).
2298  * We ensure this by saving the currently loaded values to temps and rewriting the
2299  * instructions to load the values.
2300  * This is not done for opcodes that terminate a basic block (because it's handled already
2301  * by handle_stack_args ()) and for opcodes that can't change values, like POP.
2302  */
2303 static void
2304 handle_loaded_temps (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst **stack, MonoInst **sp)
2305 {
2306         MonoInst *load, *store, *temp, *ins;
2307
2308         while (stack < sp) {
2309                 ins = *stack;
2310                 /* handle also other constants */
2311                 if ((ins->opcode != OP_ICONST) &&
2312                     /* temps never get written to again, so we can safely avoid duplicating them */
2313                     !(ins->ssa_op == MONO_SSA_LOAD && ins->inst_i0->opcode == OP_LOCAL && ins->inst_i0->flags & MONO_INST_IS_TEMP)) {
2314                         temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
2315                         temp->flags |= MONO_INST_IS_TEMP;
2316                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2317                         store->cil_code = ins->cil_code;
2318                         if (store->opcode == CEE_STOBJ) {
2319                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
2320                                 handle_stobj (cfg, bblock, store, ins, ins->cil_code, temp->klass, FALSE, FALSE, FALSE);
2321                         } else
2322                                 MONO_ADD_INS (bblock, store);
2323                         NEW_TEMPLOAD (cfg, load, temp->inst_c0);
2324                         load->cil_code = ins->cil_code;
2325                         *stack = load;
2326                 }
2327                 stack++;
2328         }
2329 }
2330
2331 /*
2332  * target_type_is_incompatible:
2333  * @cfg: MonoCompile context
2334  *
2335  * Check that the item @arg on the evaluation stack can be stored
2336  * in the target type (can be a local, or field, etc).
2337  * The cfg arg can be used to check if we need verification or just
2338  * validity checks.
2339  *
2340  * Returns: non-0 value if arg can't be stored on a target.
2341  */
2342 static int
2343 target_type_is_incompatible (MonoCompile *cfg, MonoType *target, MonoInst *arg)
2344 {
2345         MonoType *simple_type;
2346         MonoClass *klass;
2347
2348         if (target->byref) {
2349                 /* FIXME: check that the pointed to types match */
2350                 if (arg->type == STACK_MP)
2351                         return arg->klass != mono_class_from_mono_type (target);
2352                 if (arg->type == STACK_PTR)
2353                         return 0;
2354                 return 1;
2355         }
2356         simple_type = mono_type_get_underlying_type (target);
2357         switch (simple_type->type) {
2358         case MONO_TYPE_VOID:
2359                 return 1;
2360         case MONO_TYPE_I1:
2361         case MONO_TYPE_U1:
2362         case MONO_TYPE_BOOLEAN:
2363         case MONO_TYPE_I2:
2364         case MONO_TYPE_U2:
2365         case MONO_TYPE_CHAR:
2366         case MONO_TYPE_I4:
2367         case MONO_TYPE_U4:
2368                 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
2369                         return 1;
2370                 return 0;
2371         case MONO_TYPE_PTR:
2372                 /* STACK_MP is needed when setting pinned locals */
2373                 if (arg->type != STACK_I4 && arg->type != STACK_PTR && arg->type != STACK_MP)
2374                         return 1;
2375                 return 0;
2376         case MONO_TYPE_I:
2377         case MONO_TYPE_U:
2378         case MONO_TYPE_FNPTR:
2379                 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
2380                         return 1;
2381                 return 0;
2382         case MONO_TYPE_OBJECT:
2383                 if (arg->type != STACK_OBJ)
2384                         return 1;
2385                 return 0;
2386         case MONO_TYPE_STRING:
2387                 if (arg->type != STACK_OBJ)
2388                         return 1;
2389                 /* ldnull has arg->klass unset */
2390                 /*if (arg->klass && arg->klass != mono_defaults.string_class) {
2391                         G_BREAKPOINT ();
2392                         return 1;
2393                 }*/
2394                 return 0;
2395         case MONO_TYPE_CLASS:
2396         case MONO_TYPE_SZARRAY:
2397         case MONO_TYPE_ARRAY:    
2398                 if (arg->type != STACK_OBJ)
2399                         return 1;
2400                 /* FIXME: check type compatibility */
2401                 return 0;
2402         case MONO_TYPE_I8:
2403         case MONO_TYPE_U8:
2404                 if (arg->type != STACK_I8)
2405                         return 1;
2406                 return 0;
2407         case MONO_TYPE_R4:
2408         case MONO_TYPE_R8:
2409                 if (arg->type != STACK_R8)
2410                         return 1;
2411                 return 0;
2412         case MONO_TYPE_VALUETYPE:
2413                 if (arg->type != STACK_VTYPE)
2414                         return 1;
2415                 klass = mono_class_from_mono_type (simple_type);
2416                 if (klass != arg->klass)
2417                         return 1;
2418                 return 0;
2419         case MONO_TYPE_TYPEDBYREF:
2420                 if (arg->type != STACK_VTYPE)
2421                         return 1;
2422                 klass = mono_class_from_mono_type (simple_type);
2423                 if (klass != arg->klass)
2424                         return 1;
2425                 return 0;
2426         case MONO_TYPE_GENERICINST:
2427                 if (mono_type_generic_inst_is_valuetype (simple_type)) {
2428                         klass = mono_class_from_mono_type (simple_type);
2429                         if (klass->enumtype)
2430                                 return target_type_is_incompatible (cfg, klass->enum_basetype, arg);
2431                         if (arg->type != STACK_VTYPE)
2432                                 return 1;
2433                         if (klass != arg->klass)
2434                                 return 1;
2435                         return 0;
2436                 } else {
2437                         if (arg->type != STACK_OBJ)
2438                                 return 1;
2439                         /* FIXME: check type compatibility */
2440                         return 0;
2441                 }
2442         case MONO_TYPE_VAR:
2443         case MONO_TYPE_MVAR:
2444                 /* FIXME: all the arguments must be references for now,
2445                  * later look inside cfg and see if the arg num is
2446                  * really a reference
2447                  */
2448                 g_assert (cfg->generic_sharing_context);
2449                 if (arg->type != STACK_OBJ)
2450                         return 1;
2451                 return 0;
2452         default:
2453                 g_error ("unknown type 0x%02x in target_type_is_incompatible", simple_type->type);
2454         }
2455         return 1;
2456 }
2457
2458 /*
2459  * Prepare arguments for passing to a function call.
2460  * Return a non-zero value if the arguments can't be passed to the given
2461  * signature.
2462  * The type checks are not yet complete and some conversions may need
2463  * casts on 32 or 64 bit architectures.
2464  *
2465  * FIXME: implement this using target_type_is_incompatible ()
2466  */
2467 static int
2468 check_call_signature (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args)
2469 {
2470         MonoType *simple_type;
2471         int i;
2472
2473         if (sig->hasthis) {
2474                 if (args [0]->type != STACK_OBJ && args [0]->type != STACK_MP && args [0]->type != STACK_PTR)
2475                         return 1;
2476                 args++;
2477         }
2478         for (i = 0; i < sig->param_count; ++i) {
2479                 if (sig->params [i]->byref) {
2480                         if (args [i]->type != STACK_MP && args [i]->type != STACK_PTR)
2481                                 return 1;
2482                         continue;
2483                 }
2484                 simple_type = sig->params [i];
2485                 simple_type = mini_get_basic_type_from_generic (cfg->generic_sharing_context, simple_type);
2486 handle_enum:
2487                 switch (simple_type->type) {
2488                 case MONO_TYPE_VOID:
2489                         return 1;
2490                         continue;
2491                 case MONO_TYPE_I1:
2492                 case MONO_TYPE_U1:
2493                 case MONO_TYPE_BOOLEAN:
2494                 case MONO_TYPE_I2:
2495                 case MONO_TYPE_U2:
2496                 case MONO_TYPE_CHAR:
2497                 case MONO_TYPE_I4:
2498                 case MONO_TYPE_U4:
2499                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR)
2500                                 return 1;
2501                         continue;
2502                 case MONO_TYPE_I:
2503                 case MONO_TYPE_U:
2504                 case MONO_TYPE_PTR:
2505                 case MONO_TYPE_FNPTR:
2506                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR && args [i]->type != STACK_MP && args [i]->type != STACK_OBJ)
2507                                 return 1;
2508                         continue;
2509                 case MONO_TYPE_CLASS:
2510                 case MONO_TYPE_STRING:
2511                 case MONO_TYPE_OBJECT:
2512                 case MONO_TYPE_SZARRAY:
2513                 case MONO_TYPE_ARRAY:    
2514                         if (args [i]->type != STACK_OBJ)
2515                                 return 1;
2516                         continue;
2517                 case MONO_TYPE_I8:
2518                 case MONO_TYPE_U8:
2519                         if (args [i]->type != STACK_I8)
2520                                 return 1;
2521                         continue;
2522                 case MONO_TYPE_R4:
2523                 case MONO_TYPE_R8:
2524                         if (args [i]->type != STACK_R8)
2525                                 return 1;
2526                         continue;
2527                 case MONO_TYPE_VALUETYPE:
2528                         if (simple_type->data.klass->enumtype) {
2529                                 simple_type = simple_type->data.klass->enum_basetype;
2530                                 goto handle_enum;
2531                         }
2532                         if (args [i]->type != STACK_VTYPE)
2533                                 return 1;
2534                         continue;
2535                 case MONO_TYPE_TYPEDBYREF:
2536                         if (args [i]->type != STACK_VTYPE)
2537                                 return 1;
2538                         continue;
2539                 case MONO_TYPE_GENERICINST:
2540                         simple_type = &simple_type->data.generic_class->container_class->byval_arg;
2541                         goto handle_enum;
2542
2543                 default:
2544                         g_error ("unknown type 0x%02x in check_call_signature",
2545                                  simple_type->type);
2546                 }
2547         }
2548         return 0;
2549 }
2550
2551 inline static int
2552 mono_spill_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoCallInst *call, MonoMethodSignature *sig, gboolean ret_object, 
2553                  const guint8 *ip, gboolean to_end)
2554 {
2555         MonoInst *temp, *store, *ins = (MonoInst*)call;
2556         MonoType *ret = sig->ret;
2557
2558         if (!MONO_TYPE_IS_VOID (ret) || ret_object) {
2559                 if (ret_object) {
2560                         call->inst.type = STACK_OBJ;
2561                         call->inst.opcode = OP_CALL;
2562                         temp = mono_compile_create_var (cfg, &mono_defaults.string_class->byval_arg, OP_LOCAL);
2563                 } else {
2564                         type_to_eval_stack_type (cfg, ret, ins);
2565                         temp = mono_compile_create_var (cfg, ret, OP_LOCAL);
2566                 }
2567                 
2568                 temp->flags |= MONO_INST_IS_TEMP;
2569
2570                 if (MONO_TYPE_ISSTRUCT (ret)) {
2571                         MonoInst *loada, *dummy_store;
2572
2573                         /* 
2574                          * Emit a dummy store to the local holding the result so the
2575                          * liveness info remains correct.
2576                          */
2577                         NEW_DUMMY_STORE (cfg, dummy_store, temp->inst_c0);
2578                         if (to_end)
2579                                 mono_add_ins_to_end (bblock, dummy_store);
2580                         else
2581                                 MONO_ADD_INS (bblock, dummy_store);
2582
2583                         /* we use this to allocate native sized structs */
2584                         temp->backend.is_pinvoke = sig->pinvoke;
2585
2586                         NEW_TEMPLOADA (cfg, loada, temp->inst_c0);
2587                         if (call->inst.opcode == OP_VCALL)
2588                                 ins->inst_left = loada;
2589                         else
2590                                 ins->inst_right = loada; /* a virtual or indirect call */
2591
2592                         if (to_end)
2593                                 mono_add_ins_to_end (bblock, ins);
2594                         else
2595                                 MONO_ADD_INS (bblock, ins);
2596                 } else {
2597                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2598                         store->cil_code = ip;
2599                         
2600 #ifdef MONO_ARCH_SOFT_FLOAT
2601                         if (store->opcode == CEE_STIND_R4) {
2602                                 /*FIXME implement proper support for to_end*/
2603                                 g_assert (!to_end);
2604                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
2605                                 handle_store_float (cfg, bblock, store, ins, ip);
2606                         } else
2607 #endif
2608                         if (to_end)
2609                                 mono_add_ins_to_end (bblock, store);
2610                         else
2611                                 MONO_ADD_INS (bblock, store);
2612                 }
2613                 return temp->inst_c0;
2614         } else {
2615                 if (to_end)
2616                         mono_add_ins_to_end (bblock, ins);
2617                 else
2618                         MONO_ADD_INS (bblock, ins);
2619                 return -1;
2620         }
2621 }
2622
2623 inline static MonoCallInst *
2624 mono_emit_call_args (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, 
2625                      MonoInst **args, int calli, int virtual, const guint8 *ip, gboolean to_end)
2626 {
2627         MonoCallInst *call;
2628         MonoInst *arg, *n;
2629
2630         MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (sig->ret, calli, virtual, cfg->generic_sharing_context));
2631
2632 #ifdef MONO_ARCH_SOFT_FLOAT
2633         /* we need to convert the r4 value to an int value */
2634         {
2635                 int i;
2636                 for (i = 0; i < sig->param_count; ++i) {
2637                         if (!sig->params [i]->byref && sig->params [i]->type == MONO_TYPE_R4) {
2638                                 MonoInst *iargs [1];
2639                                 int temp;
2640                                 iargs [0] = args [i + sig->hasthis];
2641
2642                                 temp = mono_emit_jit_icall (cfg, bblock, mono_fload_r4_arg, iargs, ip);
2643                                 NEW_TEMPLOAD (cfg, arg, temp);
2644                                 args [i + sig->hasthis] = arg;
2645                         }
2646                 }
2647         }
2648 #endif
2649
2650         call->inst.cil_code = ip;
2651         call->args = args;
2652         call->signature = sig;
2653         call = mono_arch_call_opcode (cfg, bblock, call, virtual);
2654         type_to_eval_stack_type (cfg, sig->ret, &call->inst);
2655
2656         MONO_INST_LIST_FOR_EACH_ENTRY_SAFE (arg, n, &call->out_args, node) {
2657                 if (!arg->cil_code)
2658                         arg->cil_code = ip;
2659                 if (to_end)
2660                         mono_add_ins_to_end (bblock, arg);
2661                 else
2662                         MONO_ADD_INS (bblock, arg);
2663         }
2664         return call;
2665 }
2666
2667 inline static MonoCallInst*
2668 mono_emit_calli (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, 
2669                  MonoInst **args, MonoInst *addr, const guint8 *ip)
2670 {
2671         MonoCallInst *call = mono_emit_call_args (cfg, bblock, sig, args, TRUE, FALSE, ip, FALSE);
2672
2673         call->inst.inst_i0 = addr;
2674
2675         return call;
2676 }
2677
2678 inline static int
2679 mono_emit_calli_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, 
2680                                                  MonoInst **args, MonoInst *addr, const guint8 *ip)
2681 {
2682         MonoCallInst *call = mono_emit_calli (cfg, bblock, sig, args, addr, ip);
2683
2684         return mono_spill_call (cfg, bblock, call, sig, FALSE, ip, FALSE);
2685 }
2686
2687 static MonoCallInst*
2688 mono_emit_method_call_full (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method, MonoMethodSignature *sig,
2689                        MonoInst **args, const guint8 *ip, MonoInst *this, gboolean to_end)
2690 {
2691         gboolean virtual = this != NULL;
2692         MonoCallInst *call;
2693
2694         call = mono_emit_call_args (cfg, bblock, sig, args, FALSE, virtual, ip, to_end);
2695
2696         if (this && sig->hasthis && 
2697             (method->klass->marshalbyref || method->klass == mono_defaults.object_class) && 
2698             !(method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !MONO_CHECK_THIS (this)) {
2699                 call->method = mono_marshal_get_remoting_invoke_with_check (method);
2700         } else {
2701                 call->method = method;
2702         }
2703         call->inst.flags |= MONO_INST_HAS_METHOD;
2704         call->inst.inst_left = this;
2705
2706         if (call->method->klass->flags & TYPE_ATTRIBUTE_INTERFACE)
2707                 /* Needed by the code generated in inssel.brg */
2708                 mono_get_got_var (cfg);
2709
2710         return call;
2711 }
2712
2713 static MonoCallInst*
2714 mono_emit_method_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method, MonoMethodSignature *sig,
2715                        MonoInst **args, const guint8 *ip, MonoInst *this)
2716 {
2717         return mono_emit_method_call_full (cfg, bblock, method, sig, args, ip, this, FALSE);
2718 }
2719
2720 inline static int
2721 mono_emit_method_call_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,  
2722                        MonoMethodSignature *signature, MonoInst **args, const guint8 *ip, MonoInst *this)
2723 {
2724         MonoCallInst *call = mono_emit_method_call (cfg, bblock, method, signature, args, ip, this);
2725
2726         return mono_spill_call (cfg, bblock, call, signature, method->string_ctor, ip, FALSE);
2727 }
2728
2729 inline static int
2730 mono_emit_method_call_spilled_full (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,  
2731                        MonoMethodSignature *signature, MonoInst **args, const guint8 *ip, MonoInst *this,
2732                        gboolean ret_object, gboolean to_end)
2733 {
2734         MonoCallInst *call = mono_emit_method_call_full (cfg, bblock, method, signature, args, ip, this, to_end);
2735
2736         return mono_spill_call (cfg, bblock, call, signature, ret_object, ip, to_end);
2737 }
2738
2739 inline static int
2740 mono_emit_native_call (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoMethodSignature *sig,
2741                        MonoInst **args, const guint8 *ip, gboolean ret_object, gboolean to_end)
2742 {
2743         MonoCallInst *call;
2744
2745         g_assert (sig);
2746
2747         call = mono_emit_call_args (cfg, bblock, sig, args, FALSE, FALSE, ip, to_end);
2748         call->fptr = func;
2749
2750         return mono_spill_call (cfg, bblock, call, sig, ret_object, ip, to_end);
2751 }
2752
2753 inline static int
2754 mono_emit_jit_icall (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoInst **args, const guint8 *ip)
2755 {
2756         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (func);
2757         
2758         if (!info) {
2759                 g_warning ("unregistered JIT ICall");
2760                 g_assert_not_reached ();
2761         }
2762
2763         return mono_emit_native_call (cfg, bblock, mono_icall_get_wrapper (info), info->sig, args, ip, FALSE, FALSE);
2764 }
2765
2766 static void
2767 mono_emulate_opcode (MonoCompile *cfg, MonoInst *tree, MonoInst **iargs, MonoJitICallInfo *info)
2768 {
2769         MonoInst *ins, *temp = NULL, *store, *load;
2770         MonoInstList *head, *list;
2771         int nargs;
2772         MonoCallInst *call;
2773
2774         //g_print ("emulating: ");
2775         //mono_print_tree_nl (tree);
2776         MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (info->sig->ret, FALSE, FALSE, cfg->generic_sharing_context));
2777         ins = (MonoInst*)call;
2778         MONO_INST_LIST_INIT (&ins->node);
2779         
2780         call->inst.cil_code = tree->cil_code;
2781         call->args = iargs;
2782         call->signature = info->sig;
2783
2784         call = mono_arch_call_opcode (cfg, cfg->cbb, call, FALSE);
2785
2786         if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
2787                 temp = mono_compile_create_var (cfg, info->sig->ret, OP_LOCAL);
2788                 temp->flags |= MONO_INST_IS_TEMP;
2789                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2790                 MONO_INST_LIST_INIT (&store->node);
2791                 /* FIXME: handle CEE_STIND_R4 */
2792                 store->cil_code = tree->cil_code;
2793         } else {
2794                 store = ins;
2795         }
2796
2797         nargs = info->sig->param_count + info->sig->hasthis;
2798
2799         if (nargs) {
2800                 MONO_INST_LIST_ADD_TAIL (&store->node,
2801                                         &call->out_args);
2802                 list = &call->out_args;
2803         } else {
2804                 list = &store->node;
2805         }
2806
2807         if (cfg->prev_ins) {
2808                 /* 
2809                  * This assumes that that in a tree, emulate_opcode is called for a
2810                  * node before it is called for its children. dec_foreach needs to
2811                  * take this into account.
2812                  */
2813                 head = &cfg->prev_ins->node;
2814         } else {
2815                 head = &cfg->cbb->ins_list;
2816         }
2817
2818         MONO_INST_LIST_SPLICE_INIT (list, head);
2819
2820         call->fptr = mono_icall_get_wrapper (info);
2821
2822         if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
2823                 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
2824                 *tree = *load;
2825         }
2826 }
2827
2828 /*
2829  * This entry point could be used later for arbitrary method
2830  * redirection.
2831  */
2832 inline static int
2833 mini_redirect_call (int *temp, MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,  
2834                        MonoMethodSignature *signature, MonoInst **args, const guint8 *ip, MonoInst *this)
2835 {
2836
2837         if (method->klass == mono_defaults.string_class) {
2838                 /* managed string allocation support */
2839                 if (strcmp (method->name, "InternalAllocateStr") == 0) {
2840                         MonoInst *iargs [2];
2841                         MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
2842                         MonoMethod *managed_alloc = mono_gc_get_managed_allocator (vtable, FALSE);
2843                         if (!managed_alloc)
2844                                 return FALSE;
2845                         NEW_VTABLECONST (cfg, iargs [0], vtable);
2846                         iargs [1] = args [0];
2847                         *temp = mono_emit_method_call_spilled (cfg, bblock, managed_alloc, mono_method_signature (managed_alloc), iargs, ip, this);
2848                         return TRUE;
2849                 }
2850         }
2851         return FALSE;
2852 }
2853
2854 static MonoMethodSignature *
2855 mono_get_array_new_va_signature (int arity)
2856 {
2857         static GHashTable *sighash = NULL;
2858         MonoMethodSignature *res;
2859         int i;
2860
2861         mono_jit_lock ();
2862         if (!sighash) {
2863                 sighash = g_hash_table_new (NULL, NULL);
2864         }
2865         else if ((res = g_hash_table_lookup (sighash, GINT_TO_POINTER (arity)))) {
2866                 mono_jit_unlock ();
2867                 return res;
2868         }
2869
2870         res = mono_metadata_signature_alloc (mono_defaults.corlib, arity + 1);
2871
2872         res->pinvoke = 1;
2873 #ifdef MONO_ARCH_VARARG_ICALLS
2874         /* Only set this only some archs since not all backends can handle varargs+pinvoke */
2875         res->call_convention = MONO_CALL_VARARG;
2876 #endif
2877
2878 #ifdef PLATFORM_WIN32
2879         res->call_convention = MONO_CALL_C;
2880 #endif
2881
2882         res->params [0] = &mono_defaults.int_class->byval_arg;  
2883         for (i = 0; i < arity; i++)
2884                 res->params [i + 1] = &mono_defaults.int_class->byval_arg;
2885
2886         res->ret = &mono_defaults.int_class->byval_arg;
2887
2888         g_hash_table_insert (sighash, GINT_TO_POINTER (arity), res);
2889         mono_jit_unlock ();
2890
2891         return res;
2892 }
2893
2894 #ifdef MONO_ARCH_SOFT_FLOAT
2895 static void
2896 handle_store_float (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ptr, MonoInst *val, const unsigned char *ip)
2897 {
2898         MonoInst *iargs [2];
2899         iargs [0] = val;
2900         iargs [1] = ptr;
2901
2902         mono_emit_jit_icall (cfg, bblock, mono_fstore_r4, iargs, ip);
2903 }
2904
2905 static int
2906 handle_load_float (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ptr, const unsigned char *ip)
2907 {
2908         MonoInst *iargs [1];
2909         iargs [0] = ptr;
2910
2911         return mono_emit_jit_icall (cfg, bblock, mono_fload_r4, iargs, ip);
2912 }
2913
2914 #define LDLOC_SOFT_FLOAT(cfg,ins,idx,ip) do {\
2915                 if (header->locals [(idx)]->type == MONO_TYPE_R4 && !header->locals [(idx)]->byref) {   \
2916                         int temp;       \
2917                         NEW_LOCLOADA (cfg, (ins), (idx));       \
2918                         temp = handle_load_float (cfg, bblock, (ins), (ip));    \
2919                         NEW_TEMPLOAD (cfg, (ins), temp);        \
2920                 }       \
2921         } while (0)
2922 #define STLOC_SOFT_FLOAT(cfg,ins,idx,ip) do {\
2923                 if (header->locals [(idx)]->type == MONO_TYPE_R4 && !header->locals [(idx)]->byref) {   \
2924                         int temp;       \
2925                         NEW_LOCLOADA (cfg, (ins), (idx));       \
2926                         handle_store_float (cfg, bblock, (ins), *sp, (ip));     \
2927                         MONO_INST_NEW (cfg, (ins), OP_NOP);     \
2928                 }       \
2929         } while (0)
2930 #define LDARG_SOFT_FLOAT(cfg,ins,idx,ip) do {\
2931                 if (param_types [(idx)]->type == MONO_TYPE_R4 && !param_types [(idx)]->byref) { \
2932                         int temp;       \
2933                         NEW_ARGLOADA (cfg, (ins), (idx));       \
2934                         temp = handle_load_float (cfg, bblock, (ins), (ip));    \
2935                         NEW_TEMPLOAD (cfg, (ins), temp);        \
2936                 }       \
2937         } while (0)
2938 #define STARG_SOFT_FLOAT(cfg,ins,idx,ip) do {\
2939                 if (param_types [(idx)]->type == MONO_TYPE_R4 && !param_types [(idx)]->byref) { \
2940                         int temp;       \
2941                         NEW_ARGLOADA (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 #else
2947 #define LDLOC_SOFT_FLOAT(cfg,ins,idx,ip)
2948 #define STLOC_SOFT_FLOAT(cfg,ins,idx,ip)
2949 #define LDARG_SOFT_FLOAT(cfg,ins,idx,ip)
2950 #define STARG_SOFT_FLOAT(cfg,ins,idx,ip)
2951 #endif
2952
2953 static MonoMethod*
2954 get_memcpy_method (void)
2955 {
2956         static MonoMethod *memcpy_method = NULL;
2957         if (!memcpy_method) {
2958                 memcpy_method = mono_class_get_method_from_name (mono_defaults.string_class, "memcpy", 3);
2959                 if (!memcpy_method)
2960                         g_error ("Old corlib found. Install a new one");
2961         }
2962         return memcpy_method;
2963 }
2964
2965 static void
2966 handle_stobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, MonoInst *src, const unsigned char *ip, MonoClass *klass, gboolean to_end, gboolean native, gboolean write_barrier) {
2967         MonoInst *iargs [3];
2968         int n;
2969         guint32 align = 0;
2970         MonoMethod *memcpy_method;
2971
2972         g_assert (klass);
2973         /*
2974          * This check breaks with spilled vars... need to handle it during verification anyway.
2975          * g_assert (klass && klass == src->klass && klass == dest->klass);
2976          */
2977
2978         if (native)
2979                 n = mono_class_native_size (klass, &align);
2980         else
2981                 n = mono_class_value_size (klass, &align);
2982
2983 #if HAVE_WRITE_BARRIERS
2984         /* if native is true there should be no references in the struct */
2985         if (write_barrier && klass->has_references && !native) {
2986                 iargs [0] = dest;
2987                 iargs [1] = src;
2988                 NEW_PCONST (cfg, iargs [2], klass);
2989
2990                 mono_emit_jit_icall (cfg, bblock, mono_value_copy, iargs, ip);
2991                 return;
2992         }
2993 #endif
2994
2995         /* FIXME: add write barrier handling */
2996         if ((cfg->opt & MONO_OPT_INTRINS) && !to_end && n <= sizeof (gpointer) * 5) {
2997                 MonoInst *inst;
2998                 if (dest->opcode == OP_LDADDR) {
2999                         /* Keep liveness info correct */
3000                         NEW_DUMMY_STORE (cfg, inst, dest->inst_i0->inst_c0);
3001                         MONO_ADD_INS (bblock, inst);
3002                 }
3003                 NEW_MEMCPY (cfg, inst, dest, src, n, align);
3004                 MONO_ADD_INS (bblock, inst);
3005                 return;
3006         }
3007         iargs [0] = dest;
3008         iargs [1] = src;
3009         NEW_ICONST (cfg, iargs [2], n);
3010
3011         memcpy_method = get_memcpy_method ();
3012         mono_emit_method_call_spilled_full (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL, FALSE, to_end);
3013 }
3014
3015 static MonoMethod*
3016 get_memset_method (void)
3017 {
3018         static MonoMethod *memset_method = NULL;
3019         if (!memset_method) {
3020                 memset_method = mono_class_get_method_from_name (mono_defaults.string_class, "memset", 3);
3021                 if (!memset_method)
3022                         g_error ("Old corlib found. Install a new one");
3023         }
3024         return memset_method;
3025 }
3026
3027 static void
3028 handle_initobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, const guchar *ip, MonoClass *klass, MonoInst **stack_start, MonoInst **sp)
3029 {
3030         MonoInst *iargs [3];
3031         MonoInst *ins, *zero_int32;
3032         int n;
3033         guint32 align;
3034         MonoMethod *memset_method;
3035
3036         NEW_ICONST (cfg, zero_int32, 0);
3037
3038         mono_class_init (klass);
3039         n = mono_class_value_size (klass, &align);
3040         MONO_INST_NEW (cfg, ins, 0);
3041         ins->cil_code = ip;
3042         ins->inst_left = dest;
3043         ins->inst_right = zero_int32;
3044         if (n == 1) {
3045                 ins->opcode = CEE_STIND_I1;
3046                 MONO_ADD_INS (bblock, ins);
3047         } else if ((n == 2) && (align >= 2)) {
3048                 ins->opcode = CEE_STIND_I2;
3049                 MONO_ADD_INS (bblock, ins);
3050         } else if ((n == 2) && (align >= 4)) {
3051                 ins->opcode = CEE_STIND_I4;
3052                 MONO_ADD_INS (bblock, ins);
3053         } else if (n <= sizeof (gpointer) * 5) {
3054                 NEW_MEMSET (cfg, ins, dest, 0, n, align);
3055                 MONO_ADD_INS (bblock, ins);
3056         } else {
3057                 memset_method = get_memset_method ();
3058                 handle_loaded_temps (cfg, bblock, stack_start, sp);
3059                 iargs [0] = dest;
3060                 NEW_ICONST (cfg, iargs [1], 0);
3061                 NEW_ICONST (cfg, iargs [2], n);
3062                 mono_emit_method_call_spilled (cfg, bblock, memset_method, memset_method->signature, iargs, ip, NULL);
3063         }
3064 }
3065
3066 static int
3067 handle_alloc (MonoCompile *cfg, MonoBasicBlock *bblock, MonoClass *klass, gboolean for_box, const guchar *ip)
3068 {
3069         MonoInst *iargs [2];
3070         void *alloc_ftn;
3071
3072         if (cfg->opt & MONO_OPT_SHARED) {
3073                 NEW_DOMAINCONST (cfg, iargs [0]);
3074                 NEW_CLASSCONST (cfg, iargs [1], klass);
3075
3076                 alloc_ftn = mono_object_new;
3077         } else if (cfg->compile_aot && bblock->out_of_line && klass->type_token && klass->image == mono_defaults.corlib) {
3078                 /* This happens often in argument checking code, eg. throw new FooException... */
3079                 /* Avoid relocations by calling a helper function specialized to mscorlib */
3080                 NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (klass->type_token));
3081                 return mono_emit_jit_icall (cfg, bblock, mono_helper_newobj_mscorlib, iargs, ip);
3082         } else {
3083                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
3084                 MonoMethod *managed_alloc = mono_gc_get_managed_allocator (vtable, for_box);
3085                 gboolean pass_lw;
3086
3087                 if (managed_alloc) {
3088                         NEW_VTABLECONST (cfg, iargs [0], vtable);
3089                         return mono_emit_method_call_spilled (cfg, bblock, managed_alloc, mono_method_signature (managed_alloc), iargs, ip, NULL);
3090                 }
3091                 alloc_ftn = mono_class_get_allocation_ftn (vtable, for_box, &pass_lw);
3092                 if (pass_lw) {
3093                         guint32 lw = vtable->klass->instance_size;
3094                         lw = ((lw + (sizeof (gpointer) - 1)) & ~(sizeof (gpointer) - 1)) / sizeof (gpointer);
3095                         NEW_ICONST (cfg, iargs [0], lw);
3096                         NEW_VTABLECONST (cfg, iargs [1], vtable);
3097                 }
3098                 else
3099                         NEW_VTABLECONST (cfg, iargs [0], vtable);
3100         }
3101
3102         return mono_emit_jit_icall (cfg, bblock, alloc_ftn, iargs, ip);
3103 }
3104
3105 /**
3106  * Handles unbox of a Nullable<T>, returning a temp variable
3107  * where the result is stored
3108  */
3109 static int
3110 handle_unbox_nullable (MonoCompile* cfg, MonoBasicBlock* bblock, MonoInst* val, const guchar *ip, MonoClass* klass)
3111 {
3112        MonoMethod* method = mono_class_get_method_from_name (klass, "Unbox", 1);
3113        return mono_emit_method_call_spilled (cfg, bblock, method, mono_method_signature (method), &val, ip, NULL);
3114         
3115 }
3116
3117
3118
3119 static MonoInst *
3120 handle_box (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *val, const guchar *ip, MonoClass *klass)
3121 {
3122         MonoInst *dest, *vtoffset, *add, *vstore;
3123         int temp;
3124
3125        if (mono_class_is_nullable (klass)) {
3126                MonoMethod* method = mono_class_get_method_from_name (klass, "Box", 1);
3127                temp = mono_emit_method_call_spilled (cfg, bblock, method, mono_method_signature (method), &val, ip, NULL);
3128                NEW_TEMPLOAD (cfg, dest, temp);
3129                return dest;
3130        }
3131
3132
3133         temp = handle_alloc (cfg, bblock, klass, TRUE, ip);
3134         NEW_TEMPLOAD (cfg, dest, temp);
3135         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
3136         MONO_INST_NEW (cfg, add, OP_PADD);
3137         add->inst_left = dest;
3138         add->inst_right = vtoffset;
3139         add->cil_code = ip;
3140         add->klass = klass;
3141         MONO_INST_NEW (cfg, vstore, CEE_STIND_I);
3142         vstore->opcode = mini_type_to_stind (cfg, &klass->byval_arg);
3143         vstore->cil_code = ip;
3144         vstore->inst_left = add;
3145         vstore->inst_right = val;
3146
3147 #ifdef MONO_ARCH_SOFT_FLOAT
3148         if (vstore->opcode == CEE_STIND_R4) {
3149                 handle_store_float (cfg, bblock, add, val, ip);
3150         } else
3151 #endif
3152         if (vstore->opcode == CEE_STOBJ) {
3153                 handle_stobj (cfg, bblock, add, val, ip, klass, FALSE, FALSE, TRUE);
3154         } else
3155                 MONO_ADD_INS (bblock, vstore);
3156
3157         NEW_TEMPLOAD (cfg, dest, temp);
3158         return dest;
3159 }
3160
3161 static MonoInst*
3162 handle_delegate_ctor (MonoCompile *cfg, MonoBasicBlock *bblock, MonoClass *klass, MonoInst *target, MonoMethod *method, unsigned char *ip)
3163 {
3164         gpointer *trampoline;
3165         MonoInst *obj, *ins, *store, *offset_ins, *method_ins, *tramp_ins;
3166         int temp;
3167
3168         temp = handle_alloc (cfg, bblock, klass, FALSE, ip);
3169
3170         /* Inline the contents of mono_delegate_ctor */
3171
3172         /* Set target field */
3173         /* Optimize away setting of NULL target */
3174         if (!(target->opcode == OP_PCONST && target->inst_p0 == 0)) {
3175                 NEW_TEMPLOAD (cfg, obj, temp);
3176                 NEW_ICONST (cfg, offset_ins, G_STRUCT_OFFSET (MonoDelegate, target));
3177                 MONO_INST_NEW (cfg, ins, OP_PADD);
3178                 ins->cil_code = ip;
3179                 ins->inst_left = obj;
3180                 ins->inst_right = offset_ins;
3181
3182                 MONO_INST_NEW (cfg, store, CEE_STIND_REF);
3183                 store->cil_code = ip;
3184                 store->inst_left = ins;
3185                 store->inst_right = target;
3186                 mono_bblock_add_inst (bblock, store);
3187         }
3188
3189         /* Set method field */
3190         NEW_TEMPLOAD (cfg, obj, temp);
3191         NEW_ICONST (cfg, offset_ins, G_STRUCT_OFFSET (MonoDelegate, method));
3192         MONO_INST_NEW (cfg, ins, OP_PADD);
3193         ins->cil_code = ip;
3194         ins->inst_left = obj;
3195         ins->inst_right = offset_ins;
3196
3197         NEW_METHODCONST (cfg, method_ins, method);
3198
3199         MONO_INST_NEW (cfg, store, CEE_STIND_I);
3200         store->cil_code = ip;
3201         store->inst_left = ins;
3202         store->inst_right = method_ins;
3203         mono_bblock_add_inst (bblock, store);
3204
3205         /* Set invoke_impl field */
3206         NEW_TEMPLOAD (cfg, obj, temp);
3207         NEW_ICONST (cfg, offset_ins, G_STRUCT_OFFSET (MonoDelegate, invoke_impl));
3208         MONO_INST_NEW (cfg, ins, OP_PADD);
3209         ins->cil_code = ip;
3210         ins->inst_left = obj;
3211         ins->inst_right = offset_ins;
3212
3213         trampoline = mono_create_delegate_trampoline (klass);
3214         NEW_AOTCONST (cfg, tramp_ins, MONO_PATCH_INFO_ABS, trampoline);
3215
3216         MONO_INST_NEW (cfg, store, CEE_STIND_I);
3217         store->cil_code = ip;
3218         store->inst_left = ins;
3219         store->inst_right = tramp_ins;
3220         mono_bblock_add_inst (bblock, store);
3221
3222         /* All the checks which are in mono_delegate_ctor () are done by the delegate trampoline */
3223
3224         NEW_TEMPLOAD (cfg, obj, temp);
3225
3226         return obj;
3227 }
3228
3229 static int
3230 handle_array_new (MonoCompile *cfg, MonoBasicBlock *bblock, int rank, MonoInst **sp, unsigned char *ip)
3231 {
3232         MonoMethodSignature *esig;
3233         char icall_name [256];
3234         char *name;
3235         MonoJitICallInfo *info;
3236
3237         /* Need to register the icall so it gets an icall wrapper */
3238         sprintf (icall_name, "ves_array_new_va_%d", rank);
3239
3240         mono_jit_lock ();
3241         info = mono_find_jit_icall_by_name (icall_name);
3242         if (info == NULL) {
3243                 esig = mono_get_array_new_va_signature (rank);
3244                 name = g_strdup (icall_name);
3245                 info = mono_register_jit_icall (mono_array_new_va, name, esig, FALSE);
3246
3247                 g_hash_table_insert (jit_icall_name_hash, name, name);
3248         }
3249         mono_jit_unlock ();
3250
3251         cfg->flags |= MONO_CFG_HAS_VARARGS;
3252
3253         /* FIXME: This uses info->sig, but it should use the signature of the wrapper */
3254         return mono_emit_native_call (cfg, bblock, mono_icall_get_wrapper (info), info->sig, sp, ip, TRUE, FALSE);
3255 }
3256
3257 static void
3258 mono_emit_load_got_addr (MonoCompile *cfg)
3259 {
3260         MonoInst *load, *store, *dummy_use;
3261         MonoInst *get_got;
3262
3263         if (!cfg->got_var || cfg->got_var_allocated)
3264                 return;
3265
3266         MONO_INST_NEW (cfg, get_got, OP_LOAD_GOTADDR);
3267         NEW_TEMPSTORE (cfg, store, cfg->got_var->inst_c0, get_got);
3268
3269         /* Add it to the start of the first bblock */
3270         MONO_INST_LIST_ADD (&store->node, &cfg->bb_entry->ins_list);
3271
3272         cfg->got_var_allocated = TRUE;
3273
3274         /* 
3275          * Add a dummy use to keep the got_var alive, since real uses might
3276          * only be generated in the decompose or instruction selection phases.
3277          * Add it to end_bblock, so the variable's lifetime covers the whole
3278          * method.
3279          */
3280         NEW_TEMPLOAD (cfg, load, cfg->got_var->inst_c0);
3281         NEW_DUMMY_USE (cfg, dummy_use, load);
3282         MONO_ADD_INS (cfg->bb_exit, dummy_use);
3283 }
3284
3285 #define CODE_IS_STLOC(ip) (((ip) [0] >= CEE_STLOC_0 && (ip) [0] <= CEE_STLOC_3) || ((ip) [0] == CEE_STLOC_S))
3286
3287 static gboolean
3288 mini_class_is_system_array (MonoClass *klass)
3289 {
3290         if (klass->parent == mono_defaults.array_class)
3291                 return TRUE;
3292         else
3293                 return FALSE;
3294 }
3295
3296 static gboolean
3297 mono_method_check_inlining (MonoCompile *cfg, MonoMethod *method)
3298 {
3299         MonoMethodHeader *header = mono_method_get_header (method);
3300         MonoMethodSignature *signature = mono_method_signature (method);
3301         MonoVTable *vtable;
3302         int i;
3303
3304         if (cfg->generic_sharing_context)
3305                 return FALSE;
3306
3307 #ifdef MONO_ARCH_HAVE_LMF_OPS
3308         if (((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
3309                  (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) &&
3310             !MONO_TYPE_ISSTRUCT (signature->ret) && !mini_class_is_system_array (method->klass))
3311                 return TRUE;
3312 #endif
3313
3314         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3315             (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
3316             (method->iflags & METHOD_IMPL_ATTRIBUTE_NOINLINING) ||
3317             (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) ||
3318             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3319             (method->klass->marshalbyref) ||
3320             !header || header->num_clauses ||
3321             /* fixme: why cant we inline valuetype returns? */
3322             MONO_TYPE_ISSTRUCT (signature->ret))
3323                 return FALSE;
3324
3325 #ifdef MONO_ARCH_SOFT_FLOAT
3326         /* this complicates things, fix later */
3327         if (signature->ret->type == MONO_TYPE_R4)
3328                 return FALSE;
3329 #endif
3330         /* its not worth to inline methods with valuetype arguments?? */
3331         for (i = 0; i < signature->param_count; i++) {
3332                 if (MONO_TYPE_ISSTRUCT (signature->params [i])) {
3333                         return FALSE;
3334                 }
3335 #ifdef MONO_ARCH_SOFT_FLOAT
3336                 /* this complicates things, fix later */
3337                 if (!signature->params [i]->byref && signature->params [i]->type == MONO_TYPE_R4)
3338                         return FALSE;
3339 #endif
3340         }
3341
3342         /*
3343          * if we can initialize the class of the method right away, we do,
3344          * otherwise we don't allow inlining if the class needs initialization,
3345          * since it would mean inserting a call to mono_runtime_class_init()
3346          * inside the inlined code
3347          */
3348         if (!(cfg->opt & MONO_OPT_SHARED)) {
3349                 vtable = mono_class_vtable (cfg->domain, method->klass);
3350                 if (method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) {
3351                         if (cfg->run_cctors) {
3352                                 /* This makes so that inline cannot trigger */
3353                                 /* .cctors: too many apps depend on them */
3354                                 /* running with a specific order... */
3355                                 if (! vtable->initialized)
3356                                         return FALSE;
3357                                 mono_runtime_class_init (vtable);
3358                         }
3359                 }
3360                 else if (!vtable->initialized && mono_class_needs_cctor_run (method->klass, NULL))
3361                         return FALSE;
3362         } else {
3363                 /* 
3364                  * If we're compiling for shared code
3365                  * the cctor will need to be run at aot method load time, for example,
3366                  * or at the end of the compilation of the inlining method.
3367                  */
3368                 if (mono_class_needs_cctor_run (method->klass, NULL) && !((method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3369                         return FALSE;
3370         }
3371         //if (!MONO_TYPE_IS_VOID (signature->ret)) return FALSE;
3372
3373         /*
3374          * CAS - do not inline methods with declarative security
3375          * Note: this has to be before any possible return TRUE;
3376          */
3377         if (mono_method_has_declsec (method))
3378                 return FALSE;
3379
3380         /* also consider num_locals? */
3381         if (getenv ("MONO_INLINELIMIT")) {
3382                 if (header->code_size < atoi (getenv ("MONO_INLINELIMIT"))) {
3383                         return TRUE;
3384                 }
3385         } else if (header->code_size < INLINE_LENGTH_LIMIT)
3386                 return TRUE;
3387
3388         return FALSE;
3389 }
3390
3391 static gboolean
3392 mini_field_access_needs_cctor_run (MonoCompile *cfg, MonoMethod *method, MonoVTable *vtable)
3393 {
3394         if (vtable->initialized && !cfg->compile_aot)
3395                 return FALSE;
3396
3397         if (vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)
3398                 return FALSE;
3399
3400         if (!mono_class_needs_cctor_run (vtable->klass, method))
3401                 return FALSE;
3402
3403         if (! (method->flags & METHOD_ATTRIBUTE_STATIC) && (vtable->klass == method->klass))
3404                 /* The initialization is already done before the method is called */
3405                 return FALSE;
3406
3407         return TRUE;
3408 }
3409
3410 static MonoInst*
3411 mini_get_ldelema_ins (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *cmethod, MonoInst **sp, unsigned char *ip, gboolean is_set)
3412 {
3413         int temp, rank;
3414         MonoInst *addr;
3415         MonoMethod *addr_method;
3416         int element_size;
3417
3418         rank = mono_method_signature (cmethod)->param_count - (is_set? 1: 0);
3419
3420         if (rank == 1) {
3421                 MONO_INST_NEW (cfg, addr, CEE_LDELEMA);
3422                 addr->inst_left = sp [0];
3423                 addr->inst_right = sp [1];
3424                 addr->cil_code = ip;
3425                 addr->type = STACK_MP;
3426                 addr->klass = cmethod->klass->element_class;
3427                 return addr;
3428         }
3429
3430         if (rank == 2 && (cfg->opt & MONO_OPT_INTRINS)) {
3431 #if defined(MONO_ARCH_EMULATE_MUL_DIV) && !defined(MONO_ARCH_NO_EMULATE_MUL)
3432                 /* OP_LDELEMA2D depends on OP_LMUL */
3433 #else
3434                 MonoInst *indexes;
3435                 NEW_GROUP (cfg, indexes, sp [1], sp [2]);
3436                 MONO_INST_NEW (cfg, addr, OP_LDELEMA2D);
3437                 addr->inst_left = sp [0];
3438                 addr->inst_right = indexes;
3439                 addr->cil_code = ip;
3440                 addr->type = STACK_MP;
3441                 addr->klass = cmethod->klass->element_class;
3442                 return addr;
3443 #endif
3444         }
3445
3446         element_size = mono_class_array_element_size (cmethod->klass->element_class);
3447         addr_method = mono_marshal_get_array_address (rank, element_size);
3448         temp = mono_emit_method_call_spilled (cfg, bblock, addr_method, addr_method->signature, sp, ip, NULL);
3449         NEW_TEMPLOAD (cfg, addr, temp);
3450         return addr;
3451
3452 }
3453
3454 static MonoJitICallInfo **emul_opcode_map = NULL;
3455
3456 MonoJitICallInfo *
3457 mono_find_jit_opcode_emulation (int opcode)
3458 {
3459         g_assert (opcode >= 0 && opcode <= OP_LAST);
3460         if  (emul_opcode_map)
3461                 return emul_opcode_map [opcode];
3462         else
3463                 return NULL;
3464 }
3465
3466 static int
3467 is_unsigned_regsize_type (MonoType *type)
3468 {
3469         switch (type->type) {
3470         case MONO_TYPE_U1:
3471         case MONO_TYPE_U2:
3472         case MONO_TYPE_U4:
3473 #if SIZEOF_VOID_P == 8
3474         /*case MONO_TYPE_U8: this requires different opcodes in inssel.brg */
3475 #endif
3476                 return TRUE;
3477         default:
3478                 return FALSE;
3479         }
3480 }
3481
3482 static MonoInst*
3483 mini_get_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
3484 {
3485         MonoInst *ins = NULL;
3486         
3487         static MonoClass *runtime_helpers_class = NULL;
3488         if (! runtime_helpers_class)
3489                 runtime_helpers_class = mono_class_from_name (mono_defaults.corlib,
3490                         "System.Runtime.CompilerServices", "RuntimeHelpers");
3491
3492         if (cmethod->klass == mono_defaults.string_class) {
3493                 if (strcmp (cmethod->name, "get_Chars") == 0) {
3494                         MONO_INST_NEW (cfg, ins, OP_GETCHR);
3495                         ins->inst_i0 = args [0];
3496                         ins->inst_i1 = args [1];
3497                         return ins;
3498                 } else if (strcmp (cmethod->name, "get_Length") == 0) {
3499                         MONO_INST_NEW (cfg, ins, OP_STRLEN);
3500                         ins->inst_i0 = args [0];
3501                         return ins;
3502                 } else if (strcmp (cmethod->name, "InternalSetChar") == 0) {
3503                         MonoInst *get_addr;
3504                         MONO_INST_NEW (cfg, get_addr, OP_STR_CHAR_ADDR);
3505                         get_addr->inst_i0 = args [0];
3506                         get_addr->inst_i1 = args [1];
3507                         MONO_INST_NEW (cfg, ins, CEE_STIND_I2);
3508                         ins->inst_i0 = get_addr;
3509                         ins->inst_i1 = args [2];
3510                         return ins;
3511                 } else 
3512                         return NULL;
3513         } else if (cmethod->klass == mono_defaults.object_class) {
3514                 if (strcmp (cmethod->name, "GetType") == 0) {
3515                         MONO_INST_NEW (cfg, ins, OP_GETTYPE);
3516                         ins->inst_i0 = args [0];
3517                         return ins;
3518                 /* The OP_GETHASHCODE rule depends on OP_MUL */
3519 #if !defined(MONO_ARCH_EMULATE_MUL_DIV) && !defined(HAVE_MOVING_COLLECTOR)
3520                 } else if (strcmp (cmethod->name, "InternalGetHashCode") == 0) {
3521                         MONO_INST_NEW (cfg, ins, OP_GETHASHCODE);
3522                         ins->inst_i0 = args [0];
3523                         return ins;
3524 #endif
3525                 } else if (strcmp (cmethod->name, ".ctor") == 0) {
3526                         MONO_INST_NEW (cfg, ins, OP_NOP);
3527                         return ins;
3528                 } else
3529                         return NULL;
3530         } else if (cmethod->klass == mono_defaults.array_class) {
3531                 if (cmethod->name [0] != 'g')
3532                         return NULL;
3533
3534                 if (strcmp (cmethod->name, "get_Rank") == 0) {
3535                         MONO_INST_NEW (cfg, ins, OP_ARRAY_RANK);
3536                         ins->inst_i0 = args [0];
3537                         return ins;
3538                 } else if (strcmp (cmethod->name, "get_Length") == 0) {
3539                         MONO_INST_NEW (cfg, ins, CEE_LDLEN);
3540                         ins->inst_i0 = args [0];
3541                         return ins;
3542                 } else
3543                         return NULL;
3544         } else if (cmethod->klass == runtime_helpers_class) {
3545                 if (strcmp (cmethod->name, "get_OffsetToStringData") == 0) {
3546                         NEW_ICONST (cfg, ins, G_STRUCT_OFFSET (MonoString, chars));
3547                         return ins;
3548                 } else
3549                         return NULL;
3550         } else if (cmethod->klass == mono_defaults.thread_class) {
3551                 if (strcmp (cmethod->name, "get_CurrentThread") == 0 && (ins = mono_arch_get_thread_intrinsic (cfg)))
3552                         return ins;
3553                 if (strcmp (cmethod->name, "MemoryBarrier") == 0) {
3554                         MONO_INST_NEW (cfg, ins, OP_MEMORY_BARRIER);
3555                         return ins;
3556                 }
3557         } else if (mini_class_is_system_array (cmethod->klass) &&
3558                         strcmp (cmethod->name, "GetGenericValueImpl") == 0) {
3559                 MonoInst *sp [2];
3560                 MonoInst *ldelem, *store, *load;
3561                 MonoClass *eklass = mono_class_from_mono_type (fsig->params [1]);
3562                 int n;
3563                 n = mini_type_to_stind (cfg, &eklass->byval_arg);
3564                 if (n == CEE_STOBJ)
3565                         return NULL;
3566                 sp [0] = args [0];
3567                 sp [1] = args [1];
3568                 NEW_LDELEMA (cfg, ldelem, sp, eklass);
3569                 ldelem->flags |= MONO_INST_NORANGECHECK;
3570                 MONO_INST_NEW (cfg, store, n);
3571                 MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, &eklass->byval_arg));
3572                 type_to_eval_stack_type (cfg, &eklass->byval_arg, load);
3573                 load->inst_left = ldelem;
3574                 store->inst_left = args [2];
3575                 store->inst_right = load;
3576                 return store;
3577         } else if (cmethod->klass == mono_defaults.math_class) {
3578                 if (strcmp (cmethod->name, "Min") == 0) {
3579                         if (is_unsigned_regsize_type (fsig->params [0])) {
3580                                 MONO_INST_NEW (cfg, ins, OP_MIN);
3581                                 ins->inst_i0 = args [0];
3582                                 ins->inst_i1 = args [1];
3583                                 return ins;
3584                         }
3585                 } else if (strcmp (cmethod->name, "Max") == 0) {
3586                         if (is_unsigned_regsize_type (fsig->params [0])) {
3587                                 MONO_INST_NEW (cfg, ins, OP_MAX);
3588                                 ins->inst_i0 = args [0];
3589                                 ins->inst_i1 = args [1];
3590                                 return ins;
3591                         }
3592                 }
3593         } else if (cmethod->klass->image == mono_defaults.corlib &&
3594                            (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
3595                            (strcmp (cmethod->klass->name, "Interlocked") == 0)) {
3596                 ins = NULL;
3597
3598 #if SIZEOF_VOID_P == 8
3599                 if (strcmp (cmethod->name, "Read") == 0 && (fsig->params [0]->type == MONO_TYPE_I8)) {
3600                         /* 64 bit reads are already atomic */
3601                         MONO_INST_NEW (cfg, ins, CEE_LDIND_I8);
3602                         ins->inst_i0 = args [0];
3603                 }
3604 #endif
3605
3606 #ifdef MONO_ARCH_HAVE_ATOMIC_ADD
3607                 if (strcmp (cmethod->name, "Increment") == 0) {
3608                         MonoInst *ins_iconst;
3609                         guint32 opcode;
3610
3611                         if (fsig->params [0]->type == MONO_TYPE_I4)
3612                                 opcode = OP_ATOMIC_ADD_NEW_I4;
3613                         else if (fsig->params [0]->type == MONO_TYPE_I8)
3614                                 opcode = OP_ATOMIC_ADD_NEW_I8;
3615                         else
3616                                 g_assert_not_reached ();
3617
3618 #if SIZEOF_VOID_P == 4
3619                         if (opcode == OP_ATOMIC_ADD_NEW_I8)
3620                                 return NULL;
3621 #endif
3622
3623                         MONO_INST_NEW (cfg, ins, opcode);
3624                         MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
3625                         ins_iconst->inst_c0 = 1;
3626
3627                         ins->inst_i0 = args [0];
3628                         ins->inst_i1 = ins_iconst;
3629                 } else if (strcmp (cmethod->name, "Decrement") == 0) {
3630                         MonoInst *ins_iconst;
3631                         guint32 opcode;
3632
3633                         if (fsig->params [0]->type == MONO_TYPE_I4)
3634                                 opcode = OP_ATOMIC_ADD_NEW_I4;
3635                         else if (fsig->params [0]->type == MONO_TYPE_I8)
3636                                 opcode = OP_ATOMIC_ADD_NEW_I8;
3637                         else
3638                                 g_assert_not_reached ();
3639
3640 #if SIZEOF_VOID_P == 4
3641                         if (opcode == OP_ATOMIC_ADD_NEW_I8)
3642                                 return NULL;
3643 #endif
3644
3645                         MONO_INST_NEW (cfg, ins, opcode);
3646                         MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
3647                         ins_iconst->inst_c0 = -1;
3648
3649                         ins->inst_i0 = args [0];
3650                         ins->inst_i1 = ins_iconst;
3651                 } else if (strcmp (cmethod->name, "Add") == 0) {
3652                         guint32 opcode;
3653
3654                         if (fsig->params [0]->type == MONO_TYPE_I4)
3655                                 opcode = OP_ATOMIC_ADD_NEW_I4;
3656                         else if (fsig->params [0]->type == MONO_TYPE_I8)
3657                                 opcode = OP_ATOMIC_ADD_NEW_I8;
3658                         else
3659                                 g_assert_not_reached ();
3660
3661 #if SIZEOF_VOID_P == 4
3662                         if (opcode == OP_ATOMIC_ADD_NEW_I8)
3663                                 return NULL;
3664 #endif
3665                         
3666                         MONO_INST_NEW (cfg, ins, opcode);
3667
3668                         ins->inst_i0 = args [0];
3669                         ins->inst_i1 = args [1];
3670                 }
3671 #endif /* MONO_ARCH_HAVE_ATOMIC_ADD */
3672
3673 #ifdef MONO_ARCH_HAVE_ATOMIC_EXCHANGE
3674                 if (strcmp (cmethod->name, "Exchange") == 0) {
3675                         guint32 opcode;
3676
3677                         if (fsig->params [0]->type == MONO_TYPE_I4)
3678                                 opcode = OP_ATOMIC_EXCHANGE_I4;
3679 #if SIZEOF_VOID_P == 8
3680                         else if ((fsig->params [0]->type == MONO_TYPE_I8) ||
3681                                          (fsig->params [0]->type == MONO_TYPE_I) ||
3682                                          (fsig->params [0]->type == MONO_TYPE_OBJECT))
3683                                 opcode = OP_ATOMIC_EXCHANGE_I8;
3684 #else
3685                         else if ((fsig->params [0]->type == MONO_TYPE_I) ||
3686                                          (fsig->params [0]->type == MONO_TYPE_OBJECT))
3687                                 opcode = OP_ATOMIC_EXCHANGE_I4;
3688 #endif
3689                         else
3690                                 return NULL;
3691
3692 #if SIZEOF_VOID_P == 4
3693                         if (opcode == OP_ATOMIC_EXCHANGE_I8)
3694                                 return NULL;
3695 #endif
3696
3697                         MONO_INST_NEW (cfg, ins, opcode);
3698
3699                         ins->inst_i0 = args [0];
3700                         ins->inst_i1 = args [1];
3701                 }
3702 #endif /* MONO_ARCH_HAVE_ATOMIC_EXCHANGE */
3703
3704                 if (ins)
3705                         return ins;
3706         } else if (cmethod->klass->image == mono_defaults.corlib) {
3707                 if (cmethod->name [0] == 'B' && strcmp (cmethod->name, "Break") == 0
3708                                 && strcmp (cmethod->klass->name, "Debugger") == 0) {
3709                         MONO_INST_NEW (cfg, ins, OP_BREAK);
3710                         return ins;
3711                 }
3712                 if (cmethod->name [0] == 'g' && strcmp (cmethod->name, "get_IsRunningOnWindows") == 0
3713                                 && strcmp (cmethod->klass->name, "Environment") == 0) {
3714 #ifdef PLATFORM_WIN32
3715                         NEW_ICONST (cfg, ins, 1);
3716 #else
3717                         NEW_ICONST (cfg, ins, 0);
3718 #endif
3719                         return ins;
3720                 }
3721         }
3722
3723         return mono_arch_get_inst_for_method (cfg, cmethod, fsig, args);
3724 }
3725
3726 static void
3727 mono_save_args (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, MonoInst **sp, MonoInst **args)
3728 {
3729         MonoInst *store, *temp;
3730         int i;
3731
3732         g_assert (!MONO_TYPE_ISSTRUCT (sig->ret));
3733
3734         if (!sig->hasthis && sig->param_count == 0) 
3735                 return;
3736
3737         if (sig->hasthis) {
3738                 if (sp [0]->opcode == OP_ICONST) {
3739                         *args++ = sp [0];
3740                 } else {
3741                         temp = mono_compile_create_var (cfg, type_from_stack_type (*sp), OP_LOCAL);
3742                         *args++ = temp;
3743                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
3744                         /* FIXME: handle CEE_STIND_R4 */
3745                         store->cil_code = sp [0]->cil_code;
3746                         MONO_ADD_INS (bblock, store);
3747                 }
3748                 sp++;
3749         }
3750
3751         for (i = 0; i < sig->param_count; ++i) {
3752                 if (sp [0]->opcode == OP_ICONST) {
3753                         *args++ = sp [0];
3754                 } else {
3755                         temp = mono_compile_create_var (cfg, sig->params [i], OP_LOCAL);
3756                         *args++ = temp;
3757                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
3758                         store->cil_code = sp [0]->cil_code;
3759                         /* FIXME: handle CEE_STIND_R4 */
3760                         if (store->opcode == CEE_STOBJ) {
3761                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
3762                                 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, temp->klass, FALSE, FALSE, FALSE);
3763 #ifdef MONO_ARCH_SOFT_FLOAT
3764                         } else if (store->opcode == CEE_STIND_R4) {
3765                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
3766                                 handle_store_float (cfg, bblock, store, *sp, sp [0]->cil_code);
3767 #endif
3768                         } else {
3769                                 MONO_ADD_INS (bblock, store);
3770                         } 
3771                 }
3772                 sp++;
3773         }
3774 }
3775 #define MONO_INLINE_CALLED_LIMITED_METHODS 0
3776 #define MONO_INLINE_CALLER_LIMITED_METHODS 0
3777
3778 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
3779 static char*
3780 mono_inline_called_method_name_limit = NULL;
3781 static gboolean check_inline_called_method_name_limit (MonoMethod *called_method) {
3782         char *called_method_name = mono_method_full_name (called_method, TRUE);
3783         int strncmp_result;
3784         
3785         if (mono_inline_called_method_name_limit == NULL) {
3786                 char *limit_string = getenv ("MONO_INLINE_CALLED_METHOD_NAME_LIMIT");
3787                 if (limit_string != NULL) {
3788                         mono_inline_called_method_name_limit = limit_string;
3789                 } else {
3790                         mono_inline_called_method_name_limit = (char *) "";
3791                 }
3792         }
3793         
3794         strncmp_result = strncmp (called_method_name, mono_inline_called_method_name_limit, strlen (mono_inline_called_method_name_limit));
3795         g_free (called_method_name);
3796         
3797         //return (strncmp_result <= 0);
3798         return (strncmp_result == 0);
3799 }
3800 #endif
3801
3802 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
3803 static char*
3804 mono_inline_caller_method_name_limit = NULL;
3805 static gboolean check_inline_caller_method_name_limit (MonoMethod *caller_method) {
3806         char *caller_method_name = mono_method_full_name (caller_method, TRUE);
3807         int strncmp_result;
3808         
3809         if (mono_inline_caller_method_name_limit == NULL) {
3810                 char *limit_string = getenv ("MONO_INLINE_CALLER_METHOD_NAME_LIMIT");
3811                 if (limit_string != NULL) {
3812                         mono_inline_caller_method_name_limit = limit_string;
3813                 } else {
3814                         mono_inline_caller_method_name_limit = (char *) "";
3815                 }
3816         }
3817         
3818         strncmp_result = strncmp (caller_method_name, mono_inline_caller_method_name_limit, strlen (mono_inline_caller_method_name_limit));
3819         g_free (caller_method_name);
3820         
3821         //return (strncmp_result <= 0);
3822         return (strncmp_result == 0);
3823 }
3824 #endif
3825
3826 static int
3827 inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoBasicBlock *bblock, MonoInst **sp,
3828                 guchar *ip, guint real_offset, GList *dont_inline, MonoBasicBlock **last_b, gboolean inline_allways)
3829 {
3830         MonoInst *ins, *rvar = NULL;
3831         MonoMethodHeader *cheader;
3832         MonoBasicBlock *ebblock, *sbblock;
3833         int i, costs, new_locals_offset;
3834         MonoMethod *prev_inlined_method;
3835         MonoBasicBlock **prev_cil_offset_to_bb;
3836         unsigned char* prev_cil_start;
3837         guint32 prev_cil_offset_to_bb_len;
3838
3839         g_assert (cfg->exception_type == MONO_EXCEPTION_NONE);
3840
3841 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
3842         if ((! inline_allways) && ! check_inline_called_method_name_limit (cmethod))
3843                 return 0;
3844 #endif
3845 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
3846         if ((! inline_allways) && ! check_inline_caller_method_name_limit (cfg->method))
3847                 return 0;
3848 #endif
3849
3850         if (bblock->out_of_line && !inline_allways)
3851                 return 0;
3852
3853         if (cfg->verbose_level > 2)
3854                 g_print ("INLINE START %p %s -> %s\n", cmethod,  mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
3855
3856         if (!cmethod->inline_info) {
3857                 mono_jit_stats.inlineable_methods++;
3858                 cmethod->inline_info = 1;
3859         }
3860         /* allocate space to store the return value */
3861         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
3862                 rvar =  mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
3863         }
3864
3865         /* allocate local variables */
3866         cheader = mono_method_get_header (cmethod);
3867         new_locals_offset = cfg->num_varinfo;
3868         for (i = 0; i < cheader->num_locals; ++i)
3869                 mono_compile_create_var (cfg, cheader->locals [i], OP_LOCAL);
3870
3871         /* allocate starte and end blocks */
3872         NEW_BBLOCK (cfg, sbblock);
3873         sbblock->block_num = cfg->num_bblocks++;
3874         sbblock->real_offset = real_offset;
3875
3876         NEW_BBLOCK (cfg, ebblock);
3877         ebblock->block_num = cfg->num_bblocks++;
3878         ebblock->real_offset = real_offset;
3879
3880         prev_inlined_method = cfg->inlined_method;
3881         cfg->inlined_method = cmethod;
3882         prev_cil_offset_to_bb = cfg->cil_offset_to_bb;
3883         prev_cil_offset_to_bb_len = cfg->cil_offset_to_bb_len;
3884         prev_cil_start = cfg->cil_start;
3885
3886         costs = mono_method_to_ir (cfg, cmethod, sbblock, ebblock, new_locals_offset, rvar, dont_inline, sp, real_offset, *ip == CEE_CALLVIRT);
3887
3888         cfg->inlined_method = prev_inlined_method;
3889         cfg->cil_offset_to_bb = prev_cil_offset_to_bb;
3890         cfg->cil_offset_to_bb_len = prev_cil_offset_to_bb_len;
3891         cfg->cil_start = prev_cil_start;
3892
3893         if ((costs >= 0 && costs < 60) || inline_allways) {
3894                 if (cfg->verbose_level > 2)
3895                         g_print ("INLINE END %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
3896                 
3897                 mono_jit_stats.inlined_methods++;
3898
3899                 /* always add some code to avoid block split failures */
3900                 MONO_INST_NEW (cfg, ins, OP_NOP);
3901                 MONO_ADD_INS (bblock, ins);
3902                 ins->cil_code = ip;
3903
3904                 bblock->next_bb = sbblock;
3905                 link_bblock (cfg, bblock, sbblock);
3906
3907                 if (rvar) {
3908                         NEW_TEMPLOAD (cfg, ins, rvar->inst_c0);
3909 #ifdef MONO_ARCH_SOFT_FLOAT
3910                         if (ins->opcode == CEE_LDIND_R4) {
3911                                 int temp;
3912                                 NEW_TEMPLOADA (cfg, ins, rvar->inst_c0);
3913                                 temp = handle_load_float (cfg, bblock, ins, ip);
3914                                 NEW_TEMPLOAD (cfg, ins, temp);
3915                         }
3916 #endif
3917                         *sp++ = ins;
3918                 }
3919                 *last_b = ebblock;
3920                 return costs + 1;
3921         } else {
3922                 if (cfg->verbose_level > 2)
3923                         g_print ("INLINE ABORTED %s\n", mono_method_full_name (cmethod, TRUE));
3924                 cfg->exception_type = MONO_EXCEPTION_NONE;
3925         }
3926         return 0;
3927 }
3928
3929 /*
3930  * Some of these comments may well be out-of-date.
3931  * Design decisions: we do a single pass over the IL code (and we do bblock 
3932  * splitting/merging in the few cases when it's required: a back jump to an IL
3933  * address that was not already seen as bblock starting point).
3934  * Code is validated as we go (full verification is still better left to metadata/verify.c).
3935  * Complex operations are decomposed in simpler ones right away. We need to let the 
3936  * arch-specific code peek and poke inside this process somehow (except when the 
3937  * optimizations can take advantage of the full semantic info of coarse opcodes).
3938  * All the opcodes of the form opcode.s are 'normalized' to opcode.
3939  * MonoInst->opcode initially is the IL opcode or some simplification of that 
3940  * (OP_LOAD, OP_STORE). The arch-specific code may rearrange it to an arch-specific 
3941  * opcode with value bigger than OP_LAST.
3942  * At this point the IR can be handed over to an interpreter, a dumb code generator
3943  * or to the optimizing code generator that will translate it to SSA form.
3944  *
3945  * Profiling directed optimizations.
3946  * We may compile by default with few or no optimizations and instrument the code
3947  * or the user may indicate what methods to optimize the most either in a config file
3948  * or through repeated runs where the compiler applies offline the optimizations to 
3949  * each method and then decides if it was worth it.
3950  *
3951  */
3952
3953 #define CHECK_TYPE(ins) if (!(ins)->type) UNVERIFIED
3954 #define CHECK_STACK(num) if ((sp - stack_start) < (num)) UNVERIFIED
3955 #define CHECK_STACK_OVF(num) if (((sp - stack_start) + (num)) > header->max_stack) UNVERIFIED
3956 #define CHECK_ARG(num) if ((unsigned)(num) >= (unsigned)num_args) UNVERIFIED
3957 #define CHECK_LOCAL(num) if ((unsigned)(num) >= (unsigned)header->num_locals) UNVERIFIED
3958 #define CHECK_OPSIZE(size) if (ip + size > end) UNVERIFIED
3959 #define CHECK_UNVERIFIABLE(cfg) if (cfg->unverifiable) UNVERIFIED
3960 #define CHECK_TYPELOAD(klass) if (!(klass) || (klass)->exception_type) {cfg->exception_ptr = klass; goto load_error;}
3961
3962 /* offset from br.s -> br like opcodes */
3963 #define BIG_BRANCH_OFFSET 13
3964
3965 static inline gboolean
3966 ip_in_bb (MonoCompile *cfg, MonoBasicBlock *bb, const guint8* ip)
3967 {
3968         MonoBasicBlock *b = cfg->cil_offset_to_bb [ip - cfg->cil_start];
3969         
3970         return b == NULL || b == bb;
3971 }
3972
3973 static int
3974 get_basic_blocks (MonoCompile *cfg, MonoMethodHeader* header, guint real_offset, unsigned char *start, unsigned char *end, unsigned char **pos)
3975 {
3976         unsigned char *ip = start;
3977         unsigned char *target;
3978         int i;
3979         guint cli_addr;
3980         MonoBasicBlock *bblock;
3981         const MonoOpcode *opcode;
3982
3983         while (ip < end) {
3984                 cli_addr = ip - start;
3985                 i = mono_opcode_value ((const guint8 **)&ip, end);
3986                 if (i < 0)
3987                         UNVERIFIED;
3988                 opcode = &mono_opcodes [i];
3989                 switch (opcode->argument) {
3990                 case MonoInlineNone:
3991                         ip++; 
3992                         break;
3993                 case MonoInlineString:
3994                 case MonoInlineType:
3995                 case MonoInlineField:
3996                 case MonoInlineMethod:
3997                 case MonoInlineTok:
3998                 case MonoInlineSig:
3999                 case MonoShortInlineR:
4000                 case MonoInlineI:
4001                         ip += 5;
4002                         break;
4003                 case MonoInlineVar:
4004                         ip += 3;
4005                         break;
4006                 case MonoShortInlineVar:
4007                 case MonoShortInlineI:
4008                         ip += 2;
4009                         break;
4010                 case MonoShortInlineBrTarget:
4011                         target = start + cli_addr + 2 + (signed char)ip [1];
4012                         GET_BBLOCK (cfg, bblock, target);
4013                         ip += 2;
4014                         if (ip < end)
4015                                 GET_BBLOCK (cfg, bblock, ip);
4016                         break;
4017                 case MonoInlineBrTarget:
4018                         target = start + cli_addr + 5 + (gint32)read32 (ip + 1);
4019                         GET_BBLOCK (cfg, bblock, target);
4020                         ip += 5;
4021                         if (ip < end)
4022                                 GET_BBLOCK (cfg, bblock, ip);
4023                         break;
4024                 case MonoInlineSwitch: {
4025                         guint32 n = read32 (ip + 1);
4026                         guint32 j;
4027                         ip += 5;
4028                         cli_addr += 5 + 4 * n;
4029                         target = start + cli_addr;
4030                         GET_BBLOCK (cfg, bblock, target);
4031                         
4032                         for (j = 0; j < n; ++j) {
4033                                 target = start + cli_addr + (gint32)read32 (ip);
4034                                 GET_BBLOCK (cfg, bblock, target);
4035                                 ip += 4;
4036                         }
4037                         break;
4038                 }
4039                 case MonoInlineR:
4040                 case MonoInlineI8:
4041                         ip += 9;
4042                         break;
4043                 default:
4044                         g_assert_not_reached ();
4045                 }
4046
4047                 if (i == CEE_THROW) {
4048                         unsigned char *bb_start = ip - 1;
4049                         
4050                         /* Find the start of the bblock containing the throw */
4051                         bblock = NULL;
4052                         while ((bb_start >= start) && !bblock) {
4053                                 bblock = cfg->cil_offset_to_bb [(bb_start) - start];
4054                                 bb_start --;
4055                         }
4056                         if (bblock)
4057                                 bblock->out_of_line = 1;
4058                 }
4059         }
4060         return 0;
4061 unverified:
4062         *pos = ip;
4063         return 1;
4064 }
4065
4066 static MonoInst*
4067 emit_tree (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ins, const guint8* ip_next)
4068 {
4069         MonoInst *store, *temp, *load;
4070         
4071         if (ip_in_bb (cfg, bblock, ip_next) &&
4072                 (CODE_IS_STLOC (ip_next) || *ip_next == CEE_RET))
4073                         return ins;
4074         
4075         temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
4076         temp->flags |= MONO_INST_IS_TEMP;
4077         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
4078         /* FIXME: handle CEE_STIND_R4 */
4079         store->cil_code = ins->cil_code;
4080         MONO_ADD_INS (bblock, store);
4081         NEW_TEMPLOAD (cfg, load, temp->inst_c0);
4082         load->cil_code = ins->cil_code;
4083         return load;
4084 }
4085
4086 static inline MonoMethod *
4087 mini_get_method (MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context)
4088 {
4089         MonoMethod *method;
4090
4091         if (m->wrapper_type != MONO_WRAPPER_NONE)
4092                 return mono_method_get_wrapper_data (m, token);
4093
4094         method = mono_get_method_full (m->klass->image, token, klass, context);
4095
4096         return method;
4097 }
4098
4099 static inline MonoClass*
4100 mini_get_class (MonoMethod *method, guint32 token, MonoGenericContext *context)
4101 {
4102         MonoClass *klass;
4103
4104         if (method->wrapper_type != MONO_WRAPPER_NONE)
4105                 klass = mono_method_get_wrapper_data (method, token);
4106         else
4107                 klass = mono_class_get_full (method->klass->image, token, context);
4108         if (klass)
4109                 mono_class_init (klass);
4110         return klass;
4111 }
4112
4113 /*
4114  * Returns TRUE if the JIT should abort inlining because "callee"
4115  * is influenced by security attributes.
4116  */
4117 static
4118 gboolean check_linkdemand (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee, MonoBasicBlock *bblock, unsigned char *ip)
4119 {
4120         guint32 result;
4121         
4122         if ((cfg->method != caller) && mono_method_has_declsec (callee)) {
4123                 return TRUE;
4124         }
4125         
4126         result = mono_declsec_linkdemand (cfg->domain, caller, callee);
4127         if (result == MONO_JIT_SECURITY_OK)
4128                 return FALSE;
4129
4130         if (result == MONO_JIT_LINKDEMAND_ECMA) {
4131                 /* Generate code to throw a SecurityException before the actual call/link */
4132                 MonoSecurityManager *secman = mono_security_manager_get_methods ();
4133                 MonoInst *args [2];
4134
4135                 NEW_ICONST (cfg, args [0], 4);
4136                 NEW_METHODCONST (cfg, args [1], caller);
4137                 mono_emit_method_call_spilled (cfg, bblock, secman->linkdemandsecurityexception, mono_method_signature (secman->linkdemandsecurityexception), args, ip, NULL);
4138         } else if (cfg->exception_type == MONO_EXCEPTION_NONE) {
4139                  /* don't hide previous results */
4140                 cfg->exception_type = MONO_EXCEPTION_SECURITY_LINKDEMAND;
4141                 cfg->exception_data = result;
4142                 return TRUE;
4143         }
4144         
4145         return FALSE;
4146 }
4147
4148 static MonoMethod*
4149 method_access_exception (void)
4150 {
4151         static MonoMethod *method = NULL;
4152
4153         if (!method) {
4154                 MonoSecurityManager *secman = mono_security_manager_get_methods ();
4155                 method = mono_class_get_method_from_name (secman->securitymanager,
4156                                                           "MethodAccessException", 2);
4157         }
4158         g_assert (method);
4159         return method;
4160 }
4161
4162 static void
4163 emit_throw_method_access_exception (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee,
4164                                     MonoBasicBlock *bblock, unsigned char *ip)
4165 {
4166         MonoMethod *thrower = method_access_exception ();
4167         MonoInst *args [2];
4168
4169         NEW_METHODCONST (cfg, args [0], caller);
4170         NEW_METHODCONST (cfg, args [1], callee);
4171         mono_emit_method_call_spilled (cfg, bblock, thrower,
4172                 mono_method_signature (thrower), args, ip, NULL);
4173 }
4174
4175 static MonoMethod*
4176 verification_exception (void)
4177 {
4178         static MonoMethod *method = NULL;
4179
4180         if (!method) {
4181                 MonoSecurityManager *secman = mono_security_manager_get_methods ();
4182                 method = mono_class_get_method_from_name (secman->securitymanager,
4183                                                           "VerificationException", 0);
4184         }
4185         g_assert (method);
4186         return method;
4187 }
4188
4189 static void
4190 emit_throw_verification_exception (MonoCompile *cfg, MonoBasicBlock *bblock, unsigned char *ip)
4191 {
4192         MonoMethod *thrower = verification_exception ();
4193
4194         mono_emit_method_call_spilled (cfg, bblock, thrower,
4195                 mono_method_signature (thrower),
4196                 NULL, ip, NULL);
4197 }
4198
4199 static void
4200 ensure_method_is_allowed_to_call_method (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee,
4201                                          MonoBasicBlock *bblock, unsigned char *ip)
4202 {
4203         MonoSecurityCoreCLRLevel caller_level = mono_security_core_clr_method_level (caller, TRUE);
4204         MonoSecurityCoreCLRLevel callee_level = mono_security_core_clr_method_level (callee, TRUE);
4205         gboolean is_safe = TRUE;
4206
4207         if (!(caller_level >= callee_level ||
4208                         caller_level == MONO_SECURITY_CORE_CLR_SAFE_CRITICAL ||
4209                         callee_level == MONO_SECURITY_CORE_CLR_SAFE_CRITICAL)) {
4210                 is_safe = FALSE;
4211         }
4212
4213         if (!is_safe)
4214                 emit_throw_method_access_exception (cfg, caller, callee, bblock, ip);
4215 }
4216
4217 static gboolean
4218 method_is_safe (MonoMethod *method)
4219 {
4220         /*
4221         if (strcmp (method->name, "unsafeMethod") == 0)
4222                 return FALSE;
4223         */
4224         return TRUE;
4225 }
4226
4227 /*
4228  * Check that the IL instructions at ip are the array initialization
4229  * sequence and return the pointer to the data and the size.
4230  */
4231 static const char*
4232 initialize_array_data (MonoMethod *method, gboolean aot, unsigned char *ip, MonoInst *newarr, int *out_size)
4233 {
4234         /*
4235          * newarr[System.Int32]
4236          * dup
4237          * ldtoken field valuetype ...
4238          * call void class [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class [mscorlib]System.Array, valuetype [mscorlib]System.RuntimeFieldHandle)
4239          */
4240         if (ip [0] == CEE_DUP && ip [1] == CEE_LDTOKEN && ip [5] == 0x4 && ip [6] == CEE_CALL) {
4241                 MonoClass *klass = newarr->inst_newa_class;
4242                 guint32 field_token = read32 (ip + 2);
4243                 guint32 field_index = field_token & 0xffffff;
4244                 guint32 token = read32 (ip + 7);
4245                 guint32 rva;
4246                 const char *data_ptr;
4247                 int size = 0;
4248                 MonoMethod *cmethod;
4249                 MonoClass *dummy_class;
4250                 MonoClassField *field = mono_field_from_token (method->klass->image, field_token, &dummy_class, NULL);
4251                 int dummy_align;
4252
4253                 if (!field)
4254                         return NULL;
4255
4256                 if (newarr->inst_newa_len->opcode != OP_ICONST)
4257                         return NULL;
4258                 cmethod = mini_get_method (method, token, NULL, NULL);
4259                 if (!cmethod)
4260                         return NULL;
4261                 if (strcmp (cmethod->name, "InitializeArray") || strcmp (cmethod->klass->name, "RuntimeHelpers") || cmethod->klass->image != mono_defaults.corlib)
4262                         return NULL;
4263                 switch (mono_type_get_underlying_type (&klass->byval_arg)->type) {
4264                 case MONO_TYPE_BOOLEAN:
4265                 case MONO_TYPE_I1:
4266                 case MONO_TYPE_U1:
4267                         size = 1; break;
4268                 /* we need to swap on big endian, so punt. Should we handle R4 and R8 as well? */
4269 #if G_BYTE_ORDER == G_LITTLE_ENDIAN
4270                 case MONO_TYPE_CHAR:
4271                 case MONO_TYPE_I2:
4272                 case MONO_TYPE_U2:
4273                         size = 2; break;
4274                 case MONO_TYPE_I4:
4275                 case MONO_TYPE_U4:
4276                 case MONO_TYPE_R4:
4277                         size = 4; break;
4278                 case MONO_TYPE_R8:
4279 #ifdef ARM_FPU_FPA
4280                         return NULL; /* stupid ARM FP swapped format */
4281 #endif
4282                 case MONO_TYPE_I8:
4283                 case MONO_TYPE_U8:
4284                         size = 8; break;
4285 #endif
4286                 default:
4287                         return NULL;
4288                 }
4289                 size *= newarr->inst_newa_len->inst_c0;
4290                 if (size > mono_type_size (field->type, &dummy_align))
4291                     return NULL;
4292                 *out_size = size;
4293                 /*g_print ("optimized in %s: size: %d, numelems: %d\n", method->name, size, newarr->inst_newa_len->inst_c0);*/
4294                 field_index = read32 (ip + 2) & 0xffffff;
4295                 mono_metadata_field_info (method->klass->image, field_index - 1, NULL, &rva, NULL);
4296                 data_ptr = mono_image_rva_map (method->klass->image, rva);
4297                 /*g_print ("field: 0x%08x, rva: %d, rva_ptr: %p\n", read32 (ip + 2), rva, data_ptr);*/
4298                 /* for aot code we do the lookup on load */
4299                 if (aot && data_ptr)
4300                         return GUINT_TO_POINTER (rva);
4301                 return data_ptr;
4302         }
4303         return NULL;
4304 }
4305
4306 static void
4307 set_exception_type_from_invalid_il (MonoCompile *cfg, MonoMethod *method, unsigned char *ip)
4308 {
4309         char *method_fname = mono_method_full_name (method, TRUE);
4310         char *method_code = mono_disasm_code_one (NULL, method, ip, NULL);
4311         cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
4312         cfg->exception_message = g_strdup_printf ("Invalid IL code in %s: %s\n", method_fname, method_code);
4313         g_free (method_fname);
4314         g_free (method_code);
4315 }
4316
4317 /*
4318  * Generates this->vtable->runtime_generic_context
4319  */
4320 static MonoInst*
4321 get_runtime_generic_context_from_this (MonoCompile *cfg, MonoInst *this, unsigned char *ip)
4322 {
4323         MonoInst *vtable, *rgc_ptr_addr, *rgc_ptr_offset, *rgc_ptr;
4324
4325         MONO_INST_NEW (cfg, vtable, CEE_LDIND_I);
4326         vtable->cil_code = ip;
4327         vtable->inst_left = this;
4328         vtable->type = STACK_PTR;
4329
4330         NEW_ICONST (cfg, rgc_ptr_offset, G_STRUCT_OFFSET (MonoVTable, runtime_generic_context));
4331
4332         MONO_INST_NEW (cfg, rgc_ptr_addr, OP_PADD);
4333         rgc_ptr_addr->cil_code = ip;
4334         rgc_ptr_addr->inst_left = vtable;
4335         rgc_ptr_addr->inst_right = rgc_ptr_offset;
4336         rgc_ptr_addr->type = STACK_PTR;
4337
4338         MONO_INST_NEW (cfg, rgc_ptr, CEE_LDIND_I);
4339         rgc_ptr->cil_code = ip;
4340         rgc_ptr->inst_left = rgc_ptr_addr;
4341         rgc_ptr->type = STACK_PTR;
4342
4343         return rgc_ptr;
4344 }
4345
4346 static MonoInst*
4347 get_runtime_generic_context_field_from_offset (MonoCompile *cfg, MonoInst *rgc_ptr, int offset, unsigned char *ip)
4348 {
4349         MonoInst *field_offset, *field_addr, *field;
4350
4351         NEW_ICONST (cfg, field_offset, offset);
4352
4353         MONO_INST_NEW (cfg, field_addr, OP_PADD);
4354         field_addr->cil_code = ip;
4355         field_addr->inst_left = rgc_ptr;
4356         field_addr->inst_right = field_offset;
4357         field_addr->type = STACK_PTR;
4358
4359         MONO_INST_NEW (cfg, field, CEE_LDIND_I);
4360         field->cil_code = ip;
4361         field->inst_left = field_addr;
4362         field->type = STACK_PTR;
4363
4364         return field;
4365 }
4366
4367 /*
4368  * Generates ((MonoRuntimeGenericSuperInfo*)rgc)[-depth].XXX where XXX
4369  * is specified by rgctx_type.
4370  */
4371 static MonoInst*
4372 get_runtime_generic_context_super_ptr (MonoCompile *cfg, MonoInst *rgc_ptr, int depth, int rgctx_type, unsigned char *ip)
4373 {
4374         int field_offset_const;
4375
4376         g_assert (depth >= 1);
4377
4378         switch (rgctx_type) {
4379         case MINI_RGCTX_STATIC_DATA :
4380                 field_offset_const = G_STRUCT_OFFSET (MonoRuntimeGenericSuperInfo, static_data);
4381                 break;
4382         case MINI_RGCTX_KLASS :
4383                 field_offset_const = G_STRUCT_OFFSET (MonoRuntimeGenericSuperInfo, klass);
4384                 break;
4385         case MINI_RGCTX_VTABLE:
4386                 field_offset_const = G_STRUCT_OFFSET (MonoRuntimeGenericSuperInfo, vtable);
4387                 break;
4388         default :
4389                 g_assert_not_reached ();
4390         }
4391
4392         return get_runtime_generic_context_field_from_offset (cfg, rgc_ptr,
4393                 -depth * sizeof (MonoRuntimeGenericSuperInfo) + field_offset_const, ip);
4394 }
4395
4396 /*
4397  * Generic rgc->arg_infos [arg_num].XXX where XXX is specified by
4398  * rgctx_type;
4399  */
4400 static MonoInst*
4401 get_runtime_generic_context_arg_ptr (MonoCompile *cfg, MonoInst *rgc_ptr, int arg_num, int rgctx_type, unsigned char *ip)
4402 {
4403         int arg_info_offset, arg_info_field_offset;
4404
4405         g_assert (arg_num >= 0);
4406
4407         arg_info_offset = G_STRUCT_OFFSET (MonoRuntimeGenericContext, arg_infos) +
4408                 arg_num * sizeof (MonoRuntimeGenericArgInfo);
4409
4410         switch (rgctx_type) {
4411         case MINI_RGCTX_STATIC_DATA :
4412                 arg_info_field_offset = G_STRUCT_OFFSET (MonoRuntimeGenericArgInfo, static_data);
4413                 break;
4414         case MINI_RGCTX_KLASS:
4415                 arg_info_field_offset = G_STRUCT_OFFSET (MonoRuntimeGenericArgInfo, klass);
4416                 break;
4417         case MINI_RGCTX_VTABLE :
4418                 arg_info_field_offset = G_STRUCT_OFFSET (MonoRuntimeGenericArgInfo, vtable);
4419                 break;
4420         default:
4421                 g_assert_not_reached ();
4422         }
4423
4424         return get_runtime_generic_context_field_from_offset (cfg, rgc_ptr, arg_info_offset + arg_info_field_offset, ip);
4425 }
4426
4427 static MonoInst*
4428 get_runtime_generic_context_other_ptr (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *bblock,
4429         MonoInst *rgc_ptr, guint32 token, int rgctx_type, unsigned char *ip)
4430 {
4431         MonoInst *args [4];
4432         int temp;
4433         MonoInst *result;
4434
4435         g_assert (method->wrapper_type == MONO_WRAPPER_NONE);
4436
4437         NEW_CLASSCONST (cfg, args [0], method->klass);
4438         args [1] = rgc_ptr;
4439         NEW_ICONST (cfg, args [2], token);
4440         NEW_ICONST (cfg, args [3], rgctx_type);
4441
4442         temp = mono_emit_jit_icall (cfg, bblock, mono_helper_get_rgctx_other_ptr, args, ip);
4443         NEW_TEMPLOAD (cfg, result, temp);
4444
4445         return result;
4446 }
4447
4448 static MonoInst*
4449 get_runtime_generic_context_ptr (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *bblock,
4450         MonoClass *klass, guint32 type_token, MonoGenericContext *generic_context, MonoInst *rgctx,
4451         int rgctx_type, unsigned char *ip)
4452 {
4453         int arg_num = -1;
4454         int relation = mono_class_generic_class_relation (klass, method->klass, generic_context, &arg_num);
4455
4456         switch (relation) {
4457         case MINI_GENERIC_CLASS_RELATION_SELF: {
4458                 int depth = klass->idepth;
4459                 return get_runtime_generic_context_super_ptr (cfg, rgctx, depth, rgctx_type, ip);
4460         }
4461         case MINI_GENERIC_CLASS_RELATION_ARGUMENT:
4462                 return get_runtime_generic_context_arg_ptr (cfg, rgctx, arg_num, rgctx_type, ip);
4463         case MINI_GENERIC_CLASS_RELATION_OTHER:
4464                 return get_runtime_generic_context_other_ptr (cfg, method, bblock, rgctx, type_token, rgctx_type, ip);
4465         default:
4466                 g_assert_not_reached ();
4467                 return NULL;
4468         }
4469 }
4470
4471 /*
4472  * mono_method_to_ir: translates IL into basic blocks containing trees
4473  */
4474 static int
4475 mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
4476                    int locals_offset, MonoInst *return_var, GList *dont_inline, MonoInst **inline_args, 
4477                    guint inline_offset, gboolean is_virtual_call)
4478 {
4479         MonoInst *zero_int32, *zero_int64, *zero_ptr, *zero_obj, *zero_r8;
4480         MonoInst *ins, **sp, **stack_start;
4481         MonoBasicBlock *bblock, *tblock = NULL, *init_localsbb = NULL;
4482         MonoMethod *cmethod;
4483         MonoInst **arg_array;
4484         MonoMethodHeader *header;
4485         MonoImage *image;
4486         guint32 token, ins_flag;
4487         MonoClass *klass;
4488         MonoClass *constrained_call = NULL;
4489         unsigned char *ip, *end, *target, *err_pos;
4490         static double r8_0 = 0.0;
4491         MonoMethodSignature *sig;
4492         MonoGenericContext *generic_context = NULL;
4493         MonoGenericContainer *generic_container = NULL;
4494         MonoType **param_types;
4495         GList *bb_recheck = NULL, *tmp;
4496         int i, n, start_new_bblock, ialign;
4497         int num_calls = 0, inline_costs = 0;
4498         int breakpoint_id = 0;
4499         guint32 align;
4500         guint real_offset, num_args;
4501         MonoBoolean security, pinvoke;
4502         MonoSecurityManager* secman = NULL;
4503         MonoDeclSecurityActions actions;
4504         GSList *class_inits = NULL;
4505         gboolean dont_verify, dont_verify_stloc;
4506
4507         /* serialization and xdomain stuff may need access to private fields and methods */
4508         dont_verify = method->klass->image->assembly->corlib_internal? TRUE: FALSE;
4509         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE;
4510         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH;
4511         dont_verify |= method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE; /* bug #77896 */
4512         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP;
4513         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP_INVOKE;
4514
4515         /* turn off visibility checks for smcs */
4516         dont_verify |= mono_security_get_mode () == MONO_SECURITY_MODE_SMCS_HACK;
4517
4518         /* still some type unsafety issues in marshal wrappers... (unknown is PtrToStructure) */
4519         dont_verify_stloc = method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE;
4520         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_UNKNOWN;
4521         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED;
4522
4523         /* Not turned on yet */
4524         cfg->dont_verify_stack_merge = TRUE;
4525
4526         image = method->klass->image;
4527         header = mono_method_get_header (method);
4528         generic_container = method->generic_container;
4529         sig = mono_method_signature (method);
4530         num_args = sig->hasthis + sig->param_count;
4531         ip = (unsigned char*)header->code;
4532         cfg->cil_start = ip;
4533         end = ip + header->code_size;
4534         mono_jit_stats.cil_code_size += header->code_size;
4535
4536         if (sig->is_inflated)
4537                 generic_context = mono_method_get_context (method);
4538         else if (generic_container)
4539                 generic_context = &generic_container->context;
4540
4541         if (!cfg->generic_sharing_context)
4542                 g_assert (!sig->has_type_parameters);
4543
4544         if (cfg->method == method)
4545                 real_offset = 0;
4546         else
4547                 real_offset = inline_offset;
4548
4549         cfg->cil_offset_to_bb = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoBasicBlock*) * header->code_size);
4550         cfg->cil_offset_to_bb_len = header->code_size;
4551
4552         if (cfg->verbose_level > 2)
4553                 g_print ("method to IR %s\n", mono_method_full_name (method, TRUE));
4554
4555         dont_inline = g_list_prepend (dont_inline, method);
4556         if (cfg->method == method) {
4557
4558                 if (cfg->prof_options & MONO_PROFILE_INS_COVERAGE)
4559                         cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, header->code_size);
4560
4561                 /* ENTRY BLOCK */
4562                 NEW_BBLOCK (cfg, start_bblock);
4563                 cfg->bb_entry = start_bblock;
4564                 start_bblock->cil_code = NULL;
4565                 start_bblock->cil_length = 0;
4566                 start_bblock->block_num = cfg->num_bblocks++;
4567
4568                 /* EXIT BLOCK */
4569                 NEW_BBLOCK (cfg, end_bblock);
4570                 cfg->bb_exit = end_bblock;
4571                 end_bblock->cil_code = NULL;
4572                 end_bblock->cil_length = 0;
4573                 end_bblock->block_num = cfg->num_bblocks++;
4574                 g_assert (cfg->num_bblocks == 2);
4575
4576                 arg_array = alloca (sizeof (MonoInst *) * num_args);
4577                 for (i = num_args - 1; i >= 0; i--)
4578                         arg_array [i] = cfg->varinfo [i];
4579
4580                 if (header->num_clauses) {
4581                         cfg->spvars = g_hash_table_new (NULL, NULL);
4582                         cfg->exvars = g_hash_table_new (NULL, NULL);
4583                 }
4584                 /* handle exception clauses */
4585                 for (i = 0; i < header->num_clauses; ++i) {
4586                         MonoBasicBlock *try_bb;
4587                         MonoExceptionClause *clause = &header->clauses [i];
4588                         GET_BBLOCK (cfg, try_bb, ip + clause->try_offset);
4589                         try_bb->real_offset = clause->try_offset;
4590                         GET_BBLOCK (cfg, tblock, ip + clause->handler_offset);
4591                         tblock->real_offset = clause->handler_offset;
4592                         tblock->flags |= BB_EXCEPTION_HANDLER;
4593
4594                         link_bblock (cfg, try_bb, tblock);
4595
4596                         if (*(ip + clause->handler_offset) == CEE_POP)
4597                                 tblock->flags |= BB_EXCEPTION_DEAD_OBJ;
4598
4599                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY ||
4600                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER ||
4601                             clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) {
4602                                 MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
4603                                 MONO_ADD_INS (tblock, ins);
4604
4605                                 /* todo: is a fault block unsafe to optimize? */
4606                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
4607                                         tblock->flags |= BB_EXCEPTION_UNSAFE;
4608                         }
4609
4610
4611                         /*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);
4612                           while (p < end) {
4613                           g_print ("%s", mono_disasm_code_one (NULL, method, p, &p));
4614                           }*/
4615                         /* catch and filter blocks get the exception object on the stack */
4616                         if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE ||
4617                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
4618                                 MonoInst *load, *dummy_use;
4619
4620                                 /* mostly like handle_stack_args (), but just sets the input args */
4621                                 /* g_print ("handling clause at IL_%04x\n", clause->handler_offset); */
4622                                 tblock->in_scount = 1;
4623                                 tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
4624                                 tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
4625                                 tblock->stack_state = mono_mempool_alloc (cfg->mempool, sizeof (MonoStackSlot));
4626                                 tblock->stack_state [0].type = STACK_OBJ;
4627                                 /* FIXME? */
4628                                 tblock->stack_state [0].klass = mono_defaults.object_class;
4629
4630                                 /* 
4631                                  * Add a dummy use for the exvar so its liveness info will be
4632                                  * correct.
4633                                  */
4634                                 NEW_TEMPLOAD (cfg, load, tblock->in_stack [0]->inst_c0);
4635                                 NEW_DUMMY_USE (cfg, dummy_use, load);
4636                                 MONO_ADD_INS (tblock, dummy_use);
4637                                 
4638                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
4639                                         GET_BBLOCK (cfg, tblock, ip + clause->data.filter_offset);
4640                                         tblock->real_offset = clause->data.filter_offset;
4641                                         tblock->in_scount = 1;
4642                                         tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
4643                                         tblock->stack_state = mono_mempool_alloc (cfg->mempool, sizeof (MonoStackSlot));
4644                                         tblock->stack_state [0].type = STACK_OBJ;
4645                                         /* FIXME? */
4646                                         tblock->stack_state [0].klass = mono_defaults.object_class;
4647
4648                                         /* The filter block shares the exvar with the handler block */
4649                                         tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
4650                                         MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
4651                                         MONO_ADD_INS (tblock, ins);
4652                                 }
4653                         }
4654                 }
4655         } else {
4656                 arg_array = alloca (sizeof (MonoInst *) * num_args);
4657                 mono_save_args (cfg, start_bblock, sig, inline_args, arg_array);
4658         }
4659
4660         /* FIRST CODE BLOCK */
4661         NEW_BBLOCK (cfg, bblock);
4662         bblock->cil_code = ip;
4663
4664         ADD_BBLOCK (cfg, bblock);
4665
4666         if (cfg->method == method) {
4667                 breakpoint_id = mono_debugger_method_has_breakpoint (method);
4668                 if (breakpoint_id && (mono_debug_format != MONO_DEBUG_FORMAT_DEBUGGER)) {
4669                         MONO_INST_NEW (cfg, ins, OP_BREAK);
4670                         MONO_ADD_INS (bblock, ins);
4671                 }
4672         }
4673
4674         if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS)
4675                 secman = mono_security_manager_get_methods ();
4676
4677         security = (secman && mono_method_has_declsec (method));
4678         /* at this point having security doesn't mean we have any code to generate */
4679         if (security && (cfg->method == method)) {
4680                 /* Only Demand, NonCasDemand and DemandChoice requires code generation.
4681                  * And we do not want to enter the next section (with allocation) if we
4682                  * have nothing to generate */
4683                 security = mono_declsec_get_demands (method, &actions);
4684         }
4685
4686         /* we must Demand SecurityPermission.Unmanaged before P/Invoking */
4687         pinvoke = (secman && (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE));
4688         if (pinvoke) {
4689                 MonoMethod *wrapped = mono_marshal_method_from_wrapper (method);
4690                 if (wrapped && (wrapped->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4691                         MonoCustomAttrInfo* custom = mono_custom_attrs_from_method (wrapped);
4692
4693                         /* unless the method or it's class has the [SuppressUnmanagedCodeSecurity] attribute */
4694                         if (custom && mono_custom_attrs_has_attr (custom, secman->suppressunmanagedcodesecurity)) {
4695                                 pinvoke = FALSE;
4696                         }
4697                         if (custom)
4698                                 mono_custom_attrs_free (custom);
4699
4700                         if (pinvoke) {
4701                                 custom = mono_custom_attrs_from_class (wrapped->klass);
4702                                 if (custom && mono_custom_attrs_has_attr (custom, secman->suppressunmanagedcodesecurity)) {
4703                                         pinvoke = FALSE;
4704                                 }
4705                                 if (custom)
4706                                         mono_custom_attrs_free (custom);
4707                         }
4708                 } else {
4709                         /* not a P/Invoke after all */
4710                         pinvoke = FALSE;
4711                 }
4712         }
4713         
4714         if ((header->init_locals || (cfg->method == method && (cfg->opt & MONO_OPT_SHARED))) || cfg->compile_aot || security || pinvoke) {
4715                 /* we use a separate basic block for the initialization code */
4716                 NEW_BBLOCK (cfg, init_localsbb);
4717                 cfg->bb_init = init_localsbb;
4718                 init_localsbb->real_offset = real_offset;
4719                 start_bblock->next_bb = init_localsbb;
4720                 init_localsbb->next_bb = bblock;
4721                 link_bblock (cfg, start_bblock, init_localsbb);
4722                 link_bblock (cfg, init_localsbb, bblock);
4723                 init_localsbb->block_num = cfg->num_bblocks++;
4724         } else {
4725                 start_bblock->next_bb = bblock;
4726                 link_bblock (cfg, start_bblock, bblock);
4727         }
4728
4729         /* at this point we know, if security is TRUE, that some code needs to be generated */
4730         if (security && (cfg->method == method)) {
4731                 MonoInst *args [2];
4732
4733                 mono_jit_stats.cas_demand_generation++;
4734
4735                 if (actions.demand.blob) {
4736                         /* Add code for SecurityAction.Demand */
4737                         NEW_DECLSECCONST (cfg, args[0], image, actions.demand);
4738                         NEW_ICONST (cfg, args [1], actions.demand.size);
4739                         /* Calls static void SecurityManager.InternalDemand (byte* permissions, int size); */
4740                         mono_emit_method_call_spilled (cfg, init_localsbb, secman->demand, mono_method_signature (secman->demand), args, ip, NULL);
4741                 }
4742                 if (actions.noncasdemand.blob) {
4743                         /* CLR 1.x uses a .noncasdemand (but 2.x doesn't) */
4744                         /* For Mono we re-route non-CAS Demand to Demand (as the managed code must deal with it anyway) */
4745                         NEW_DECLSECCONST (cfg, args[0], image, actions.noncasdemand);
4746                         NEW_ICONST (cfg, args [1], actions.noncasdemand.size);
4747                         /* Calls static void SecurityManager.InternalDemand (byte* permissions, int size); */
4748                         mono_emit_method_call_spilled (cfg, init_localsbb, secman->demand, mono_method_signature (secman->demand), args, ip, NULL);
4749                 }
4750                 if (actions.demandchoice.blob) {
4751                         /* New in 2.0, Demand must succeed for one of the permissions (i.e. not all) */
4752                         NEW_DECLSECCONST (cfg, args[0], image, actions.demandchoice);
4753                         NEW_ICONST (cfg, args [1], actions.demandchoice.size);
4754                         /* Calls static void SecurityManager.InternalDemandChoice (byte* permissions, int size); */
4755                         mono_emit_method_call_spilled (cfg, init_localsbb, secman->demandchoice, mono_method_signature (secman->demandchoice), args, ip, NULL);
4756                 }
4757         }
4758
4759         /* we must Demand SecurityPermission.Unmanaged before p/invoking */
4760         if (pinvoke) {
4761                 mono_emit_method_call_spilled (cfg, init_localsbb, secman->demandunmanaged, mono_method_signature (secman->demandunmanaged), NULL, ip, NULL);
4762         }
4763
4764         if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
4765                 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
4766                         MonoMethod *wrapped = mono_marshal_method_from_wrapper (method);
4767                         if (wrapped && (wrapped->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4768                                 if (!(method->klass && method->klass->image &&
4769                                                 mono_security_core_clr_is_platform_image (method->klass->image))) {
4770                                         emit_throw_method_access_exception (cfg, method, wrapped, bblock, ip);
4771                                 }
4772                         }
4773                 }
4774                 if (!method_is_safe (method))
4775                         emit_throw_verification_exception (cfg, bblock, ip);
4776         }
4777
4778         if (get_basic_blocks (cfg, header, real_offset, ip, end, &err_pos)) {
4779                 ip = err_pos;
4780                 UNVERIFIED;
4781         }
4782
4783         if (cfg->method == method)
4784                 mono_debug_init_method (cfg, bblock, breakpoint_id);
4785
4786         param_types = mono_mempool_alloc (cfg->mempool, sizeof (MonoType*) * num_args);
4787         if (sig->hasthis)
4788                 param_types [0] = method->klass->valuetype?&method->klass->this_arg:&method->klass->byval_arg;
4789         for (n = 0; n < sig->param_count; ++n)
4790                 param_types [n + sig->hasthis] = sig->params [n];
4791         for (n = 0; n < header->num_locals; ++n) {
4792                 if (header->locals [n]->type == MONO_TYPE_VOID && !header->locals [n]->byref)
4793                         UNVERIFIED;
4794         }
4795         class_inits = NULL;
4796
4797         /* do this somewhere outside - not here */
4798         NEW_ICONST (cfg, zero_int32, 0);
4799         NEW_ICONST (cfg, zero_int64, 0);
4800         zero_int64->type = STACK_I8;
4801         NEW_PCONST (cfg, zero_ptr, 0);
4802         NEW_PCONST (cfg, zero_obj, 0);
4803         zero_obj->type = STACK_OBJ;
4804
4805         MONO_INST_NEW (cfg, zero_r8, OP_R8CONST);
4806         zero_r8->type = STACK_R8;
4807         zero_r8->inst_p0 = &r8_0;
4808
4809         /* add a check for this != NULL to inlined methods */
4810         if (is_virtual_call) {
4811                 MONO_INST_NEW (cfg, ins, OP_CHECK_THIS);
4812                 NEW_ARGLOAD (cfg, ins->inst_left, 0);
4813                 ins->cil_code = ip;
4814                 MONO_ADD_INS (bblock, ins);
4815         }
4816
4817         /* we use a spare stack slot in SWITCH and NEWOBJ and others */
4818         stack_start = sp = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (header->max_stack + 1));
4819
4820         ins_flag = 0;
4821         start_new_bblock = 0;
4822         while (ip < end) {
4823
4824                 if (cfg->method == method)
4825                         real_offset = ip - header->code;
4826                 else
4827                         real_offset = inline_offset;
4828
4829                 if (start_new_bblock) {
4830                         bblock->cil_length = ip - bblock->cil_code;
4831                         if (start_new_bblock == 2) {
4832                                 g_assert (ip == tblock->cil_code);
4833                         } else {
4834                                 GET_BBLOCK (cfg, tblock, ip);
4835                         }
4836                         bblock->next_bb = tblock;
4837                         bblock = tblock;
4838                         start_new_bblock = 0;
4839                         for (i = 0; i < bblock->in_scount; ++i) {
4840                                 if (cfg->verbose_level > 3)
4841                                         g_print ("loading %d from temp %d\n", i, (int)bblock->in_stack [i]->inst_c0);                                           
4842                                 NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
4843                                 *sp++ = ins;
4844                         }
4845                         g_slist_free (class_inits);
4846                         class_inits = NULL;
4847                 } else {
4848                         if ((tblock = cfg->cil_offset_to_bb [ip - cfg->cil_start]) && (tblock != bblock)) {
4849                                 link_bblock (cfg, bblock, tblock);
4850                                 if (sp != stack_start) {
4851                                         handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
4852                                         sp = stack_start;
4853                                         CHECK_UNVERIFIABLE (cfg);
4854                                 }
4855                                 bblock->next_bb = tblock;
4856                                 bblock = tblock;
4857                                 for (i = 0; i < bblock->in_scount; ++i) {
4858                                         if (cfg->verbose_level > 3)
4859                                                 g_print ("loading %d from temp %d\n", i, (int)bblock->in_stack [i]->inst_c0);                                           
4860                                         NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
4861                                         *sp++ = ins;
4862                                 }
4863                                 g_slist_free (class_inits);
4864                                 class_inits = NULL;
4865                         }
4866                 }
4867
4868                 bblock->real_offset = real_offset;
4869
4870                 if ((cfg->method == method) && cfg->coverage_info) {
4871                         MonoInst *store, *one;
4872                         guint32 cil_offset = ip - header->code;
4873                         cfg->coverage_info->data [cil_offset].cil_code = ip;
4874
4875                         /* TODO: Use an increment here */
4876                         NEW_ICONST (cfg, one, 1);
4877                         one->cil_code = ip;
4878
4879                         NEW_PCONST (cfg, ins, &(cfg->coverage_info->data [cil_offset].count));
4880                         ins->cil_code = ip;
4881
4882                         MONO_INST_NEW (cfg, store, CEE_STIND_I);
4883                         store->cil_code = ip;
4884                         store->inst_left = ins;
4885                         store->inst_right = one;
4886
4887                         MONO_ADD_INS (bblock, store);
4888                 }
4889
4890                 if (cfg->verbose_level > 3)
4891                         g_print ("converting (in B%d: stack: %d) %s", bblock->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
4892
4893                 switch (*ip) {
4894                 case CEE_NOP:
4895                         MONO_INST_NEW (cfg, ins, OP_NOP);
4896                         ins->cil_code = ip++;
4897                         MONO_ADD_INS (bblock, ins);
4898                         break;
4899                 case CEE_BREAK:
4900                         MONO_INST_NEW (cfg, ins, OP_BREAK);
4901                         ins->cil_code = ip++;
4902                         MONO_ADD_INS (bblock, ins);
4903                         break;
4904                 case CEE_LDARG_0:
4905                 case CEE_LDARG_1:
4906                 case CEE_LDARG_2:
4907                 case CEE_LDARG_3:
4908                         CHECK_STACK_OVF (1);
4909                         n = (*ip)-CEE_LDARG_0;
4910                         CHECK_ARG (n);
4911                         NEW_ARGLOAD (cfg, ins, n);
4912                         LDARG_SOFT_FLOAT (cfg, ins, n, ip);
4913                         ins->cil_code = ip++;
4914                         *sp++ = ins;
4915                         break;
4916                 case CEE_LDLOC_0:
4917                 case CEE_LDLOC_1:
4918                 case CEE_LDLOC_2:
4919                 case CEE_LDLOC_3:
4920                         CHECK_STACK_OVF (1);
4921                         n = (*ip)-CEE_LDLOC_0;
4922                         CHECK_LOCAL (n);
4923                         NEW_LOCLOAD (cfg, ins, n);
4924                         LDLOC_SOFT_FLOAT (cfg, ins, n, ip);
4925                         ins->cil_code = ip++;
4926                         *sp++ = ins;
4927                         break;
4928                 case CEE_STLOC_0:
4929                 case CEE_STLOC_1:
4930                 case CEE_STLOC_2:
4931                 case CEE_STLOC_3:
4932                         CHECK_STACK (1);
4933                         n = (*ip)-CEE_STLOC_0;
4934                         CHECK_LOCAL (n);
4935                         --sp;
4936                         handle_loaded_temps (cfg, bblock, stack_start, sp);
4937                         NEW_LOCSTORE (cfg, ins, n, *sp);
4938                         ins->cil_code = ip;
4939                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
4940                                 UNVERIFIED;
4941                         STLOC_SOFT_FLOAT (cfg, ins, n, ip);
4942                         if (ins->opcode == CEE_STOBJ) {
4943                                 NEW_LOCLOADA (cfg, ins, n);
4944                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
4945                         } else
4946                                 MONO_ADD_INS (bblock, ins);
4947                         ++ip;
4948                         inline_costs += 1;
4949                         break;
4950                 case CEE_LDARG_S:
4951                         CHECK_OPSIZE (2);
4952                         CHECK_STACK_OVF (1);
4953                         CHECK_ARG (ip [1]);
4954                         NEW_ARGLOAD (cfg, ins, ip [1]);
4955                         LDARG_SOFT_FLOAT (cfg, ins, ip [1], ip);
4956                         ins->cil_code = ip;
4957                         *sp++ = ins;
4958                         ip += 2;
4959                         break;
4960                 case CEE_LDARGA_S:
4961                         CHECK_OPSIZE (2);
4962                         CHECK_STACK_OVF (1);
4963                         CHECK_ARG (ip [1]);
4964                         NEW_ARGLOADA (cfg, ins, ip [1]);
4965                         ins->cil_code = ip;
4966                         *sp++ = ins;
4967                         ip += 2;
4968                         break;
4969                 case CEE_STARG_S:
4970                         CHECK_OPSIZE (2);
4971                         CHECK_STACK (1);
4972                         --sp;
4973                         CHECK_ARG (ip [1]);
4974                         NEW_ARGSTORE (cfg, ins, ip [1], *sp);
4975                         handle_loaded_temps (cfg, bblock, stack_start, sp);
4976                         ins->cil_code = ip;
4977                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [ip [1]], *sp))
4978                                 UNVERIFIED;
4979                         STARG_SOFT_FLOAT (cfg, ins, ip [1], ip);
4980                         if (ins->opcode == CEE_STOBJ) {
4981                                 NEW_ARGLOADA (cfg, ins, ip [1]);
4982                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
4983                         } else
4984                                 MONO_ADD_INS (bblock, ins);
4985                         ip += 2;
4986                         break;
4987                 case CEE_LDLOC_S:
4988                         CHECK_OPSIZE (2);
4989                         CHECK_STACK_OVF (1);
4990                         CHECK_LOCAL (ip [1]);
4991                         NEW_LOCLOAD (cfg, ins, ip [1]);
4992                         LDLOC_SOFT_FLOAT (cfg, ins, ip [1], ip);
4993                         ins->cil_code = ip;
4994                         *sp++ = ins;
4995                         ip += 2;
4996                         break;
4997                 case CEE_LDLOCA_S:
4998                         CHECK_OPSIZE (2);
4999                         CHECK_STACK_OVF (1);
5000                         CHECK_LOCAL (ip [1]);
5001                         NEW_LOCLOADA (cfg, ins, ip [1]);
5002                         ins->cil_code = ip;
5003                         *sp++ = ins;
5004                         ip += 2;
5005                         break;
5006                 case CEE_STLOC_S:
5007                         CHECK_OPSIZE (2);
5008                         CHECK_STACK (1);
5009                         --sp;
5010                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5011                         CHECK_LOCAL (ip [1]);
5012                         NEW_LOCSTORE (cfg, ins, ip [1], *sp);
5013                         ins->cil_code = ip;
5014                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [ip [1]], *sp))
5015                                 UNVERIFIED;
5016                         STLOC_SOFT_FLOAT (cfg, ins, ip [1], ip);
5017                         if (ins->opcode == CEE_STOBJ) {
5018                                 NEW_LOCLOADA (cfg, ins, ip [1]);
5019                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
5020                         } else
5021                                 MONO_ADD_INS (bblock, ins);
5022                         ip += 2;
5023                         inline_costs += 1;
5024                         break;
5025                 case CEE_LDNULL:
5026                         CHECK_STACK_OVF (1);
5027                         NEW_PCONST (cfg, ins, NULL);
5028                         ins->cil_code = ip;
5029                         ins->type = STACK_OBJ;
5030                         ++ip;
5031                         *sp++ = ins;
5032                         break;
5033                 case CEE_LDC_I4_M1:
5034                         CHECK_STACK_OVF (1);
5035                         NEW_ICONST (cfg, ins, -1);
5036                         ins->cil_code = ip;
5037                         ++ip;
5038                         *sp++ = ins;
5039                         break;
5040                 case CEE_LDC_I4_0:
5041                 case CEE_LDC_I4_1:
5042                 case CEE_LDC_I4_2:
5043                 case CEE_LDC_I4_3:
5044                 case CEE_LDC_I4_4:
5045                 case CEE_LDC_I4_5:
5046                 case CEE_LDC_I4_6:
5047                 case CEE_LDC_I4_7:
5048                 case CEE_LDC_I4_8:
5049                         CHECK_STACK_OVF (1);
5050                         NEW_ICONST (cfg, ins, (*ip) - CEE_LDC_I4_0);
5051                         ins->cil_code = ip;
5052                         ++ip;
5053                         *sp++ = ins;
5054                         break;
5055                 case CEE_LDC_I4_S:
5056                         CHECK_OPSIZE (2);
5057                         CHECK_STACK_OVF (1);
5058                         ++ip;
5059                         NEW_ICONST (cfg, ins, *((signed char*)ip));
5060                         ins->cil_code = ip;
5061                         ++ip;
5062                         *sp++ = ins;
5063                         break;
5064                 case CEE_LDC_I4:
5065                         CHECK_OPSIZE (5);
5066                         CHECK_STACK_OVF (1);
5067                         NEW_ICONST (cfg, ins, (gint32)read32 (ip + 1));
5068                         ins->cil_code = ip;
5069                         ip += 5;
5070                         *sp++ = ins;
5071                         break;
5072                 case CEE_LDC_I8:
5073                         CHECK_OPSIZE (9);
5074                         CHECK_STACK_OVF (1);
5075                         MONO_INST_NEW (cfg, ins, OP_I8CONST);
5076                         ins->cil_code = ip;
5077                         ins->type = STACK_I8;
5078                         ++ip;
5079                         ins->inst_l = (gint64)read64 (ip);
5080                         ip += 8;
5081                         *sp++ = ins;
5082                         break;
5083                 case CEE_LDC_R4: {
5084                         float *f;
5085                         /* we should really allocate this only late in the compilation process */
5086                         mono_domain_lock (cfg->domain);
5087                         f = mono_mempool_alloc (cfg->domain->mp, sizeof (float));
5088                         mono_domain_unlock (cfg->domain);
5089                         CHECK_OPSIZE (5);
5090                         CHECK_STACK_OVF (1);
5091                         MONO_INST_NEW (cfg, ins, OP_R4CONST);
5092                         ins->type = STACK_R8;
5093                         ++ip;
5094                         readr4 (ip, f);
5095                         ins->inst_p0 = f;
5096
5097                         ip += 4;
5098                         *sp++ = ins;                    
5099                         break;
5100                 }
5101                 case CEE_LDC_R8: {
5102                         double *d;
5103                         mono_domain_lock (cfg->domain);
5104                         d = mono_mempool_alloc (cfg->domain->mp, sizeof (double));
5105                         mono_domain_unlock (cfg->domain);
5106                         CHECK_OPSIZE (9);
5107                         CHECK_STACK_OVF (1);
5108                         MONO_INST_NEW (cfg, ins, OP_R8CONST);
5109                         ins->type = STACK_R8;
5110                         ++ip;
5111                         readr8 (ip, d);
5112                         ins->inst_p0 = d;
5113
5114                         ip += 8;
5115                         *sp++ = ins;                    
5116                         break;
5117                 }
5118                 case CEE_DUP: {
5119                         MonoInst *temp, *store;
5120                         CHECK_STACK (1);
5121                         CHECK_STACK_OVF (1);
5122                         sp--;
5123                         ins = *sp;
5124                 
5125                         /* 
5126                          * small optimization: if the loaded value was from a local already,
5127                          * just load it twice.
5128                          */
5129                         if (ins->ssa_op == MONO_SSA_LOAD && 
5130                             (ins->inst_i0->opcode == OP_LOCAL || ins->inst_i0->opcode == OP_ARG)) {
5131                                 sp++;
5132                                 MONO_INST_NEW (cfg, temp, 0);
5133                                 *temp = *ins;
5134                                 temp->cil_code = ip;
5135                                 *sp++ = temp;
5136                         } else {
5137                                 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
5138                                 temp->flags |= MONO_INST_IS_TEMP;
5139                                 temp->cil_code = ip;
5140                                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
5141                                 store->cil_code = ip;
5142                                 /* FIXME: handle CEE_STIND_R4 */
5143                                 if (store->opcode == CEE_STOBJ) {
5144                                         NEW_TEMPLOADA (cfg, store, temp->inst_c0);
5145                                         handle_stobj (cfg, bblock, store, sp [0], sp [0]->cil_code, store->klass, TRUE, FALSE, FALSE);
5146                                 } else {
5147                                         MONO_ADD_INS (bblock, store);
5148                                 }
5149                                 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
5150                                 *sp++ = ins;
5151                                 ins->cil_code = ip;
5152                                 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
5153                                 *sp++ = ins;
5154                                 ins->cil_code = ip;
5155                         }
5156                         ++ip;
5157                         inline_costs += 2;
5158                         break;
5159                 }
5160                 case CEE_POP:
5161                         CHECK_STACK (1);
5162                         MONO_INST_NEW (cfg, ins, CEE_POP);
5163                         MONO_ADD_INS (bblock, ins);
5164                         ins->cil_code = ip++;
5165                         --sp;
5166                         ins->inst_i0 = *sp;
5167                         break;
5168                 case CEE_JMP:
5169                         CHECK_OPSIZE (5);
5170                         if (stack_start != sp)
5171                                 UNVERIFIED;
5172                         MONO_INST_NEW (cfg, ins, OP_JMP);
5173                         token = read32 (ip + 1);
5174                         /* FIXME: check the signature matches */
5175                         cmethod = mini_get_method (method, token, NULL, generic_context);
5176
5177                         if (!cmethod)
5178                                 goto load_error;
5179
5180                         if (cfg->generic_sharing_context && mono_method_check_context_used (cmethod))
5181                                 GENERIC_SHARING_FAILURE (CEE_JMP);
5182
5183                         if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
5184                                 if (check_linkdemand (cfg, method, cmethod, bblock, ip))
5185                                         INLINE_FAILURE;
5186                                 CHECK_CFG_EXCEPTION;
5187                         }
5188
5189                         ins->inst_p0 = cmethod;
5190                         MONO_ADD_INS (bblock, ins);
5191                         ip += 5;
5192                         start_new_bblock = 1;
5193                         break;
5194                 case CEE_CALLI:
5195                 case CEE_CALL:
5196                 case CEE_CALLVIRT: {
5197                         MonoInst *addr = NULL;
5198                         MonoMethodSignature *fsig = NULL;
5199                         int temp, array_rank = 0;
5200                         int virtual = *ip == CEE_CALLVIRT;
5201                         gboolean no_spill;
5202
5203                         CHECK_OPSIZE (5);
5204                         token = read32 (ip + 1);
5205
5206                         if (*ip == CEE_CALLI) {
5207                                 cmethod = NULL;
5208                                 CHECK_STACK (1);
5209                                 --sp;
5210                                 addr = *sp;
5211                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
5212                                         fsig = (MonoMethodSignature *)mono_method_get_wrapper_data (method, token);
5213                                 else
5214                                         fsig = mono_metadata_parse_signature (image, token);
5215
5216                                 n = fsig->param_count + fsig->hasthis;
5217                         } else {
5218                                 MonoMethod *cil_method;
5219                                 
5220                                 if (method->wrapper_type != MONO_WRAPPER_NONE) {
5221                                         cmethod =  (MonoMethod *)mono_method_get_wrapper_data (method, token);
5222                                         cil_method = cmethod;
5223                                 } else if (constrained_call) {
5224                                         cmethod = mono_get_method_constrained (image, token, constrained_call, generic_context, &cil_method);
5225                                         cil_method = cmethod;
5226                                 } else {
5227                                         cmethod = mini_get_method (method, token, NULL, generic_context);
5228                                         cil_method = cmethod;
5229                                 }
5230
5231                                 if (!cmethod)
5232                                         goto load_error;
5233                                 if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_method (method, cil_method))
5234                                         METHOD_ACCESS_FAILURE;
5235
5236                                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
5237                                         ensure_method_is_allowed_to_call_method (cfg, method, cil_method, bblock, ip);
5238
5239                                 if (!virtual && (cmethod->flags & METHOD_ATTRIBUTE_ABSTRACT))
5240                                         /* MS.NET seems to silently convert this to a callvirt */
5241                                         virtual = 1;
5242
5243                                 if (!cmethod->klass->inited){
5244                                         if (!mono_class_init (cmethod->klass))
5245                                                 goto load_error;
5246                                 }
5247
5248                                 if (mono_method_signature (cmethod)->pinvoke) {
5249                                         MonoMethod *wrapper = mono_marshal_get_native_wrapper (cmethod, check_for_pending_exc);
5250                                         fsig = mono_method_signature (wrapper);
5251                                 } else if (constrained_call) {
5252                                         fsig = mono_method_signature (cmethod);
5253                                 } else {
5254                                         fsig = mono_method_get_signature_full (cmethod, image, token, generic_context);
5255                                 }
5256
5257                                 mono_save_token_info (cfg, image, token, cmethod);
5258
5259                                 n = fsig->param_count + fsig->hasthis;
5260
5261                                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
5262                                         if (check_linkdemand (cfg, method, cmethod, bblock, ip))
5263                                                 INLINE_FAILURE;
5264                                         CHECK_CFG_EXCEPTION;
5265                                 }
5266
5267                                 if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL &&
5268                                     mini_class_is_system_array (cmethod->klass)) {
5269                                         array_rank = cmethod->klass->rank;
5270                                 }
5271
5272                                 if (cmethod->string_ctor)
5273                                         g_assert_not_reached ();
5274
5275                         }
5276
5277                         if (!cfg->generic_sharing_context && cmethod && cmethod->klass->generic_container)
5278                                 UNVERIFIED;
5279
5280                         if (cfg->generic_sharing_context && cmethod && mono_method_check_context_used (cmethod))
5281                                 GENERIC_SHARING_FAILURE (*ip);
5282
5283                         CHECK_STACK (n);
5284
5285                         //g_assert (!virtual || fsig->hasthis);
5286
5287                         sp -= n;
5288
5289                         if (constrained_call) {
5290                                 /*
5291                                  * We have the `constrained.' prefix opcode.
5292                                  */
5293                                 if (constrained_call->valuetype && !cmethod->klass->valuetype) {
5294                                         MonoInst *load;
5295                                         /*
5296                                          * The type parameter is instantiated as a valuetype,
5297                                          * but that type doesn't override the method we're
5298                                          * calling, so we need to box `this'.
5299                                          * sp [0] is a pointer to the data: we need the value
5300                                          * in handle_box (), so load it here.
5301                                          */
5302                                         MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, &constrained_call->byval_arg));
5303                                         type_to_eval_stack_type (cfg, &constrained_call->byval_arg, load);
5304                                         load->cil_code = ip;
5305                                         load->inst_left = sp [0];
5306                                         sp [0] = handle_box (cfg, bblock, load, ip, constrained_call);
5307                                 } else if (!constrained_call->valuetype) {
5308                                         MonoInst *ins;
5309
5310                                         /*
5311                                          * The type parameter is instantiated as a reference
5312                                          * type.  We have a managed pointer on the stack, so
5313                                          * we need to dereference it here.
5314                                          */
5315
5316                                         MONO_INST_NEW (cfg, ins, CEE_LDIND_REF);
5317                                         ins->cil_code = ip;
5318                                         ins->inst_i0 = sp [0];
5319                                         ins->type = STACK_OBJ;
5320                                         ins->klass = mono_class_from_mono_type (&constrained_call->byval_arg);
5321                                         sp [0] = ins;
5322                                 } else if (cmethod->klass->valuetype)
5323                                         virtual = 0;
5324                                 constrained_call = NULL;
5325                         }
5326
5327                         if (*ip != CEE_CALLI && check_call_signature (cfg, fsig, sp))
5328                                 UNVERIFIED;
5329
5330                         if (cmethod && virtual && 
5331                             (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) && 
5332                             !((cmethod->flags & METHOD_ATTRIBUTE_FINAL) && 
5333                               cmethod->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK) &&
5334                             mono_method_signature (cmethod)->generic_param_count) {
5335                                 MonoInst *this_temp, *this_arg_temp, *store;
5336                                 MonoInst *iargs [4];
5337
5338                                 g_assert (mono_method_signature (cmethod)->is_inflated);
5339                                 /* Prevent inlining of methods that contain indirect calls */
5340                                 INLINE_FAILURE;
5341
5342                                 this_temp = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
5343                                 this_temp->cil_code = ip;
5344                                 NEW_TEMPSTORE (cfg, store, this_temp->inst_c0, sp [0]);
5345
5346                                 store->cil_code = ip;
5347                                 MONO_ADD_INS (bblock, store);
5348
5349                                 /* FIXME: This should be a managed pointer */
5350                                 this_arg_temp = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
5351                                 this_arg_temp->cil_code = ip;
5352
5353                                 /* Because of the PCONST below */
5354                                 cfg->disable_aot = TRUE;
5355                                 NEW_TEMPLOAD (cfg, iargs [0], this_temp->inst_c0);
5356                                 NEW_METHODCONST (cfg, iargs [1], cmethod);
5357                                 NEW_PCONST (cfg, iargs [2], mono_method_get_context (cmethod));
5358                                 NEW_TEMPLOADA (cfg, iargs [3], this_arg_temp->inst_c0);
5359                                 temp = mono_emit_jit_icall (cfg, bblock, mono_helper_compile_generic_method, iargs, ip);
5360
5361                                 NEW_TEMPLOAD (cfg, addr, temp);
5362                                 NEW_TEMPLOAD (cfg, sp [0], this_arg_temp->inst_c0);
5363
5364                                 if ((temp = mono_emit_calli_spilled (cfg, bblock, fsig, sp, addr, ip)) != -1) {
5365                                         NEW_TEMPLOAD (cfg, *sp, temp);
5366                                         sp++;
5367                                 }
5368
5369                                 ip += 5;
5370                                 ins_flag = 0;
5371                                 break;
5372                         }
5373
5374                         if ((ins_flag & MONO_INST_TAILCALL) && cmethod && (*ip == CEE_CALL) &&
5375                                  (mono_metadata_signature_equal (mono_method_signature (method), mono_method_signature (cmethod)))) {
5376                                 int i;
5377
5378                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
5379                                 INLINE_FAILURE;
5380                                 /* FIXME: This assumes the two methods has the same number and type of arguments */
5381                                 /*
5382                                  * We implement tail calls by storing the actual arguments into the 
5383                                  * argument variables, then emitting a OP_JMP. Since the actual arguments
5384                                  * can refer to the arg variables, we have to spill them.
5385                                  */
5386                                 handle_loaded_temps (cfg, bblock, sp, sp + n);
5387                                 for (i = 0; i < n; ++i) {
5388                                         /* Prevent argument from being register allocated */
5389                                         arg_array [i]->flags |= MONO_INST_VOLATILE;
5390
5391                                         /* Check if argument is the same */
5392                                         /* 
5393                                          * FIXME: This loses liveness info, so it can only be done if the
5394                                          * argument is not register allocated.
5395                                          */
5396                                         NEW_ARGLOAD (cfg, ins, i);
5397                                         if ((ins->opcode == sp [i]->opcode) && (ins->inst_i0 == sp [i]->inst_i0))
5398                                                 continue;
5399
5400                                         NEW_ARGSTORE (cfg, ins, i, sp [i]);
5401                                         ins->cil_code = ip;
5402                                         /* FIXME: handle CEE_STIND_R4 */
5403                                         if (ins->opcode == CEE_STOBJ) {
5404                                                 NEW_ARGLOADA (cfg, ins, i);
5405                                                 handle_stobj (cfg, bblock, ins, sp [i], sp [i]->cil_code, ins->klass, FALSE, FALSE, FALSE);
5406                                         }
5407                                         else
5408                                                 MONO_ADD_INS (bblock, ins);
5409                                 }
5410                                 MONO_INST_NEW (cfg, ins, OP_JMP);
5411                                 ins->cil_code = ip;
5412                                 ins->inst_p0 = cmethod;
5413                                 ins->inst_p1 = arg_array [0];
5414                                 MONO_ADD_INS (bblock, ins);
5415                                 link_bblock (cfg, bblock, end_bblock);                  
5416                                 start_new_bblock = 1;
5417                                 /* skip CEE_RET as well */
5418                                 ip += 6;
5419                                 ins_flag = 0;
5420                                 break;
5421                         }
5422                         if (cmethod && (cfg->opt & MONO_OPT_INTRINS) && (ins = mini_get_inst_for_method (cfg, cmethod, fsig, sp))) {
5423                                 ins->cil_code = ip;
5424
5425                                 if (MONO_TYPE_IS_VOID (fsig->ret)) {
5426                                         MONO_ADD_INS (bblock, ins);
5427                                 } else {
5428                                         type_to_eval_stack_type (cfg, fsig->ret, ins);
5429                                         *sp = ins;
5430                                         sp++;
5431                                 }
5432
5433                                 ip += 5;
5434                                 ins_flag = 0;
5435                                 break;
5436                         }
5437
5438                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5439
5440                         if ((cfg->opt & MONO_OPT_INLINE) && cmethod &&
5441                             (!virtual || !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) || (cmethod->flags & METHOD_ATTRIBUTE_FINAL)) && 
5442                             mono_method_check_inlining (cfg, cmethod) &&
5443                                  !g_list_find (dont_inline, cmethod)) {
5444                                 int costs;
5445                                 MonoBasicBlock *ebblock;
5446                                 gboolean allways = FALSE;
5447
5448                                 if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
5449                                         (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5450                                         /* Prevent inlining of methods that call wrappers */
5451                                         INLINE_FAILURE;
5452                                         cmethod = mono_marshal_get_native_wrapper (cmethod, check_for_pending_exc);
5453                                         allways = TRUE;
5454                                 }
5455
5456                                 if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock, allways))) {
5457                                         ip += 5;
5458                                         real_offset += 5;
5459
5460                                         GET_BBLOCK (cfg, bblock, ip);
5461                                         ebblock->next_bb = bblock;
5462                                         link_bblock (cfg, ebblock, bblock);
5463
5464                                         if (!MONO_TYPE_IS_VOID (fsig->ret))
5465                                                 sp++;
5466
5467                                         /* indicates start of a new block, and triggers a load of all 
5468                                            stack arguments at bb boundarie */
5469                                         bblock = ebblock;
5470
5471                                         inline_costs += costs;
5472                                         ins_flag = 0;
5473                                         break;
5474                                 }
5475                         }
5476                         
5477                         inline_costs += 10 * num_calls++;
5478
5479                         /* tail recursion elimination */
5480                         if ((cfg->opt & MONO_OPT_TAILC) && *ip == CEE_CALL && cmethod == method && ip [5] == CEE_RET) {
5481                                 gboolean has_vtargs = FALSE;
5482                                 int i;
5483                                 
5484                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
5485                                 INLINE_FAILURE;
5486                                 /* keep it simple */
5487                                 for (i =  fsig->param_count - 1; i >= 0; i--) {
5488                                         if (MONO_TYPE_ISSTRUCT (mono_method_signature (cmethod)->params [i])) 
5489                                                 has_vtargs = TRUE;
5490                                 }
5491
5492                                 if (!has_vtargs) {
5493                                         for (i = 0; i < n; ++i) {
5494                                                 /* FIXME: handle CEE_STIND_R4 */
5495                                                 NEW_ARGSTORE (cfg, ins, i, sp [i]);
5496                                                 ins->cil_code = ip;
5497                                                 MONO_ADD_INS (bblock, ins);
5498                                         }
5499                                         MONO_INST_NEW (cfg, ins, OP_BR);
5500                                         ins->cil_code = ip;
5501                                         MONO_ADD_INS (bblock, ins);
5502                                         tblock = start_bblock->out_bb [0];
5503                                         link_bblock (cfg, bblock, tblock);
5504                                         ins->inst_target_bb = tblock;
5505                                         start_new_bblock = 1;
5506
5507                                         /* skip the CEE_RET, too */
5508                                         if (ip_in_bb (cfg, bblock, ip + 5))
5509                                                 ip += 6;
5510                                         else
5511                                                 ip += 5;
5512                                         ins_flag = 0;
5513                                         break;
5514                                 }
5515                         }
5516
5517                         if (ip_in_bb (cfg, bblock, ip + 5) 
5518                                 && (!MONO_TYPE_ISSTRUCT (fsig->ret))
5519                                 && (!MONO_TYPE_IS_VOID (fsig->ret) || (cmethod && cmethod->string_ctor))
5520                                 && (CODE_IS_STLOC (ip + 5) || ip [5] == CEE_POP || ip [5] == CEE_RET))
5521                                 /* No need to spill */
5522                                 no_spill = TRUE;
5523                         else
5524                                 no_spill = FALSE;
5525
5526                         if (*ip == CEE_CALLI) {
5527                                 /* Prevent inlining of methods with indirect calls */
5528                                 INLINE_FAILURE;
5529                                 if (no_spill) {
5530                                         ins = (MonoInst*)mono_emit_calli (cfg, bblock, fsig, sp, addr, ip);
5531                                         *sp++ = ins;                                    
5532                                 } else {
5533                                         if ((temp = mono_emit_calli_spilled (cfg, bblock, fsig, sp, addr, ip)) != -1) {
5534                                                 NEW_TEMPLOAD (cfg, *sp, temp);
5535                                                 sp++;
5536                                         }
5537                                 }                       
5538                         } else if (array_rank) {
5539                                 MonoInst *addr;
5540
5541                                 if (strcmp (cmethod->name, "Set") == 0) { /* array Set */ 
5542                                         if (sp [fsig->param_count]->type == STACK_OBJ) {
5543                                                 MonoInst *iargs [2];
5544                                                 MonoInst *array, *to_store, *store;
5545
5546                                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
5547                                                 
5548                                                 array = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
5549                                                 NEW_TEMPSTORE (cfg, store, array->inst_c0, sp [0]);
5550                                                 store->cil_code = ip;
5551                                                 MONO_ADD_INS (bblock, store);
5552                                                 NEW_TEMPLOAD (cfg, iargs [0], array->inst_c0);
5553
5554                                                 to_store = mono_compile_create_var (cfg, type_from_stack_type (sp [fsig->param_count]), OP_LOCAL);
5555                                                 NEW_TEMPSTORE (cfg, store, to_store->inst_c0, sp [fsig->param_count]);
5556                                                 /* FIXME: handle CEE_STIND_R4 */
5557                                                 store->cil_code = ip;
5558                                                 MONO_ADD_INS (bblock, store);
5559                                                 NEW_TEMPLOAD (cfg, iargs [1], to_store->inst_c0);
5560
5561                                                 /*
5562                                                  * We first save the args for the call so that the args are copied to the stack
5563                                                  * and a new instruction tree for them is created. If we don't do this,
5564                                                  * the same MonoInst is added to two different trees and this is not 
5565                                                  * allowed by burg.
5566                                                  */
5567                                                 mono_emit_jit_icall (cfg, bblock, mono_helper_stelem_ref_check, iargs, ip);
5568
5569                                                 NEW_TEMPLOAD (cfg, sp [0], array->inst_c0);
5570                                                 NEW_TEMPLOAD (cfg, sp [fsig->param_count], to_store->inst_c0);
5571                                         }
5572
5573                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, TRUE);
5574                                         NEW_INDSTORE (cfg, ins, addr, sp [fsig->param_count], fsig->params [fsig->param_count - 1]);
5575                                         ins->cil_code = ip;
5576                                         /* FIXME: handle CEE_STIND_R4 */
5577                                         if (ins->opcode == CEE_STOBJ) {
5578                                                 handle_stobj (cfg, bblock, addr, sp [fsig->param_count], ip, mono_class_from_mono_type (fsig->params [fsig->param_count-1]), FALSE, FALSE, TRUE);
5579                                         } else {
5580                                                 MONO_ADD_INS (bblock, ins);
5581                                         }
5582
5583                                 } else if (strcmp (cmethod->name, "Get") == 0) { /* array Get */
5584                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
5585                                         NEW_INDLOAD (cfg, ins, addr, fsig->ret);
5586                                         ins->cil_code = ip;
5587
5588                                         *sp++ = ins;
5589                                 } else if (strcmp (cmethod->name, "Address") == 0) { /* array Address */
5590                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
5591                                         *sp++ = addr;
5592                                 } else {
5593                                         g_assert_not_reached ();
5594                                 }
5595
5596                         } else {
5597                                 /* Prevent inlining of methods which call other methods */
5598                                 INLINE_FAILURE;
5599                                 if (mini_redirect_call (&temp, cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL)) {
5600                                         if (temp != -1) {
5601                                                 NEW_TEMPLOAD (cfg, *sp, temp);
5602                                                 sp++;
5603                                         }
5604                                 } else if (no_spill) {
5605                                         ins = (MonoInst*)mono_emit_method_call (cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL);
5606                                         *sp++ = ins;
5607                                 } else {
5608                                         if ((temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL)) != -1) {
5609                                                 MonoInst *load;
5610                                                 NEW_TEMPLOAD (cfg, load, temp);
5611
5612 #ifdef MONO_ARCH_SOFT_FLOAT
5613                                                 if (load->opcode == CEE_LDIND_R4) {
5614                                                         NEW_TEMPLOADA (cfg, load, temp);
5615                                                         temp = handle_load_float (cfg, bblock, load, ip);
5616                                                         NEW_TEMPLOAD (cfg, load, temp);
5617                                                 }
5618 #endif
5619                                                 *sp++ = load;
5620                                         }
5621                                 }
5622                         }
5623
5624                         ip += 5;
5625                         ins_flag = 0;
5626                         break;
5627                 }
5628                 case CEE_RET:
5629                         if (cfg->method != method) {
5630                                 /* return from inlined method */
5631                                 if (return_var) {
5632                                         MonoInst *store;
5633                                         CHECK_STACK (1);
5634                                         --sp;
5635                                         //g_assert (returnvar != -1);
5636                                         NEW_TEMPSTORE (cfg, store, return_var->inst_c0, *sp);
5637                                         store->cil_code = sp [0]->cil_code;
5638                                         /* FIXME: handle CEE_STIND_R4 */
5639                                         if (store->opcode == CEE_STOBJ) {
5640                                                 g_assert_not_reached ();
5641                                                 NEW_TEMPLOADA (cfg, store, return_var->inst_c0);
5642                                                 /* FIXME: it is possible some optimization will pass the a heap pointer for the struct address, so we'll need the write barrier */
5643                                                 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, return_var->klass, FALSE, FALSE, FALSE);
5644 #ifdef MONO_ARCH_SOFT_FLOAT
5645                                         } else if (store->opcode == CEE_STIND_R4) {
5646                                                 NEW_TEMPLOADA (cfg, store, return_var->inst_c0);
5647                                                 handle_store_float (cfg, bblock, store, *sp, sp [0]->cil_code);
5648 #endif
5649                                         } else
5650                                                 MONO_ADD_INS (bblock, store);
5651                                 } 
5652                         } else {
5653                                 if (cfg->ret) {
5654                                         g_assert (!return_var);
5655                                         CHECK_STACK (1);
5656                                         --sp;
5657                                         MONO_INST_NEW (cfg, ins, OP_NOP);
5658                                         ins->opcode = mini_type_to_stind (cfg, mono_method_signature (method)->ret);
5659                                         if (ins->opcode == CEE_STOBJ) {
5660                                                 NEW_RETLOADA (cfg, ins);
5661                                                 /* FIXME: it is possible some optimization will pass the a heap pointer for the struct address, so we'll need the write barrier */
5662                                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
5663                                         } else {
5664                                                 ins->opcode = OP_SETRET;
5665                                                 ins->cil_code = ip;
5666                                                 ins->inst_i0 = *sp;;
5667                                                 ins->inst_i1 = NULL;
5668                                                 MONO_ADD_INS (bblock, ins);
5669                                         }
5670                                 }
5671                         }
5672                         if (sp != stack_start)
5673                                 UNVERIFIED;
5674                         MONO_INST_NEW (cfg, ins, OP_BR);
5675                         ins->cil_code = ip++;
5676                         ins->inst_target_bb = end_bblock;
5677                         MONO_ADD_INS (bblock, ins);
5678                         link_bblock (cfg, bblock, end_bblock);
5679                         start_new_bblock = 1;
5680                         break;
5681                 case CEE_BR_S:
5682                         CHECK_OPSIZE (2);
5683                         MONO_INST_NEW (cfg, ins, OP_BR);
5684                         ins->cil_code = ip++;
5685                         MONO_ADD_INS (bblock, ins);
5686                         target = ip + 1 + (signed char)(*ip);
5687                         ++ip;
5688                         GET_BBLOCK (cfg, tblock, target);
5689                         link_bblock (cfg, bblock, tblock);
5690                         CHECK_BBLOCK (target, ip, tblock);
5691                         ins->inst_target_bb = tblock;
5692                         if (sp != stack_start) {
5693                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5694                                 sp = stack_start;
5695                                 CHECK_UNVERIFIABLE (cfg);
5696                         }
5697                         start_new_bblock = 1;
5698                         inline_costs += BRANCH_COST;
5699                         break;
5700                 case CEE_BRFALSE_S:
5701                 case CEE_BRTRUE_S:
5702                         CHECK_OPSIZE (2);
5703                         CHECK_STACK (1);
5704                         if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
5705                                 UNVERIFIED;
5706                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
5707                         ins->cil_code = ip++;
5708                         target = ip + 1 + *(signed char*)ip;
5709                         ip++;
5710                         ADD_UNCOND (ins->opcode == CEE_BRTRUE);
5711                         if (sp != stack_start) {
5712                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5713                                 sp = stack_start;
5714                                 CHECK_UNVERIFIABLE (cfg);
5715                         }
5716                         inline_costs += BRANCH_COST;
5717                         break;
5718                 case CEE_BEQ_S:
5719                 case CEE_BGE_S:
5720                 case CEE_BGT_S:
5721                 case CEE_BLE_S:
5722                 case CEE_BLT_S:
5723                 case CEE_BNE_UN_S:
5724                 case CEE_BGE_UN_S:
5725                 case CEE_BGT_UN_S:
5726                 case CEE_BLE_UN_S:
5727                 case CEE_BLT_UN_S:
5728                         CHECK_OPSIZE (2);
5729                         CHECK_STACK (2);
5730                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
5731                         ins->cil_code = ip++;
5732                         target = ip + 1 + *(signed char*)ip;
5733                         ip++;
5734 #ifdef MONO_ARCH_SOFT_FLOAT
5735                         if (sp [-1]->type == STACK_R8 || sp [-2]->type == STACK_R8) {
5736                                 ins->opcode = condbr_to_fp_br (ins->opcode);
5737                                 sp -= 2;
5738                                 ins->inst_left = sp [0];
5739                                 ins->inst_right = sp [1];
5740                                 ins->type = STACK_I4;
5741                                 *sp++ = emit_tree (cfg, bblock, ins, ins->cil_code);
5742                                 MONO_INST_NEW (cfg, ins, CEE_BRTRUE);
5743                                 ADD_UNCOND (TRUE);
5744                         } else {
5745                                 ADD_BINCOND (NULL);
5746                         }
5747 #else
5748                         ADD_BINCOND (NULL);
5749 #endif
5750                         if (sp != stack_start) {
5751                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5752                                 sp = stack_start;
5753                                 CHECK_UNVERIFIABLE (cfg);
5754                         }
5755                         inline_costs += BRANCH_COST;
5756                         break;
5757                 case CEE_BR:
5758                         CHECK_OPSIZE (5);
5759                         MONO_INST_NEW (cfg, ins, OP_BR);
5760                         ins->cil_code = ip++;
5761                         MONO_ADD_INS (bblock, ins);
5762                         target = ip + 4 + (gint32)read32(ip);
5763                         ip += 4;
5764                         GET_BBLOCK (cfg, tblock, target);
5765                         link_bblock (cfg, bblock, tblock);
5766                         CHECK_BBLOCK (target, ip, tblock);
5767                         ins->inst_target_bb = tblock;
5768                         if (sp != stack_start) {
5769                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5770                                 sp = stack_start;
5771                                 CHECK_UNVERIFIABLE (cfg);
5772                         }
5773                         start_new_bblock = 1;
5774                         inline_costs += BRANCH_COST;
5775                         break;
5776                 case CEE_BRFALSE:
5777                 case CEE_BRTRUE:
5778                         CHECK_OPSIZE (5);
5779                         CHECK_STACK (1);
5780                         if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
5781                                 UNVERIFIED;
5782                         MONO_INST_NEW (cfg, ins, *ip);
5783                         ins->cil_code = ip++;
5784                         target = ip + 4 + (gint32)read32(ip);
5785                         ip += 4;
5786                         ADD_UNCOND(ins->opcode == CEE_BRTRUE);
5787                         if (sp != stack_start) {
5788                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5789                                 sp = stack_start;
5790                                 CHECK_UNVERIFIABLE (cfg);
5791                         }
5792                         inline_costs += BRANCH_COST;
5793                         break;
5794                 case CEE_BEQ:
5795                 case CEE_BGE:
5796                 case CEE_BGT:
5797                 case CEE_BLE:
5798                 case CEE_BLT:
5799                 case CEE_BNE_UN:
5800                 case CEE_BGE_UN:
5801                 case CEE_BGT_UN:
5802                 case CEE_BLE_UN:
5803                 case CEE_BLT_UN:
5804                         CHECK_OPSIZE (5);
5805                         CHECK_STACK (2);
5806                         MONO_INST_NEW (cfg, ins, *ip);
5807                         ins->cil_code = ip++;
5808                         target = ip + 4 + (gint32)read32(ip);
5809                         ip += 4;
5810 #ifdef MONO_ARCH_SOFT_FLOAT
5811                         if (sp [-1]->type == STACK_R8 || sp [-2]->type == STACK_R8) {
5812                                 ins->opcode = condbr_to_fp_br (ins->opcode);
5813                                 sp -= 2;
5814                                 ins->inst_left = sp [0];
5815                                 ins->inst_right = sp [1];
5816                                 ins->type = STACK_I4;
5817                                 *sp++ = emit_tree (cfg, bblock, ins, ins->cil_code);
5818                                 MONO_INST_NEW (cfg, ins, CEE_BRTRUE);
5819                                 ADD_UNCOND (TRUE);
5820                         } else {
5821                                 ADD_BINCOND (NULL);
5822                         }
5823 #else
5824                         ADD_BINCOND (NULL);
5825 #endif
5826                         if (sp != stack_start) {
5827                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5828                                 sp = stack_start;
5829                                 CHECK_UNVERIFIABLE (cfg);
5830                         }
5831                         inline_costs += BRANCH_COST;
5832                         break;
5833                 case CEE_SWITCH:
5834                         CHECK_OPSIZE (5);
5835                         CHECK_STACK (1);
5836                         n = read32 (ip + 1);
5837                         MONO_INST_NEW (cfg, ins, OP_SWITCH);
5838                         --sp;
5839                         ins->inst_left = *sp;
5840                         if ((ins->inst_left->type != STACK_I4) && (ins->inst_left->type != STACK_PTR)) 
5841                                 UNVERIFIED;
5842                         ins->cil_code = ip;
5843                         ip += 5;
5844                         CHECK_OPSIZE (n * sizeof (guint32));
5845                         target = ip + n * sizeof (guint32);
5846                         MONO_ADD_INS (bblock, ins);
5847                         GET_BBLOCK (cfg, tblock, target);
5848                         link_bblock (cfg, bblock, tblock);
5849                         ins->klass = GUINT_TO_POINTER (n);
5850                         ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (n + 1));
5851                         ins->inst_many_bb [n] = tblock;
5852
5853                         for (i = 0; i < n; ++i) {
5854                                 GET_BBLOCK (cfg, tblock, target + (gint32)read32(ip));
5855                                 link_bblock (cfg, bblock, tblock);
5856                                 ins->inst_many_bb [i] = tblock;
5857                                 ip += 4;
5858                         }
5859                         if (sp != stack_start) {
5860                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5861                                 sp = stack_start;
5862                                 CHECK_UNVERIFIABLE (cfg);
5863                         }
5864                         /* Needed by the code generated in inssel.brg */
5865                         mono_get_got_var (cfg);
5866                         inline_costs += (BRANCH_COST * 2);
5867                         break;
5868                 case CEE_LDIND_I1:
5869                 case CEE_LDIND_U1:
5870                 case CEE_LDIND_I2:
5871                 case CEE_LDIND_U2:
5872                 case CEE_LDIND_I4:
5873                 case CEE_LDIND_U4:
5874                 case CEE_LDIND_I8:
5875                 case CEE_LDIND_I:
5876                 case CEE_LDIND_R4:
5877                 case CEE_LDIND_R8:
5878                 case CEE_LDIND_REF:
5879                         CHECK_STACK (1);
5880                         MONO_INST_NEW (cfg, ins, *ip);
5881                         ins->cil_code = ip;
5882                         --sp;
5883                         ins->inst_i0 = *sp;
5884                         *sp++ = ins;
5885                         ins->type = ldind_type [*ip - CEE_LDIND_I1];
5886                         ins->flags |= ins_flag;
5887                         ins_flag = 0;
5888                         if (ins->type == STACK_OBJ)
5889                                 ins->klass = mono_defaults.object_class;
5890 #ifdef MONO_ARCH_SOFT_FLOAT
5891                         if (*ip == CEE_LDIND_R4) {
5892                                 int temp;
5893                                 --sp;
5894                                 temp = handle_load_float (cfg, bblock, ins->inst_i0, ip);
5895                                 NEW_TEMPLOAD (cfg, *sp, temp);
5896                                 sp++;
5897                         }
5898 #endif
5899                         ++ip;
5900                         break;
5901                 case CEE_STIND_REF:
5902                 case CEE_STIND_I1:
5903                 case CEE_STIND_I2:
5904                 case CEE_STIND_I4:
5905                 case CEE_STIND_I8:
5906                 case CEE_STIND_R4:
5907                 case CEE_STIND_R8:
5908                         CHECK_STACK (2);
5909 #ifdef MONO_ARCH_SOFT_FLOAT
5910                         if (*ip == CEE_STIND_R4) {
5911                                 sp -= 2;
5912                                 handle_store_float (cfg, bblock, sp [0], sp [1], ip);
5913                                 ip++;
5914                                 break;
5915                         }
5916 #endif
5917 #if HAVE_WRITE_BARRIERS
5918                         if (*ip == CEE_STIND_REF && method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER && !((sp [-1]->opcode == OP_PCONST) && (sp [-1]->inst_p0 == 0))) {
5919                                 /* insert call to write barrier */
5920                                 MonoMethod *write_barrier = mono_marshal_get_write_barrier ();
5921                                 sp -= 2;
5922                                 mono_emit_method_call_spilled (cfg, bblock, write_barrier, mono_method_signature (write_barrier), sp, ip, NULL);
5923                                 ip++;
5924                                 break;
5925                         }
5926 #endif
5927                         MONO_INST_NEW (cfg, ins, *ip);
5928                         ins->cil_code = ip++;
5929                         sp -= 2;
5930                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5931                         MONO_ADD_INS (bblock, ins);
5932                         ins->inst_i0 = sp [0];
5933                         ins->inst_i1 = sp [1];
5934                         ins->flags |= ins_flag;
5935                         ins_flag = 0;
5936                         inline_costs += 1;
5937                         break;
5938                 case CEE_MUL:
5939                         CHECK_STACK (2);
5940                         ADD_BINOP (*ip);
5941
5942 #ifdef MONO_ARCH_NO_EMULATE_MUL_IMM
5943                         /* FIXME: This breaks with ssapre (mono -O=ssapre loader.exe) */
5944                         if ((ins->inst_right->opcode == OP_ICONST) && !(cfg->opt & MONO_OPT_SSAPRE)) {
5945                                 switch (ins->opcode) {
5946                                 case CEE_MUL:
5947                                         ins->opcode = OP_IMUL_IMM;
5948                                         ins->inst_imm = ins->inst_right->inst_c0;
5949                                         break;
5950                                 case OP_LMUL:
5951                                         ins->opcode = OP_LMUL_IMM;
5952                                         ins->inst_imm = ins->inst_right->inst_c0;
5953                                         break;
5954                                 default:
5955                                         g_assert_not_reached ();
5956                                 }
5957                         }
5958 #endif
5959
5960                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
5961                                 --sp;
5962                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
5963                         }
5964                         ip++;
5965                         break;
5966                 case CEE_ADD:
5967                 case CEE_SUB:
5968                 case CEE_DIV:
5969                 case CEE_DIV_UN:
5970                 case CEE_REM:
5971                 case CEE_REM_UN:
5972                 case CEE_AND:
5973                 case CEE_OR:
5974                 case CEE_XOR:
5975                 case CEE_SHL:
5976                 case CEE_SHR:
5977                 case CEE_SHR_UN:
5978                         CHECK_STACK (2);
5979                         ADD_BINOP (*ip);
5980                         /* special case that gives a nice speedup and happens to workaorund a ppc jit but (for the release)
5981                          * later apply the speedup to the left shift as well
5982                          * See BUG# 57957.
5983                          */
5984                         if ((ins->opcode == OP_LSHR_UN) && (ins->type == STACK_I8) 
5985                                         && (ins->inst_right->opcode == OP_ICONST) && (ins->inst_right->inst_c0 == 32)) {
5986                                 ins->opcode = OP_LONG_SHRUN_32;
5987                                 /*g_print ("applied long shr speedup to %s\n", cfg->method->name);*/
5988                                 ip++;
5989                                 break;
5990                         }
5991                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
5992                                 --sp;
5993                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
5994                         }
5995                         ip++;
5996                         break;
5997                 case CEE_NEG:
5998                 case CEE_NOT:
5999                 case CEE_CONV_I1:
6000                 case CEE_CONV_I2:
6001                 case CEE_CONV_I4:
6002                 case CEE_CONV_R4:
6003                 case CEE_CONV_R8:
6004                 case CEE_CONV_U4:
6005                 case CEE_CONV_I8:
6006                 case CEE_CONV_U8:
6007                 case CEE_CONV_OVF_I8:
6008                 case CEE_CONV_OVF_U8:
6009                 case CEE_CONV_R_UN:
6010                         CHECK_STACK (1);
6011                         ADD_UNOP (*ip);
6012                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
6013                                 --sp;
6014                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
6015                         }
6016                         ip++;                   
6017                         break;
6018                 case CEE_CONV_OVF_I4:
6019                 case CEE_CONV_OVF_I1:
6020                 case CEE_CONV_OVF_I2:
6021                 case CEE_CONV_OVF_I:
6022                 case CEE_CONV_OVF_U:
6023                         CHECK_STACK (1);
6024
6025                         if (sp [-1]->type == STACK_R8) {
6026                                 ADD_UNOP (CEE_CONV_OVF_I8);
6027                                 ADD_UNOP (*ip);
6028                         } else {
6029                                 ADD_UNOP (*ip);
6030                         }
6031
6032                         ip++;
6033                         break;
6034                 case CEE_CONV_OVF_U1:
6035                 case CEE_CONV_OVF_U2:
6036                 case CEE_CONV_OVF_U4:
6037                         CHECK_STACK (1);
6038
6039                         if (sp [-1]->type == STACK_R8) {
6040                                 ADD_UNOP (CEE_CONV_OVF_U8);
6041                                 ADD_UNOP (*ip);
6042                         } else {
6043                                 ADD_UNOP (*ip);
6044                         }
6045
6046                         ip++;
6047                         break;
6048                 case CEE_CONV_OVF_I1_UN:
6049                 case CEE_CONV_OVF_I2_UN:
6050                 case CEE_CONV_OVF_I4_UN:
6051                 case CEE_CONV_OVF_I8_UN:
6052                 case CEE_CONV_OVF_U1_UN:
6053                 case CEE_CONV_OVF_U2_UN:
6054                 case CEE_CONV_OVF_U4_UN:
6055                 case CEE_CONV_OVF_U8_UN:
6056                 case CEE_CONV_OVF_I_UN:
6057                 case CEE_CONV_OVF_U_UN:
6058                         CHECK_STACK (1);
6059                         ADD_UNOP (*ip);
6060                         ip++;
6061                         break;
6062                 case CEE_CPOBJ:
6063                         CHECK_OPSIZE (5);
6064                         CHECK_STACK (2);
6065                         token = read32 (ip + 1);
6066                         klass = mini_get_class (method, token, generic_context);
6067                         CHECK_TYPELOAD (klass);
6068                         sp -= 2;
6069                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
6070                                 MonoInst *store, *load;
6071                                 MONO_INST_NEW (cfg, load, CEE_LDIND_REF);
6072                                 load->cil_code = ip;
6073                                 load->inst_i0 = sp [1];
6074                                 load->type = STACK_OBJ;
6075                                 load->klass = klass;
6076                                 load->flags |= ins_flag;
6077                                 MONO_INST_NEW (cfg, store, CEE_STIND_REF);
6078                                 store->cil_code = ip;
6079                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
6080                                 MONO_ADD_INS (bblock, store);
6081                                 store->inst_i0 = sp [0];
6082                                 store->inst_i1 = load;
6083                                 store->flags |= ins_flag;
6084                         } else {
6085                                 guint32 align;
6086
6087                                 n = mono_class_value_size (klass, &align);
6088                                 if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
6089                                         MonoInst *copy;
6090                                         NEW_MEMCPY (cfg, copy, sp [0], sp [1], n, align);
6091                                         MONO_ADD_INS (bblock, copy);
6092                                 } else {
6093                                         MonoMethod *memcpy_method = get_memcpy_method ();
6094                                         MonoInst *iargs [3];
6095                                         iargs [0] = sp [0];
6096                                         iargs [1] = sp [1];
6097                                         NEW_ICONST (cfg, iargs [2], n);
6098                                         iargs [2]->cil_code = ip;
6099
6100                                         mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
6101                                 }
6102                         }
6103                         ins_flag = 0;
6104                         ip += 5;
6105                         break;
6106                 case CEE_LDOBJ: {
6107                         MonoInst *iargs [3];
6108                         int loc_index = -1;
6109                         int stloc_len = 0;
6110                         guint32 align;
6111
6112                         CHECK_OPSIZE (5);
6113                         CHECK_STACK (1);
6114                         --sp;
6115                         token = read32 (ip + 1);
6116                         klass = mini_get_class (method, token, generic_context);
6117                         CHECK_TYPELOAD (klass);
6118                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
6119                                 MONO_INST_NEW (cfg, ins, CEE_LDIND_REF);
6120                                 ins->cil_code = ip;
6121                                 ins->inst_i0 = sp [0];
6122                                 ins->type = STACK_OBJ;
6123                                 ins->klass = klass;
6124                                 ins->flags |= ins_flag;
6125                                 ins_flag = 0;
6126                                 *sp++ = ins;
6127                                 ip += 5;
6128                                 break;
6129                         }
6130
6131                         /* Optimize the common ldobj+stloc combination */
6132                         switch (ip [5]) {
6133                         case CEE_STLOC_S:
6134                                 loc_index = ip [6];
6135                                 stloc_len = 2;
6136                                 break;
6137                         case CEE_STLOC_0:
6138                         case CEE_STLOC_1:
6139                         case CEE_STLOC_2:
6140                         case CEE_STLOC_3:
6141                                 loc_index = ip [5] - CEE_STLOC_0;
6142                                 stloc_len = 1;
6143                                 break;
6144                         default:
6145                                 break;
6146                         }
6147
6148                         if ((loc_index != -1) && ip_in_bb (cfg, bblock, ip + 5)) {
6149                                 CHECK_LOCAL (loc_index);
6150                                 NEW_LOCSTORE (cfg, ins, loc_index, *sp);
6151
6152                                 /* FIXME: handle CEE_STIND_R4 */
6153                                 if (ins->opcode == CEE_STOBJ) {
6154                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
6155                                         ins->cil_code = ip;
6156                                         g_assert (ins->opcode == CEE_STOBJ);
6157                                         NEW_LOCLOADA (cfg, ins, loc_index);
6158                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
6159                                         ip += 5;
6160                                         ip += stloc_len;
6161                                         break;
6162                                 }
6163                         }
6164
6165                         n = mono_class_value_size (klass, &align);
6166                         ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
6167                         NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
6168                         if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
6169                                 MonoInst *copy;
6170                                 NEW_MEMCPY (cfg, copy, iargs [0], *sp, n, align);
6171                                 MONO_ADD_INS (bblock, copy);
6172                         } else {
6173                                 MonoMethod *memcpy_method = get_memcpy_method ();
6174                                 iargs [1] = *sp;
6175                                 NEW_ICONST (cfg, iargs [2], n);
6176                                 iargs [2]->cil_code = ip;
6177
6178                                 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
6179                         }
6180                         NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
6181                         ++sp;
6182                         ip += 5;
6183                         ins_flag = 0;
6184                         inline_costs += 1;
6185                         break;
6186                 }
6187                 case CEE_LDSTR:
6188                         CHECK_STACK_OVF (1);
6189                         CHECK_OPSIZE (5);
6190                         n = read32 (ip + 1);
6191
6192                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
6193                                 /* FIXME: moving GC */
6194                                 NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, n));
6195                                 ins->cil_code = ip;
6196                                 ins->type = STACK_OBJ;
6197                                 ins->klass = mono_defaults.string_class;
6198                                 *sp = ins;
6199                         }
6200                         else if (method->wrapper_type != MONO_WRAPPER_NONE) {
6201                                 int temp;
6202                                 MonoInst *iargs [1];
6203
6204                                 NEW_PCONST (cfg, iargs [0], mono_method_get_wrapper_data (method, n));                          
6205                                 temp = mono_emit_jit_icall (cfg, bblock, mono_string_new_wrapper, iargs, ip);
6206                                 NEW_TEMPLOAD (cfg, *sp, temp);
6207
6208                         } else {
6209
6210                                 if (cfg->opt & MONO_OPT_SHARED) {
6211                                         int temp;
6212                                         MonoInst *iargs [3];
6213                                         MonoInst* domain_var;
6214                                         
6215                                         if (cfg->compile_aot) {
6216                                                 /* FIXME: bug when inlining methods from different assemblies (n is a token valid just in one). */
6217                                                 cfg->ldstr_list = g_list_prepend (cfg->ldstr_list, GINT_TO_POINTER (n));
6218                                         }
6219                                         /* avoid depending on undefined C behavior in sequence points */
6220                                         domain_var = mono_get_domainvar (cfg);
6221                                         NEW_TEMPLOAD (cfg, iargs [0], domain_var->inst_c0);
6222                                         NEW_IMAGECONST (cfg, iargs [1], image);
6223                                         NEW_ICONST (cfg, iargs [2], mono_metadata_token_index (n));
6224                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldstr, iargs, ip);
6225                                         NEW_TEMPLOAD (cfg, *sp, temp);
6226                                         mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
6227                                 } else {
6228                                         if (bblock->out_of_line) {
6229                                                 MonoInst *iargs [2];
6230                                                 int temp;
6231
6232                                                 if (cfg->compile_aot && cfg->method->klass->image == mono_defaults.corlib) {
6233                                                         /* 
6234                                                          * Avoid relocations by using a version of helper_ldstr
6235                                                          * specialized to mscorlib.
6236                                                          */
6237                                                         NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (n));
6238                                                         temp = mono_emit_jit_icall (cfg, bblock, mono_helper_ldstr_mscorlib, iargs, ip);
6239                                                 } else {
6240                                                         /* Avoid creating the string object */
6241                                                         NEW_IMAGECONST (cfg, iargs [0], image);
6242                                                         NEW_ICONST (cfg, iargs [1], mono_metadata_token_index (n));
6243                                                         temp = mono_emit_jit_icall (cfg, bblock, mono_helper_ldstr, iargs, ip);
6244                                                 }
6245                                                 NEW_TEMPLOAD (cfg, *sp, temp);
6246                                         } 
6247                                         else
6248                                         if (cfg->compile_aot) {
6249                                                 NEW_LDSTRCONST (cfg, ins, image, n);
6250                                                 *sp = ins;
6251                                         } 
6252                                         else {
6253                                                 NEW_PCONST (cfg, ins, NULL);
6254                                                 ins->cil_code = ip;
6255                                                 ins->type = STACK_OBJ;
6256                                                 ins->inst_p0 = mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
6257                                                 ins->klass = mono_defaults.string_class;
6258                                                 *sp = ins;
6259                                         }
6260                                 }
6261                         }
6262
6263                         sp++;
6264                         ip += 5;
6265                         break;
6266                 case CEE_NEWOBJ: {
6267                         MonoInst *iargs [2];
6268                         MonoMethodSignature *fsig;
6269                         int temp;
6270
6271                         CHECK_OPSIZE (5);
6272                         token = read32 (ip + 1);
6273                         cmethod = mini_get_method (method, token, NULL, generic_context);
6274                         if (!cmethod)
6275                                 goto load_error;
6276                         fsig = mono_method_get_signature (cmethod, image, token);
6277
6278                         mono_save_token_info (cfg, image, token, cmethod);
6279
6280                         if (!mono_class_init (cmethod->klass))
6281                                 goto load_error;
6282
6283                         if (cfg->generic_sharing_context && mono_method_check_context_used (cmethod))
6284                                 GENERIC_SHARING_FAILURE (CEE_NEWOBJ);
6285
6286                         if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
6287                                 if (check_linkdemand (cfg, method, cmethod, bblock, ip))
6288                                         INLINE_FAILURE;
6289                                 CHECK_CFG_EXCEPTION;
6290                         } else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
6291                                 ensure_method_is_allowed_to_call_method (cfg, method, cmethod, bblock, ip);
6292                         }
6293
6294                         n = fsig->param_count;
6295                         CHECK_STACK (n);
6296
6297                         /* move the args to allow room for 'this' in the first position */
6298                         while (n--) {
6299                                 --sp;
6300                                 sp [1] = sp [0];
6301                         }
6302
6303                         handle_loaded_temps (cfg, bblock, stack_start, sp);
6304
6305                         if (mini_class_is_system_array (cmethod->klass)) {
6306                                 NEW_METHODCONST (cfg, *sp, cmethod);
6307                                 temp = handle_array_new (cfg, bblock, fsig->param_count, sp, ip);
6308                         } else if (cmethod->string_ctor) {
6309                                 /* we simply pass a null pointer */
6310                                 NEW_PCONST (cfg, *sp, NULL); 
6311                                 /* now call the string ctor */
6312                                 temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, NULL);
6313                         } else {
6314                                 MonoInst* callvirt_this_arg = NULL;
6315                                 
6316                                 if (cmethod->klass->valuetype) {
6317                                         iargs [0] = mono_compile_create_var (cfg, &cmethod->klass->byval_arg, OP_LOCAL);
6318                                         temp = iargs [0]->inst_c0;
6319
6320                                         NEW_TEMPLOADA (cfg, *sp, temp);
6321
6322                                         handle_initobj (cfg, bblock, *sp, NULL, cmethod->klass, stack_start, sp);
6323
6324                                         NEW_TEMPLOADA (cfg, *sp, temp);
6325
6326                                         /* 
6327                                          * The code generated by mini_emit_virtual_call () expects
6328                                          * iargs [0] to be a boxed instance, but luckily the vcall
6329                                          * will be transformed into a normal call there.
6330                                          */
6331                                 } else {
6332                                         MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
6333                                         if (mini_field_access_needs_cctor_run (cfg, method, vtable) && !(g_slist_find (class_inits, vtable))) {
6334                                                 guint8 *tramp = mono_create_class_init_trampoline (vtable);
6335                                                 mono_emit_native_call (cfg, bblock, tramp, 
6336                                                                                            helper_sig_class_init_trampoline,
6337                                                                                            NULL, ip, FALSE, FALSE);
6338                                                 if (cfg->verbose_level > 2)
6339                                                         g_print ("class %s.%s needs init call for ctor\n", cmethod->klass->name_space, cmethod->klass->name);
6340                                                 class_inits = g_slist_prepend (class_inits, vtable);
6341                                         }
6342                                         temp = handle_alloc (cfg, bblock, cmethod->klass, FALSE, ip);
6343                                         NEW_TEMPLOAD (cfg, *sp, temp);
6344                                 }
6345
6346                                 /* Avoid virtual calls to ctors if possible */
6347                                 if (cmethod->klass->marshalbyref)
6348                                         callvirt_this_arg = sp [0];
6349                                 
6350                                 if ((cfg->opt & MONO_OPT_INLINE) && cmethod &&
6351                                     mono_method_check_inlining (cfg, cmethod) &&
6352                                     !mono_class_is_subclass_of (cmethod->klass, mono_defaults.exception_class, FALSE) &&
6353                                     !g_list_find (dont_inline, cmethod)) {
6354                                         int costs;
6355                                         MonoBasicBlock *ebblock;
6356                                         if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock, FALSE))) {
6357
6358                                                 ip += 5;
6359                                                 real_offset += 5;
6360                                                 
6361                                                 GET_BBLOCK (cfg, bblock, ip);
6362                                                 ebblock->next_bb = bblock;
6363                                                 link_bblock (cfg, ebblock, bblock);
6364
6365                                                 NEW_TEMPLOAD (cfg, *sp, temp);
6366                                                 sp++;
6367
6368                                                 /* indicates start of a new block, and triggers a load 
6369                                                    of all stack arguments at bb boundarie */
6370                                                 bblock = ebblock;
6371
6372                                                 inline_costs += costs;
6373                                                 break;
6374                                                 
6375                                         } else {
6376                                                 /* Prevent inlining of methods which call other methods */
6377                                                 INLINE_FAILURE;
6378                                                 mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, callvirt_this_arg);
6379                                         }
6380                                 } else {
6381                                         /* Prevent inlining of methods which call other methods */
6382                                         INLINE_FAILURE;
6383                                         /* now call the actual ctor */
6384                                         mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, callvirt_this_arg);
6385                                 }
6386                         }
6387
6388                         NEW_TEMPLOAD (cfg, *sp, temp);
6389                         sp++;
6390                         
6391                         ip += 5;
6392                         inline_costs += 5;
6393                         break;
6394                 }
6395                 case CEE_ISINST:
6396                         CHECK_STACK (1);
6397                         --sp;
6398                         CHECK_OPSIZE (5);
6399                         token = read32 (ip + 1);
6400                         klass = mini_get_class (method, token, generic_context);
6401                         CHECK_TYPELOAD (klass);
6402                         if (sp [0]->type != STACK_OBJ)
6403                                 UNVERIFIED;
6404
6405                         if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
6406                                 GENERIC_SHARING_FAILURE (CEE_ISINST);
6407
6408                         /* Needed by the code generated in inssel.brg */
6409                         mono_get_got_var (cfg);
6410
6411                         if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
6412                         
6413                                 MonoMethod *mono_isinst;
6414                                 MonoInst *iargs [1];
6415                                 MonoBasicBlock *ebblock;
6416                                 int costs;
6417                                 int temp;
6418                                 
6419                                 mono_isinst = mono_marshal_get_isinst (klass); 
6420                                 iargs [0] = sp [0];
6421                                 
6422                                 costs = inline_method (cfg, mono_isinst, mono_method_signature (mono_isinst), bblock, 
6423                                                        iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
6424                         
6425                                 g_assert (costs > 0);
6426                                 
6427                                 ip += 5;
6428                                 real_offset += 5;
6429                         
6430                                 GET_BBLOCK (cfg, bblock, ip);
6431                                 ebblock->next_bb = bblock;
6432                                 link_bblock (cfg, ebblock, bblock);
6433
6434                                 temp = iargs [0]->inst_i0->inst_c0;
6435                                 NEW_TEMPLOAD (cfg, *sp, temp);
6436                                 
6437                                 sp++;
6438                                 bblock = ebblock;
6439                                 inline_costs += costs;
6440                         } else {
6441                                 MONO_INST_NEW (cfg, ins, *ip);
6442                                 ins->type = STACK_OBJ;
6443                                 ins->inst_left = *sp;
6444                                 ins->inst_newa_class = klass;
6445                                 ins->klass = klass;
6446                                 ins->cil_code = ip;
6447                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 5);
6448                                 ip += 5;
6449                         }
6450                         break;
6451                 case CEE_UNBOX_ANY: {
6452                         MonoInst *add, *vtoffset;
6453                         MonoInst *iargs [3];
6454                         guint32 align;
6455
6456                         CHECK_STACK (1);
6457                         --sp;
6458                         CHECK_OPSIZE (5);
6459                         token = read32 (ip + 1);
6460                         klass = mini_get_class (method, token, generic_context);
6461                         CHECK_TYPELOAD (klass);
6462
6463                         if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
6464                                 GENERIC_SHARING_FAILURE (CEE_UNBOX_ANY);
6465
6466                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
6467                                 /* CASTCLASS */
6468                                 if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
6469                                         MonoMethod *mono_castclass;
6470                                         MonoInst *iargs [1];
6471                                         MonoBasicBlock *ebblock;
6472                                         int costs;
6473                                         int temp;
6474                                         
6475                                         mono_castclass = mono_marshal_get_castclass (klass); 
6476                                         iargs [0] = sp [0];
6477                                         
6478                                         costs = inline_method (cfg, mono_castclass, mono_method_signature (mono_castclass), bblock, 
6479                                                         iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
6480                                 
6481                                         g_assert (costs > 0);
6482                                         
6483                                         ip += 5;
6484                                         real_offset += 5;
6485                                 
6486                                         GET_BBLOCK (cfg, bblock, ip);
6487                                         ebblock->next_bb = bblock;
6488                                         link_bblock (cfg, ebblock, bblock);
6489         
6490                                         temp = iargs [0]->inst_i0->inst_c0;
6491                                         NEW_TEMPLOAD (cfg, *sp, temp);
6492                                         
6493                                         sp++;
6494                                         bblock = ebblock;
6495                                         inline_costs += costs;                          
6496                                 } else {
6497                                         MONO_INST_NEW (cfg, ins, CEE_CASTCLASS);
6498                                         ins->type = STACK_OBJ;
6499                                         ins->inst_left = *sp;
6500                                         ins->klass = klass;
6501                                         ins->inst_newa_class = klass;
6502                                         ins->cil_code = ip;
6503                                         *sp++ = ins;
6504                                         ip += 5;
6505                                 }
6506                                 break;
6507                         }
6508
6509                         if (mono_class_is_nullable (klass)) {
6510                                 int v = handle_unbox_nullable (cfg, bblock, *sp, ip, klass);
6511                                 NEW_TEMPLOAD (cfg, *sp, v);
6512                                 sp ++;
6513                                 ip += 5;
6514                                 break;
6515                         }
6516
6517                         MONO_INST_NEW (cfg, ins, OP_UNBOXCAST);
6518                         ins->type = STACK_OBJ;
6519                         ins->inst_left = *sp;
6520                         ins->klass = klass;
6521                         ins->inst_newa_class = klass;
6522                         ins->cil_code = ip;
6523
6524                         MONO_INST_NEW (cfg, add, OP_PADD);
6525                         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
6526                         add->inst_left = ins;
6527                         add->inst_right = vtoffset;
6528                         add->type = STACK_MP;
6529                         add->klass = mono_defaults.object_class;
6530                         *sp = add;
6531                         ip += 5;
6532                         /* LDOBJ impl */
6533                         n = mono_class_value_size (klass, &align);
6534                         ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
6535                         NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
6536                         if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
6537                                 MonoInst *copy;
6538                                 NEW_MEMCPY (cfg, copy, iargs [0], *sp, n, align);
6539                                 MONO_ADD_INS (bblock, copy);
6540                         } else {
6541                                 MonoMethod *memcpy_method = get_memcpy_method ();
6542                                 iargs [1] = *sp;
6543                                 NEW_ICONST (cfg, iargs [2], n);
6544                                 iargs [2]->cil_code = ip;
6545
6546                                 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
6547                         }
6548                         NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
6549                         ++sp;
6550                         inline_costs += 2;
6551                         break;
6552                 }
6553                 case CEE_UNBOX: {
6554                         MonoInst *add, *vtoffset;
6555
6556                         CHECK_STACK (1);
6557                         --sp;
6558                         CHECK_OPSIZE (5);
6559                         token = read32 (ip + 1);
6560                         klass = mini_get_class (method, token, generic_context);
6561                         CHECK_TYPELOAD (klass);
6562
6563                         if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
6564                                 GENERIC_SHARING_FAILURE (CEE_UNBOX);
6565
6566                         if (mono_class_is_nullable (klass)) {
6567                                 int v = handle_unbox_nullable (cfg, bblock, *sp, ip, klass);
6568                                 NEW_TEMPLOAD (cfg, *sp, v);
6569                                 sp ++;
6570                                 ip += 5;
6571                                 break;
6572                         }
6573
6574                         /* Needed by the code generated in inssel.brg */
6575                         mono_get_got_var (cfg);
6576
6577                         MONO_INST_NEW (cfg, ins, OP_UNBOXCAST);
6578                         ins->type = STACK_OBJ;
6579                         ins->inst_left = *sp;
6580                         ins->klass = klass;
6581                         ins->inst_newa_class = klass;
6582                         ins->cil_code = ip;
6583
6584                         MONO_INST_NEW (cfg, add, OP_PADD);
6585                         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
6586                         add->inst_left = ins;
6587                         add->inst_right = vtoffset;
6588                         add->type = STACK_MP;
6589                         add->klass = klass;
6590                         *sp++ = add;
6591                         ip += 5;
6592                         inline_costs += 2;
6593                         break;
6594                 }
6595                 case CEE_CASTCLASS:
6596                         CHECK_STACK (1);
6597                         --sp;
6598                         CHECK_OPSIZE (5);
6599                         token = read32 (ip + 1);
6600                         klass = mini_get_class (method, token, generic_context);
6601                         CHECK_TYPELOAD (klass);
6602                         if (sp [0]->type != STACK_OBJ)
6603                                 UNVERIFIED;
6604
6605                         if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
6606                                 GENERIC_SHARING_FAILURE (CEE_CASTCLASS);
6607
6608                         /* Needed by the code generated in inssel.brg */
6609                         mono_get_got_var (cfg);
6610                 
6611                         if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
6612                                 
6613                                 MonoMethod *mono_castclass;
6614                                 MonoInst *iargs [1];
6615                                 MonoBasicBlock *ebblock;
6616                                 int costs;
6617                                 int temp;
6618                                 
6619                                 mono_castclass = mono_marshal_get_castclass (klass); 
6620                                 iargs [0] = sp [0];
6621                                 
6622                                 costs = inline_method (cfg, mono_castclass, mono_method_signature (mono_castclass), bblock, 
6623                                                 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
6624                         
6625                                 g_assert (costs > 0);
6626                                 
6627                                 ip += 5;
6628                                 real_offset += 5;
6629                         
6630                                 GET_BBLOCK (cfg, bblock, ip);
6631                                 ebblock->next_bb = bblock;
6632                                 link_bblock (cfg, ebblock, bblock);
6633
6634                                 temp = iargs [0]->inst_i0->inst_c0;
6635                                 NEW_TEMPLOAD (cfg, *sp, temp);
6636                                 
6637                                 sp++;
6638                                 bblock = ebblock;
6639                                 inline_costs += costs;
6640                         } else {
6641                                 MONO_INST_NEW (cfg, ins, *ip);
6642                                 ins->type = STACK_OBJ;
6643                                 ins->inst_left = *sp;
6644                                 ins->klass = klass;
6645                                 ins->inst_newa_class = klass;
6646                                 ins->cil_code = ip;
6647                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 5);
6648                                 ip += 5;
6649                         }
6650                         break;
6651                 case CEE_THROW:
6652                         CHECK_STACK (1);
6653                         MONO_INST_NEW (cfg, ins, OP_THROW);
6654                         --sp;
6655                         ins->inst_left = *sp;
6656                         ins->cil_code = ip++;
6657                         bblock->out_of_line = TRUE;
6658                         MONO_ADD_INS (bblock, ins);
6659                         MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
6660                         ins->cil_code = ip - 1;
6661                         MONO_ADD_INS (bblock, ins);
6662                         sp = stack_start;
6663                         
6664                         link_bblock (cfg, bblock, end_bblock);
6665                         start_new_bblock = 1;
6666                         break;
6667                 case CEE_LDFLD:
6668                 case CEE_LDFLDA:
6669                 case CEE_STFLD: {
6670                         MonoInst *offset_ins;
6671                         MonoClassField *field;
6672                         MonoBasicBlock *ebblock;
6673                         int costs;
6674                         guint foffset;
6675
6676                         if (*ip == CEE_STFLD) {
6677                                 CHECK_STACK (2);
6678                                 sp -= 2;
6679                         } else {
6680                                 CHECK_STACK (1);
6681                                 --sp;
6682                         }
6683                         if (sp [0]->type == STACK_I4 || sp [0]->type == STACK_I8 || sp [0]->type == STACK_R8)
6684                                 UNVERIFIED;
6685                         if (*ip != CEE_LDFLD && sp [0]->type == STACK_VTYPE)
6686                                 UNVERIFIED;
6687                         CHECK_OPSIZE (5);
6688                         token = read32 (ip + 1);
6689                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
6690                                 field = mono_method_get_wrapper_data (method, token);
6691                                 klass = field->parent;
6692                         } else {
6693                                 field = mono_field_from_token (image, token, &klass, generic_context);
6694                         }
6695                         if (!field)
6696                                 goto load_error;
6697                         mono_class_init (klass);
6698                         if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_field (method, field))
6699                                 FIELD_ACCESS_FAILURE;
6700
6701                         foffset = klass->valuetype? field->offset - sizeof (MonoObject): field->offset;
6702                         /* FIXME: mark instructions for use in SSA */
6703                         if (*ip == CEE_STFLD) {
6704                                 if (target_type_is_incompatible (cfg, field->type, sp [1]))
6705                                         UNVERIFIED;
6706                                 if ((klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) || klass->contextbound || klass == mono_defaults.marshalbyrefobject_class) {
6707                                         MonoMethod *stfld_wrapper = mono_marshal_get_stfld_wrapper (field->type); 
6708                                         MonoInst *iargs [5];
6709
6710                                         iargs [0] = sp [0];
6711                                         NEW_CLASSCONST (cfg, iargs [1], klass);
6712                                         NEW_FIELDCONST (cfg, iargs [2], field);
6713                                         NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : 
6714                                                     field->offset);
6715                                         iargs [4] = sp [1];
6716
6717                                         if (cfg->opt & MONO_OPT_INLINE) {
6718                                                 costs = inline_method (cfg, stfld_wrapper, mono_method_signature (stfld_wrapper), bblock, 
6719                                                                 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
6720                                                 g_assert (costs > 0);
6721                                                       
6722                                                 ip += 5;
6723                                                 real_offset += 5;
6724
6725                                                 GET_BBLOCK (cfg, bblock, ip);
6726                                                 ebblock->next_bb = bblock;
6727                                                 link_bblock (cfg, ebblock, bblock);
6728
6729                                                 /* indicates start of a new block, and triggers a load 
6730                                                    of all stack arguments at bb boundarie */
6731                                                 bblock = ebblock;
6732
6733                                                 inline_costs += costs;
6734                                                 break;
6735                                         } else {
6736                                                 mono_emit_method_call_spilled (cfg, bblock, stfld_wrapper, mono_method_signature (stfld_wrapper), iargs, ip, NULL);
6737                                         }
6738 #if HAVE_WRITE_BARRIERS
6739                                 } else if (mini_type_to_stind (cfg, field->type) == CEE_STIND_REF) {
6740                                         /* insert call to write barrier */
6741                                         MonoMethod *write_barrier = mono_marshal_get_write_barrier ();
6742                                         MonoInst *iargs [2];
6743                                         NEW_ICONST (cfg, offset_ins, foffset);
6744                                         MONO_INST_NEW (cfg, ins, OP_PADD);
6745                                         ins->cil_code = ip;
6746                                         ins->inst_left = *sp;
6747                                         ins->inst_right = offset_ins;
6748                                         ins->type = STACK_MP;
6749                                         ins->klass = mono_defaults.object_class;
6750                                         iargs [0] = ins;
6751                                         iargs [1] = sp [1];
6752                                         mono_emit_method_call_spilled (cfg, bblock, write_barrier, mono_method_signature (write_barrier), iargs, ip, NULL);
6753 #endif
6754 #ifdef MONO_ARCH_SOFT_FLOAT
6755                                 } else if (mini_type_to_stind (cfg, field->type) == CEE_STIND_R4) {
6756                                         NEW_ICONST (cfg, offset_ins, foffset);
6757                                         MONO_INST_NEW (cfg, ins, OP_PADD);
6758                                         ins->cil_code = ip;
6759                                         ins->inst_left = *sp;
6760                                         ins->inst_right = offset_ins;
6761                                         ins->type = STACK_MP;
6762                                         ins->klass = mono_defaults.object_class;
6763                                         handle_store_float (cfg, bblock, ins, sp [1], ip);
6764 #endif
6765                                 } else {
6766                                         MonoInst *store;
6767                                         NEW_ICONST (cfg, offset_ins, foffset);
6768                                         MONO_INST_NEW (cfg, ins, OP_PADD);
6769                                         ins->cil_code = ip;
6770                                         ins->inst_left = *sp;
6771                                         ins->inst_right = offset_ins;
6772                                         ins->type = STACK_MP;
6773
6774                                         MONO_INST_NEW (cfg, store, mini_type_to_stind (cfg, field->type));
6775                                         store->cil_code = ip;
6776                                         store->inst_left = ins;
6777                                         store->inst_right = sp [1];
6778                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
6779                                         store->flags |= ins_flag;
6780                                         ins_flag = 0;
6781                                         if (store->opcode == CEE_STOBJ) {
6782                                                 handle_stobj (cfg, bblock, ins, sp [1], ip, 
6783                                                               mono_class_from_mono_type (field->type), FALSE, FALSE, TRUE);
6784                                         } else
6785                                                 MONO_ADD_INS (bblock, store);
6786                                 }
6787                         } else {
6788                                 if ((klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) || klass->contextbound || klass == mono_defaults.marshalbyrefobject_class) {
6789                                         MonoMethod *wrapper = (*ip == CEE_LDFLDA) ? mono_marshal_get_ldflda_wrapper (field->type) : mono_marshal_get_ldfld_wrapper (field->type); 
6790                                         MonoInst *iargs [4];
6791                                         int temp;
6792                                         
6793                                         iargs [0] = sp [0];
6794                                         NEW_CLASSCONST (cfg, iargs [1], klass);
6795                                         NEW_FIELDCONST (cfg, iargs [2], field);
6796                                         NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
6797                                         if ((cfg->opt & MONO_OPT_INLINE) && !MONO_TYPE_ISSTRUCT (mono_method_signature (wrapper)->ret)) {
6798                                                 costs = inline_method (cfg, wrapper, mono_method_signature (wrapper), bblock, 
6799                                                                 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
6800                                                 g_assert (costs > 0);
6801                                                       
6802                                                 ip += 5;
6803                                                 real_offset += 5;
6804
6805                                                 GET_BBLOCK (cfg, bblock, ip);
6806                                                 ebblock->next_bb = bblock;
6807                                                 link_bblock (cfg, ebblock, bblock);
6808
6809                                                 temp = iargs [0]->inst_i0->inst_c0;
6810
6811                                                 NEW_TEMPLOAD (cfg, *sp, temp);
6812                                                 sp++;
6813
6814                                                 /* indicates start of a new block, and triggers a load of
6815                                                    all stack arguments at bb boundarie */
6816                                                 bblock = ebblock;
6817                                                 
6818                                                 inline_costs += costs;
6819                                                 break;
6820                                         } else {
6821                                                 temp = mono_emit_method_call_spilled (cfg, bblock, wrapper, mono_method_signature (wrapper), iargs, ip, NULL);
6822                                                 NEW_TEMPLOAD (cfg, *sp, temp);
6823                                                 sp++;
6824                                         }
6825                                 } else {
6826                                         NEW_ICONST (cfg, offset_ins, foffset);
6827                                         MONO_INST_NEW (cfg, ins, OP_PADD);
6828                                         ins->cil_code = ip;
6829                                         ins->inst_left = *sp;
6830                                         ins->inst_right = offset_ins;
6831                                         ins->type = STACK_MP;
6832
6833                                         if (*ip == CEE_LDFLDA) {
6834                                                 ins->klass = mono_class_from_mono_type (field->type);
6835                                                 *sp++ = ins;
6836                                         } else {
6837                                                 MonoInst *load;
6838                                                 MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, field->type));
6839                                                 type_to_eval_stack_type (cfg, field->type, load);
6840                                                 load->cil_code = ip;
6841                                                 load->inst_left = ins;
6842                                                 load->flags |= ins_flag;
6843                                                 ins_flag = 0;
6844 #ifdef MONO_ARCH_SOFT_FLOAT
6845                                                 if (mini_type_to_ldind (cfg, field->type) == CEE_LDIND_R4) {
6846                                                         int temp;
6847                                                         temp = handle_load_float (cfg, bblock, ins, ip);
6848                                                         NEW_TEMPLOAD (cfg, *sp, temp);
6849                                                         sp++;
6850                                                 } else
6851 #endif
6852                                                 *sp++ = load;
6853                                         }
6854                                 }
6855                         }
6856                         ip += 5;
6857                         break;
6858                 }
6859                 case CEE_LDSFLD:
6860                 case CEE_LDSFLDA:
6861                 case CEE_STSFLD: {
6862                         MonoClassField *field;
6863                         gpointer addr = NULL;
6864                         gboolean shared_access = FALSE;
6865                         int relation = 0;
6866
6867                         CHECK_OPSIZE (5);
6868                         token = read32 (ip + 1);
6869                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
6870                                 field = mono_method_get_wrapper_data (method, token);
6871                                 klass = field->parent;
6872                         }
6873                         else
6874                                 field = mono_field_from_token (image, token, &klass, generic_context);
6875                         if (!field)
6876                                 goto load_error;
6877                         mono_class_init (klass);
6878                         if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_field (method, field))
6879                                 FIELD_ACCESS_FAILURE;
6880
6881                         /*
6882                          * We can only support shared generic static
6883                          * field access on architectures where the
6884                          * trampoline code has been extended to handle
6885                          * the generic class init.
6886                          */
6887 #ifndef MONO_ARCH_VTABLE_REG
6888                         GENERIC_SHARING_FAILURE (*ip);
6889 #endif
6890
6891                         if (cfg->generic_sharing_context) {
6892                                 int context_used = mono_class_check_context_used (klass);
6893
6894                                 if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD ||
6895                                                 klass->valuetype)
6896                                         GENERIC_SHARING_FAILURE (*ip);
6897
6898                                 if (context_used) {
6899                                         relation = mono_class_generic_class_relation (klass, method->klass, generic_context, NULL);
6900
6901                                         if (!(method->flags & METHOD_ATTRIBUTE_STATIC) /*&& relation != MINI_GENERIC_CLASS_RELATION_OTHER*/)
6902                                                 shared_access = TRUE;
6903                                         else
6904                                                 GENERIC_SHARING_FAILURE (*ip);
6905                                 }
6906                         }
6907
6908                         g_assert (!(field->type->attrs & FIELD_ATTRIBUTE_LITERAL));
6909
6910                         if ((*ip) == CEE_STSFLD)
6911                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
6912
6913                         /* The special_static_fields field is init'd in mono_class_vtable, so it needs
6914                          * to be called here.
6915                          */
6916                         if (!(cfg->opt & MONO_OPT_SHARED))
6917                                 mono_class_vtable (cfg->domain, klass);
6918                         mono_domain_lock (cfg->domain);
6919                         if (cfg->domain->special_static_fields)
6920                                 addr = g_hash_table_lookup (cfg->domain->special_static_fields, field);
6921                         mono_domain_unlock (cfg->domain);
6922
6923                         if (shared_access) {
6924                                 MonoInst *this, *rgctx, *static_data;
6925
6926                                 /*
6927                                 g_print ("sharing static field access in %s.%s.%s - depth %d offset %d\n",
6928                                         method->klass->name_space, method->klass->name, method->name,
6929                                         depth, field->offset);
6930                                 */
6931
6932                                 if (mono_class_needs_cctor_run (klass, method)) {
6933                                         MonoMethodSignature *sig = helper_sig_generic_class_init_trampoline;
6934                                         MonoCallInst *call;
6935                                         MonoInst *this, *vtable;
6936
6937                                         NEW_ARGLOAD (cfg, this, 0);
6938
6939                                         if (relation == MINI_GENERIC_CLASS_RELATION_SELF) {
6940                                                 MONO_INST_NEW (cfg, vtable, CEE_LDIND_I);
6941                                                 vtable->cil_code = ip;
6942                                                 vtable->inst_left = this;
6943                                                 vtable->type = STACK_PTR;
6944                                                 vtable->klass = klass;
6945                                         } else {
6946                                                 MonoInst *rgctx = get_runtime_generic_context_from_this (cfg, this, ip);
6947
6948                                                 vtable = get_runtime_generic_context_ptr (cfg, method, bblock, klass,
6949                                                         token, generic_context, rgctx, MINI_RGCTX_VTABLE, ip);
6950                                         }
6951
6952                                         call = mono_emit_call_args (cfg, bblock, sig, NULL, FALSE, FALSE, ip, FALSE);
6953                                         call->inst.opcode = OP_TRAMPCALL_VTABLE;
6954                                         call->fptr = mono_get_trampoline_code (MONO_TRAMPOLINE_GENERIC_CLASS_INIT);
6955
6956                                         call->inst.inst_left = vtable;
6957
6958                                         mono_spill_call (cfg, bblock, call, sig, FALSE, ip, FALSE);
6959                                 }
6960
6961                                 /*
6962                                  * The pointer we're computing here is
6963                                  *
6964                                  *   super_info.static_data + field->offset
6965                                  */
6966
6967                                 NEW_ARGLOAD (cfg, this, 0);
6968                                 rgctx = get_runtime_generic_context_from_this (cfg, this, ip);
6969                                 static_data = get_runtime_generic_context_ptr (cfg, method, bblock, klass,
6970                                         token, generic_context, rgctx, MINI_RGCTX_STATIC_DATA, ip);
6971
6972                                 if (field->offset == 0) {
6973                                         ins = static_data;
6974                                 } else {
6975                                         MonoInst *field_offset;
6976
6977                                         NEW_ICONST (cfg, field_offset, field->offset);
6978
6979                                         MONO_INST_NEW (cfg, ins, OP_PADD);
6980                                         ins->cil_code = ip;
6981                                         ins->inst_left = static_data;
6982                                         ins->inst_right = field_offset;
6983                                         ins->type = STACK_PTR;
6984                                         ins->klass = klass;
6985                                 }
6986                         } else if ((cfg->opt & MONO_OPT_SHARED) || (cfg->compile_aot && addr)) {
6987                                 int temp;
6988                                 MonoInst *iargs [2];
6989                                 MonoInst *domain_var;
6990                                 
6991                                 g_assert (field->parent);
6992                                 /* avoid depending on undefined C behavior in sequence points */
6993                                 domain_var = mono_get_domainvar (cfg);
6994                                 NEW_TEMPLOAD (cfg, iargs [0], domain_var->inst_c0);
6995                                 NEW_FIELDCONST (cfg, iargs [1], field);
6996                                 temp = mono_emit_jit_icall (cfg, bblock, mono_class_static_field_address, iargs, ip);
6997                                 NEW_TEMPLOAD (cfg, ins, temp);
6998                         } else {
6999                                 MonoVTable *vtable;
7000                                 vtable = mono_class_vtable (cfg->domain, klass);
7001                                 if (!addr) {
7002                                         if (mini_field_access_needs_cctor_run (cfg, method, vtable) && !(g_slist_find (class_inits, vtable))) {
7003                                                 guint8 *tramp = mono_create_class_init_trampoline (vtable);
7004                                                 mono_emit_native_call (cfg, bblock, tramp, 
7005                                                                                            helper_sig_class_init_trampoline,
7006                                                                                            NULL, ip, FALSE, FALSE);
7007                                                 if (cfg->verbose_level > 2)
7008                                                         g_print ("class %s.%s needs init call for %s\n", klass->name_space, klass->name, field->name);
7009                                                 class_inits = g_slist_prepend (class_inits, vtable);
7010                                         } else {
7011                                                 if (cfg->run_cctors) {
7012                                                         /* This makes so that inline cannot trigger */
7013                                                         /* .cctors: too many apps depend on them */
7014                                                         /* running with a specific order... */
7015                                                         if (! vtable->initialized)
7016                                                                 INLINE_FAILURE;
7017                                                         mono_runtime_class_init (vtable);
7018                                                 }
7019                                         }
7020                                         addr = (char*)vtable->data + field->offset;
7021
7022                                         if (cfg->compile_aot)
7023                                                 NEW_SFLDACONST (cfg, ins, field);
7024                                         else
7025                                                 NEW_PCONST (cfg, ins, addr);
7026                                         ins->cil_code = ip;
7027                                 } else {
7028                                         /* 
7029                                          * insert call to mono_threads_get_static_data (GPOINTER_TO_UINT (addr)) 
7030                                          * This could be later optimized to do just a couple of
7031                                          * memory dereferences with constant offsets.
7032                                          */
7033                                         int temp;
7034                                         MonoInst *iargs [1];
7035                                         NEW_ICONST (cfg, iargs [0], GPOINTER_TO_UINT (addr));
7036                                         temp = mono_emit_jit_icall (cfg, bblock, mono_get_special_static_data, iargs, ip);
7037                                         NEW_TEMPLOAD (cfg, ins, temp);
7038                                 }
7039                         }
7040
7041                         /* FIXME: mark instructions for use in SSA */
7042                         if (*ip == CEE_LDSFLDA) {
7043                                 ins->klass = mono_class_from_mono_type (field->type);
7044                                 *sp++ = ins;
7045                         } else if (*ip == CEE_STSFLD) {
7046                                 MonoInst *store;
7047                                 CHECK_STACK (1);
7048                                 sp--;
7049                                 MONO_INST_NEW (cfg, store, mini_type_to_stind (cfg, field->type));
7050                                 store->cil_code = ip;
7051                                 store->inst_left = ins;
7052                                 store->inst_right = sp [0];
7053                                 store->flags |= ins_flag;
7054                                 ins_flag = 0;
7055
7056 #ifdef MONO_ARCH_SOFT_FLOAT
7057                                 if (store->opcode == CEE_STIND_R4)
7058                                         handle_store_float (cfg, bblock, ins, sp [0], ip);
7059                                 else
7060 #endif
7061                                 if (store->opcode == CEE_STOBJ) {
7062                                         handle_stobj (cfg, bblock, ins, sp [0], ip, mono_class_from_mono_type (field->type), FALSE, FALSE, FALSE);
7063                                 } else
7064                                         MONO_ADD_INS (bblock, store);
7065                         } else {
7066                                 gboolean is_const = FALSE;
7067                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
7068                                 if (!shared_access && !((cfg->opt & MONO_OPT_SHARED) || cfg->compile_aot) && 
7069                                     vtable->initialized && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY)) {
7070                                         gpointer addr = (char*)vtable->data + field->offset;
7071                                         int ro_type = field->type->type;
7072                                         if (ro_type == MONO_TYPE_VALUETYPE && field->type->data.klass->enumtype) {
7073                                                 ro_type = field->type->data.klass->enum_basetype->type;
7074                                         }
7075                                         /* g_print ("RO-FIELD %s.%s:%s\n", klass->name_space, klass->name, field->name);*/
7076                                         is_const = TRUE;
7077                                         switch (ro_type) {
7078                                         case MONO_TYPE_BOOLEAN:
7079                                         case MONO_TYPE_U1:
7080                                                 NEW_ICONST (cfg, *sp, *((guint8 *)addr));
7081                                                 sp++;
7082                                                 break;
7083                                         case MONO_TYPE_I1:
7084                                                 NEW_ICONST (cfg, *sp, *((gint8 *)addr));
7085                                                 sp++;
7086                                                 break;                                          
7087                                         case MONO_TYPE_CHAR:
7088                                         case MONO_TYPE_U2:
7089                                                 NEW_ICONST (cfg, *sp, *((guint16 *)addr));
7090                                                 sp++;
7091                                                 break;
7092                                         case MONO_TYPE_I2:
7093                                                 NEW_ICONST (cfg, *sp, *((gint16 *)addr));
7094                                                 sp++;
7095                                                 break;
7096                                                 break;
7097                                         case MONO_TYPE_I4:
7098                                                 NEW_ICONST (cfg, *sp, *((gint32 *)addr));
7099                                                 sp++;
7100                                                 break;                                          
7101                                         case MONO_TYPE_U4:
7102                                                 NEW_ICONST (cfg, *sp, *((guint32 *)addr));
7103                                                 sp++;
7104                                                 break;
7105 #ifndef HAVE_MOVING_COLLECTOR
7106                                         case MONO_TYPE_I:
7107                                         case MONO_TYPE_U:
7108                                         case MONO_TYPE_STRING:
7109                                         case MONO_TYPE_OBJECT:
7110                                         case MONO_TYPE_CLASS:
7111                                         case MONO_TYPE_SZARRAY:
7112                                         case MONO_TYPE_PTR:
7113                                         case MONO_TYPE_FNPTR:
7114                                         case MONO_TYPE_ARRAY:
7115                                                 NEW_PCONST (cfg, *sp, *((gpointer *)addr));
7116                                                 type_to_eval_stack_type (cfg, field->type, *sp);
7117                                                 sp++;
7118                                                 break;
7119 #endif
7120                                         case MONO_TYPE_I8:
7121                                         case MONO_TYPE_U8:
7122                                                 MONO_INST_NEW (cfg, *sp, OP_I8CONST);
7123                                                 sp [0]->type = STACK_I8;
7124                                                 sp [0]->inst_l = *((gint64 *)addr);
7125                                                 sp++;
7126                                                 break;
7127                                         case MONO_TYPE_R4:
7128                                         case MONO_TYPE_R8:
7129                                         case MONO_TYPE_VALUETYPE:
7130                                         default:
7131                                                 is_const = FALSE;
7132                                                 break;
7133                                         }
7134                                 }
7135
7136                                 if (!is_const) {
7137                                         MonoInst *load;
7138                                         CHECK_STACK_OVF (1);
7139                                         MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, field->type));
7140                                         type_to_eval_stack_type (cfg, field->type, load);
7141                                         load->cil_code = ip;
7142                                         load->inst_left = ins;
7143                                         load->flags |= ins_flag;
7144 #ifdef MONO_ARCH_SOFT_FLOAT
7145                                         if (load->opcode == CEE_LDIND_R4) {
7146                                                 int temp;
7147                                                 temp = handle_load_float (cfg, bblock, ins, ip);
7148                                                 NEW_TEMPLOAD (cfg, load, temp);
7149                                         }
7150 #endif
7151                                         *sp++ = load;
7152                                         ins_flag = 0;
7153                                 }
7154                         }
7155                         ip += 5;
7156                         break;
7157                 }
7158                 case CEE_STOBJ:
7159                         CHECK_STACK (2);
7160                         sp -= 2;
7161                         CHECK_OPSIZE (5);
7162                         token = read32 (ip + 1);
7163                         klass = mini_get_class (method, token, generic_context);
7164                         CHECK_TYPELOAD (klass);
7165                         n = mini_type_to_stind (cfg, &klass->byval_arg);
7166                         /* FIXME: handle CEE_STIND_R4 */
7167                         if (n == CEE_STOBJ) {
7168                                 handle_stobj (cfg, bblock, sp [0], sp [1], ip, klass, FALSE, FALSE, TRUE);
7169                         } else {
7170                                 /* FIXME: should check item at sp [1] is compatible with the type of the store. */
7171                                 MonoInst *store;
7172                                 MONO_INST_NEW (cfg, store, n);
7173                                 store->cil_code = ip;
7174                                 store->inst_left = sp [0];
7175                                 store->inst_right = sp [1];
7176                                 store->flags |= ins_flag;
7177                                 MONO_ADD_INS (bblock, store);
7178                         }
7179                         ins_flag = 0;
7180                         ip += 5;
7181                         inline_costs += 1;
7182                         break;
7183                 case CEE_BOX: {
7184                         MonoInst *val;
7185
7186                         CHECK_STACK (1);
7187                         --sp;
7188                         val = *sp;
7189                         CHECK_OPSIZE (5);
7190                         token = read32 (ip + 1);
7191                         klass = mini_get_class (method, token, generic_context);
7192                         CHECK_TYPELOAD (klass);
7193
7194                         if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
7195                                 GENERIC_SHARING_FAILURE (CEE_BOX);
7196
7197                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
7198                                 *sp++ = val;
7199                                 ip += 5;
7200                                 break;
7201                         }
7202                         if (klass == mono_defaults.void_class)
7203                                 UNVERIFIED;
7204                         if (target_type_is_incompatible (cfg, &klass->byval_arg, *sp))
7205                                 UNVERIFIED;
7206                         /* frequent check in generic code: box (struct), brtrue */
7207                         if (!mono_class_is_nullable (klass) &&
7208                             ip + 5 < end && ip_in_bb (cfg, bblock, ip + 5) && (ip [5] == CEE_BRTRUE || ip [5] == CEE_BRTRUE_S)) {
7209                                 /*g_print ("box-brtrue opt at 0x%04x in %s\n", real_offset, method->name);*/
7210                                 MONO_INST_NEW (cfg, ins, CEE_POP);
7211                                 MONO_ADD_INS (bblock, ins);
7212                                 ins->cil_code = ip;
7213                                 ins->inst_i0 = *sp;
7214                                 ip += 5;
7215                                 MONO_INST_NEW (cfg, ins, OP_BR);
7216                                 ins->cil_code = ip;
7217                                 MONO_ADD_INS (bblock, ins);
7218                                 if (*ip == CEE_BRTRUE_S) {
7219                                         CHECK_OPSIZE (2);
7220                                         ip++;
7221                                         target = ip + 1 + (signed char)(*ip);
7222                                         ip++;
7223                                 } else {
7224                                         CHECK_OPSIZE (5);
7225                                         ip++;
7226                                         target = ip + 4 + (gint)(read32 (ip));
7227                                         ip += 4;
7228                                 }
7229                                 GET_BBLOCK (cfg, tblock, target);
7230                                 link_bblock (cfg, bblock, tblock);
7231                                 CHECK_BBLOCK (target, ip, tblock);
7232                                 ins->inst_target_bb = tblock;
7233                                 GET_BBLOCK (cfg, tblock, ip);
7234                                 link_bblock (cfg, bblock, tblock);
7235                                 if (sp != stack_start) {
7236                                         handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
7237                                         sp = stack_start;
7238                                         CHECK_UNVERIFIABLE (cfg);
7239                                 }
7240                                 start_new_bblock = 1;
7241                                 break;
7242                         }
7243                         *sp++ = handle_box (cfg, bblock, val, ip, klass);
7244                         ip += 5;
7245                         inline_costs += 1;
7246                         break;
7247                 }
7248                 case CEE_NEWARR: {
7249                         gboolean shared_access = FALSE;
7250
7251                         CHECK_STACK (1);
7252                         --sp;
7253
7254                         CHECK_OPSIZE (5);
7255                         token = read32 (ip + 1);
7256
7257                         /* allocate the domainvar - becaus this is used in decompose_foreach */
7258                         if (cfg->opt & MONO_OPT_SHARED) {
7259                                 mono_get_domainvar (cfg);
7260                                 /* LAME-IR: Mark it as used since otherwise it will be optimized away */
7261                                 cfg->domainvar->flags |= MONO_INST_VOLATILE;
7262                         }
7263
7264                         /* Ditto */
7265                         mono_get_got_var (cfg);
7266
7267                         klass = mini_get_class (method, token, generic_context);
7268                         CHECK_TYPELOAD (klass);
7269
7270                         if (cfg->generic_sharing_context) {
7271                                 int context_used = mono_class_check_context_used (klass);
7272
7273                                 if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD || klass->valuetype)
7274                                         GENERIC_SHARING_FAILURE (CEE_NEWARR);
7275
7276                                 if (context_used) {
7277                                         if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
7278                                                 shared_access = TRUE;
7279                                         else
7280                                                 GENERIC_SHARING_FAILURE (CEE_NEWARR);
7281                                 }
7282                         }
7283
7284                         if (shared_access) {
7285                                 MonoInst *this, *rgctx;
7286                                 MonoInst *args [3];
7287                                 int temp;
7288
7289                                 /* domain */
7290                                 NEW_DOMAINCONST (cfg, args [0]);
7291
7292                                 /* klass */
7293                                 NEW_ARGLOAD (cfg, this, 0);
7294                                 rgctx = get_runtime_generic_context_from_this (cfg, this, ip);
7295                                 args [1] = get_runtime_generic_context_ptr (cfg, method, bblock, klass,
7296                                         token, generic_context, rgctx, MINI_RGCTX_KLASS, ip);
7297
7298                                 /* array len */
7299                                 args [2] = *sp;
7300
7301                                 temp = mono_emit_jit_icall (cfg, bblock, mono_array_new, args, ip);
7302                                 NEW_TEMPLOAD (cfg, ins, temp);
7303                         } else {
7304                                 MONO_INST_NEW (cfg, ins, *ip);
7305                                 ins->cil_code = ip;
7306                                 ins->inst_newa_class = klass;
7307                                 ins->inst_newa_len = *sp;
7308                                 ins->type = STACK_OBJ;
7309                                 ins->klass = mono_array_class_get (klass, 1);
7310                         }
7311
7312                         ip += 5;
7313                         *sp++ = ins;
7314                         /* 
7315                          * we store the object so calls to create the array are not interleaved
7316                          * with the arguments of other calls.
7317                          */
7318                         if (1) {
7319                                 MonoInst *store, *temp, *load;
7320                                 const char *data_ptr;
7321                                 int data_size = 0;
7322                                 --sp;
7323                                 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
7324                                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
7325                                 store->cil_code = ins->cil_code;
7326                                 MONO_ADD_INS (bblock, store);
7327                                 /* 
7328                                  * we inline/optimize the initialization sequence if possible.
7329                                  * we should also allocate the array as not cleared, since we spend as much time clearing to 0 as initializing
7330                                  * for small sizes open code the memcpy
7331                                  * ensure the rva field is big enough
7332                                  */
7333                                 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))) {
7334                                         MonoMethod *memcpy_method = get_memcpy_method ();
7335                                         MonoInst *data_offset, *add;
7336                                         MonoInst *iargs [3];
7337                                         NEW_ICONST (cfg, iargs [2], data_size);
7338                                         NEW_TEMPLOAD (cfg, load, temp->inst_c0);
7339                                         load->cil_code = ins->cil_code;
7340                                         NEW_ICONST (cfg, data_offset, G_STRUCT_OFFSET (MonoArray, vector));
7341                                         MONO_INST_NEW (cfg, add, OP_PADD);
7342                                         add->inst_left = load;
7343                                         add->inst_right = data_offset;
7344                                         add->cil_code = ip;
7345                                         iargs [0] = add;
7346                                         if (cfg->compile_aot) {
7347                                                 NEW_AOTCONST_TOKEN (cfg, iargs [1], MONO_PATCH_INFO_RVA, method->klass->image, GPOINTER_TO_UINT(data_ptr), STACK_PTR, NULL);
7348                                         } else {
7349                                                 NEW_PCONST (cfg, iargs [1], (char*)data_ptr);
7350                                         }
7351                                         mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
7352                                         ip += 11;
7353                                 }
7354                                 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
7355                                 load->cil_code = ins->cil_code;
7356                                 *sp++ = load;
7357                         }
7358                         inline_costs += 1;
7359                         break;
7360                 }
7361                 case CEE_LDLEN:
7362                         CHECK_STACK (1);
7363                         --sp;
7364                         if (sp [0]->type != STACK_OBJ)
7365                                 UNVERIFIED;
7366                         MONO_INST_NEW (cfg, ins, *ip);
7367                         ins->cil_code = ip++;
7368                         ins->inst_left = *sp;
7369                         ins->type = STACK_PTR;
7370                         *sp++ = ins;
7371                         break;
7372                 case CEE_LDELEMA:
7373                         CHECK_STACK (2);
7374                         sp -= 2;
7375                         CHECK_OPSIZE (5);
7376                         if (sp [0]->type != STACK_OBJ)
7377                                 UNVERIFIED;
7378
7379                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
7380                         CHECK_TYPELOAD (klass);
7381                         /* we need to make sure that this array is exactly the type it needs
7382                          * to be for correctness. the wrappers are lax with their usage
7383                          * so we need to ignore them here
7384                          */
7385                         if (!klass->valuetype && method->wrapper_type == MONO_WRAPPER_NONE) {
7386                                 MonoInst* check;
7387
7388                                 /* Needed by the code generated in inssel.brg */
7389                                 mono_get_got_var (cfg);
7390
7391                                 MONO_INST_NEW (cfg, check, OP_CHECK_ARRAY_TYPE);
7392                                 check->cil_code = ip;
7393                                 check->klass = klass;
7394                                 check->inst_left = sp [0];
7395                                 check->type = STACK_OBJ;
7396                                 check->klass = klass;
7397                                 sp [0] = check;
7398                         }
7399                         
7400                         mono_class_init (klass);
7401                         NEW_LDELEMA (cfg, ins, sp, klass);
7402                         ins->cil_code = ip;
7403                         *sp++ = ins;
7404                         ip += 5;
7405                         break;
7406                 case CEE_LDELEM_ANY: {
7407                         MonoInst *load;
7408                         CHECK_STACK (2);
7409                         sp -= 2;
7410                         if (sp [0]->type != STACK_OBJ)
7411                                 UNVERIFIED;
7412                         CHECK_OPSIZE (5);
7413                         token = read32 (ip + 1);
7414                         klass = mini_get_class (method, token, generic_context);
7415                         CHECK_TYPELOAD (klass);
7416                         mono_class_init (klass);
7417                         NEW_LDELEMA (cfg, load, sp, klass);
7418                         load->cil_code = ip;
7419                         MONO_INST_NEW (cfg, ins, mini_type_to_ldind (cfg, &klass->byval_arg));
7420                         ins->cil_code = ip;
7421                         ins->inst_left = load;
7422                         *sp++ = ins;
7423                         type_to_eval_stack_type (cfg, &klass->byval_arg, ins);
7424                         ip += 5;
7425                         break;
7426                 }
7427                 case CEE_LDELEM_I1:
7428                 case CEE_LDELEM_U1:
7429                 case CEE_LDELEM_I2:
7430                 case CEE_LDELEM_U2:
7431                 case CEE_LDELEM_I4:
7432                 case CEE_LDELEM_U4:
7433                 case CEE_LDELEM_I8:
7434                 case CEE_LDELEM_I:
7435                 case CEE_LDELEM_R4:
7436                 case CEE_LDELEM_R8:
7437                 case CEE_LDELEM_REF: {
7438                         MonoInst *load;
7439                         /*
7440                          * translate to:
7441                          * ldind.x (ldelema (array, index))
7442                          * ldelema does the bounds check
7443                          */
7444                         CHECK_STACK (2);
7445                         sp -= 2;
7446                         if (sp [0]->type != STACK_OBJ)
7447                                 UNVERIFIED;
7448                         klass = array_access_to_klass (*ip, sp [0]);
7449                         NEW_LDELEMA (cfg, load, sp, klass);
7450                         load->cil_code = ip;
7451 #ifdef MONO_ARCH_SOFT_FLOAT
7452                         if (*ip == CEE_LDELEM_R4) {
7453                                 int temp;
7454                                 temp = handle_load_float (cfg, bblock, load, ip);
7455                                 NEW_TEMPLOAD (cfg, *sp, temp);
7456                                 sp++;
7457                                 ++ip;
7458                                 break;
7459                         }
7460 #endif
7461                         MONO_INST_NEW (cfg, ins, ldelem_to_ldind [*ip - CEE_LDELEM_I1]);
7462                         ins->cil_code = ip;
7463                         ins->inst_left = load;
7464                         *sp++ = ins;
7465                         ins->type = ldind_type [ins->opcode - CEE_LDIND_I1];
7466                         ins->klass = klass;
7467                         ++ip;
7468                         break;
7469                 }
7470                 case CEE_STELEM_I:
7471                 case CEE_STELEM_I1:
7472                 case CEE_STELEM_I2:
7473                 case CEE_STELEM_I4:
7474                 case CEE_STELEM_I8:
7475                 case CEE_STELEM_R4:
7476                 case CEE_STELEM_R8: {
7477                         MonoInst *load;
7478                         /*
7479                          * translate to:
7480                          * stind.x (ldelema (array, index), val)
7481                          * ldelema does the bounds check
7482                          */
7483                         CHECK_STACK (3);
7484                         sp -= 3;
7485                         if (sp [0]->type != STACK_OBJ)
7486                                 UNVERIFIED;
7487                         klass = array_access_to_klass (*ip, sp [0]);
7488                         NEW_LDELEMA (cfg, load, sp, klass);
7489                         load->cil_code = ip;
7490 #ifdef MONO_ARCH_SOFT_FLOAT
7491                         if (*ip == CEE_STELEM_R4) {
7492                                 handle_store_float (cfg, bblock, load, sp [2], ip);
7493                                 ip++;
7494                                 break;
7495                         }
7496 #endif
7497                         MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
7498                         ins->cil_code = ip;
7499                         ins->inst_left = load;
7500                         ins->inst_right = sp [2];
7501                         ++ip;
7502                         handle_loaded_temps (cfg, bblock, stack_start, sp);
7503                         MONO_ADD_INS (bblock, ins);
7504                         inline_costs += 1;
7505                         break;
7506                 }
7507                 case CEE_STELEM_ANY: {
7508                         MonoInst *load;
7509                         /*
7510                          * translate to:
7511                          * stind.x (ldelema (array, index), val)
7512                          * ldelema does the bounds check
7513                          */
7514                         CHECK_STACK (3);
7515                         sp -= 3;
7516                         if (sp [0]->type != STACK_OBJ)
7517                                 UNVERIFIED;
7518                         CHECK_OPSIZE (5);
7519                         token = read32 (ip + 1);
7520                         klass = mini_get_class (method, token, generic_context);
7521                         CHECK_TYPELOAD (klass);
7522                         mono_class_init (klass);
7523                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
7524                                 /* storing a NULL doesn't need any of the complex checks in stelemref */
7525                                 if (sp [2]->opcode == OP_PCONST && sp [2]->inst_p0 == NULL) {
7526                                         MonoInst *load;
7527                                         NEW_LDELEMA (cfg, load, sp, mono_defaults.object_class);
7528                                         load->cil_code = ip;
7529                                         MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
7530                                         ins->cil_code = ip;
7531                                         ins->inst_left = load;
7532                                         ins->inst_right = sp [2];
7533                                         MONO_ADD_INS (bblock, ins);
7534                                 } else {
7535                                         MonoMethod* helper = mono_marshal_get_stelemref ();
7536                                         MonoInst *iargs [3];
7537                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
7538
7539                                         iargs [2] = sp [2];
7540                                         iargs [1] = sp [1];
7541                                         iargs [0] = sp [0];
7542
7543                                         mono_emit_method_call_spilled (cfg, bblock, helper, mono_method_signature (helper), iargs, ip, NULL);
7544                                 }
7545                         } else {
7546                                 NEW_LDELEMA (cfg, load, sp, klass);
7547                                 load->cil_code = ip;
7548
7549                                 n = mini_type_to_stind (cfg, &klass->byval_arg);
7550                                 /* FIXME: CEE_STIND_R4 */
7551                                 if (n == CEE_STOBJ)
7552                                         handle_stobj (cfg, bblock, load, sp [2], ip, klass, FALSE, FALSE, TRUE);
7553                                 else {
7554                                         MONO_INST_NEW (cfg, ins, n);
7555                                         ins->cil_code = ip;
7556                                         ins->inst_left = load;
7557                                         ins->inst_right = sp [2];
7558                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
7559                                         MONO_ADD_INS (bblock, ins);
7560                                 }
7561                         }
7562                         ip += 5;
7563                         inline_costs += 1;
7564                         break;
7565                 }
7566                 case CEE_STELEM_REF: {
7567                         MonoInst *iargs [3];
7568                         MonoMethod* helper = mono_marshal_get_stelemref ();
7569
7570                         CHECK_STACK (3);
7571                         sp -= 3;
7572                         if (sp [0]->type != STACK_OBJ)
7573                                 UNVERIFIED;
7574                         if (sp [2]->type != STACK_OBJ)
7575                                 UNVERIFIED;
7576
7577                         handle_loaded_temps (cfg, bblock, stack_start, sp);
7578
7579                         /* storing a NULL doesn't need any of the complex checks in stelemref */
7580                         if (sp [2]->opcode == OP_PCONST && sp [2]->inst_p0 == NULL) {
7581                                 MonoInst *load;
7582                                 NEW_LDELEMA (cfg, load, sp, mono_defaults.object_class);
7583                                 load->cil_code = ip;
7584                                 MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
7585                                 ins->cil_code = ip;
7586                                 ins->inst_left = load;
7587                                 ins->inst_right = sp [2];
7588                                 MONO_ADD_INS (bblock, ins);
7589                         } else {
7590                                 iargs [2] = sp [2];
7591                                 iargs [1] = sp [1];
7592                                 iargs [0] = sp [0];
7593                         
7594                                 mono_emit_method_call_spilled (cfg, bblock, helper, mono_method_signature (helper), iargs, ip, NULL);
7595                                 inline_costs += 1;
7596                         }
7597
7598                         ++ip;
7599                         break;
7600                 }
7601                 case CEE_CKFINITE: {
7602                         MonoInst *store, *temp;
7603                         CHECK_STACK (1);
7604
7605                         /* this instr. can throw exceptions as side effect,
7606                          * so we cant eliminate dead code which contains CKFINITE opdodes.
7607                          * Spilling to memory makes sure that we always perform
7608                          * this check */
7609
7610                         
7611                         MONO_INST_NEW (cfg, ins, OP_CKFINITE);
7612                         ins->cil_code = ip;
7613                         ins->inst_left = sp [-1];
7614                         temp = mono_compile_create_var (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL);
7615
7616                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
7617                         store->cil_code = ip;
7618                         MONO_ADD_INS (bblock, store);
7619
7620                         NEW_TEMPLOAD (cfg, sp [-1], temp->inst_c0);
7621                        
7622                         ++ip;
7623                         break;
7624                 }
7625                 case CEE_REFANYVAL:
7626                         CHECK_STACK (1);
7627                         MONO_INST_NEW (cfg, ins, *ip);
7628                         --sp;
7629                         CHECK_OPSIZE (5);
7630                         klass = mono_class_get_full (image, read32 (ip + 1), generic_context);
7631                         CHECK_TYPELOAD (klass);
7632                         mono_class_init (klass);
7633                         ins->type = STACK_MP;
7634                         ins->inst_left = *sp;
7635                         ins->klass = klass;
7636                         ins->inst_newa_class = klass;
7637                         ins->cil_code = ip;
7638                         ip += 5;
7639                         *sp++ = ins;
7640                         break;
7641                 case CEE_MKREFANY: {
7642                         MonoInst *loc, *klassconst;
7643
7644                         CHECK_STACK (1);
7645                         MONO_INST_NEW (cfg, ins, *ip);
7646                         --sp;
7647                         CHECK_OPSIZE (5);
7648                         klass = mono_class_get_full (image, read32 (ip + 1), generic_context);
7649                         CHECK_TYPELOAD (klass);
7650                         mono_class_init (klass);
7651                         ins->cil_code = ip;
7652
7653                         if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
7654                                 GENERIC_SHARING_FAILURE (CEE_MKREFANY);
7655
7656                         loc = mono_compile_create_var (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL);
7657                         NEW_TEMPLOADA (cfg, ins->inst_right, loc->inst_c0);
7658
7659                         NEW_PCONST (cfg, klassconst, klass);
7660                         NEW_GROUP (cfg, ins->inst_left, *sp, klassconst);
7661                         
7662                         MONO_ADD_INS (bblock, ins);
7663
7664                         NEW_TEMPLOAD (cfg, *sp, loc->inst_c0);
7665                         ++sp;
7666                         ip += 5;
7667                         break;
7668                 }
7669                 case CEE_LDTOKEN: {
7670                         gpointer handle;
7671                         MonoClass *handle_class;
7672
7673                         CHECK_STACK_OVF (1);
7674
7675                         CHECK_OPSIZE (5);
7676                         n = read32 (ip + 1);
7677
7678                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
7679                                 handle = mono_method_get_wrapper_data (method, n);
7680                                 handle_class = mono_method_get_wrapper_data (method, n + 1);
7681                                 if (handle_class == mono_defaults.typehandle_class)
7682                                         handle = &((MonoClass*)handle)->byval_arg;
7683                         }
7684                         else {
7685                                 handle = mono_ldtoken (image, n, &handle_class, generic_context);
7686                                 if (cfg->generic_sharing_context &&
7687                                                 mono_class_check_context_used (handle_class))
7688                                         GENERIC_SHARING_FAILURE (CEE_LDTOKEN);
7689                         }
7690                         if (!handle)
7691                                 goto load_error;
7692                         mono_class_init (handle_class);
7693
7694                         if (cfg->opt & MONO_OPT_SHARED) {
7695                                 int temp;
7696                                 MonoInst *res, *store, *addr, *vtvar, *iargs [3];
7697
7698                                 GENERIC_SHARING_FAILURE (CEE_LDTOKEN);
7699
7700                                 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL); 
7701
7702                                 NEW_IMAGECONST (cfg, iargs [0], image);
7703                                 NEW_ICONST (cfg, iargs [1], n);
7704                                 NEW_PCONST (cfg, iargs [2], generic_context);
7705                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldtoken_wrapper, iargs, ip);
7706                                 NEW_TEMPLOAD (cfg, res, temp);
7707                                 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
7708                                 NEW_INDSTORE (cfg, store, addr, res, &mono_defaults.int_class->byval_arg);
7709                                 MONO_ADD_INS (bblock, store);
7710                                 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
7711                         } else {
7712                                 if ((ip [5] == CEE_CALL) && (cmethod = mini_get_method (method, read32 (ip + 6), NULL, generic_context)) &&
7713                                                 (cmethod->klass == mono_defaults.monotype_class->parent) &&
7714                                                 (strcmp (cmethod->name, "GetTypeFromHandle") == 0) && ip_in_bb (cfg, bblock, ip + 5)) {
7715                                         MonoClass *tclass = mono_class_from_mono_type (handle);
7716                                         mono_class_init (tclass);
7717                                         if (cfg->compile_aot)
7718                                                 NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, image, n);
7719                                         else
7720                                                 NEW_PCONST (cfg, ins, mono_type_get_object (cfg->domain, handle));
7721                                         ins->type = STACK_OBJ;
7722                                         ins->klass = cmethod->klass;
7723                                         ip += 5;
7724                                 } else {
7725                                         MonoInst *store, *addr, *vtvar;
7726
7727                                         if (cfg->compile_aot)
7728                                                 NEW_LDTOKENCONST (cfg, ins, image, n);
7729                                         else
7730                                                 NEW_PCONST (cfg, ins, handle);
7731                                         vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL);
7732                                         NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
7733                                         NEW_INDSTORE (cfg, store, addr, ins, &mono_defaults.int_class->byval_arg);
7734                                         MONO_ADD_INS (bblock, store);
7735                                         NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
7736                                 }
7737                         }
7738
7739                         *sp++ = ins;
7740                         ip += 5;
7741                         break;
7742                 }
7743                 case CEE_CONV_U2:
7744                 case CEE_CONV_U1:
7745                 case CEE_CONV_I:
7746                         CHECK_STACK (1);
7747                         ADD_UNOP (*ip);
7748                         ip++;
7749                         break;
7750                 case CEE_ADD_OVF:
7751                 case CEE_ADD_OVF_UN:
7752                 case CEE_MUL_OVF:
7753                 case CEE_MUL_OVF_UN:
7754                 case CEE_SUB_OVF:
7755                 case CEE_SUB_OVF_UN:
7756                         CHECK_STACK (2);
7757                         ADD_BINOP (*ip);
7758                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
7759                                 --sp;
7760                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
7761                         }
7762                         ip++;
7763                         break;
7764                 case CEE_ENDFINALLY:
7765                         MONO_INST_NEW (cfg, ins, OP_ENDFINALLY);
7766                         MONO_ADD_INS (bblock, ins);
7767                         ins->cil_code = ip++;
7768                         start_new_bblock = 1;
7769
7770                         /*
7771                          * Control will leave the method so empty the stack, otherwise
7772                          * the next basic block will start with a nonempty stack.
7773                          */
7774                         while (sp != stack_start) {
7775                                 MONO_INST_NEW (cfg, ins, CEE_POP);
7776                                 ins->cil_code = ip;
7777                                 sp--;
7778                                 ins->inst_i0 = *sp;
7779                                 MONO_ADD_INS (bblock, ins);
7780                         }
7781                         break;
7782                 case CEE_LEAVE:
7783                 case CEE_LEAVE_S: {
7784                         GList *handlers;
7785
7786                         if (*ip == CEE_LEAVE) {
7787                                 CHECK_OPSIZE (5);
7788                                 target = ip + 5 + (gint32)read32(ip + 1);
7789                         } else {
7790                                 CHECK_OPSIZE (2);
7791                                 target = ip + 2 + (signed char)(ip [1]);
7792                         }
7793
7794                         /* empty the stack */
7795                         while (sp != stack_start) {
7796                                 MONO_INST_NEW (cfg, ins, CEE_POP);
7797                                 ins->cil_code = ip;
7798                                 sp--;
7799                                 ins->inst_i0 = *sp;
7800                                 MONO_ADD_INS (bblock, ins);
7801                         }
7802
7803                         /* 
7804                          * If this leave statement is in a catch block, check for a
7805                          * pending exception, and rethrow it if necessary.
7806                          */
7807                         for (i = 0; i < header->num_clauses; ++i) {
7808                                 MonoExceptionClause *clause = &header->clauses [i];
7809
7810                                 /* 
7811                                  * Use <= in the final comparison to handle clauses with multiple
7812                                  * leave statements, like in bug #78024.
7813                                  * The ordering of the exception clauses guarantees that we find the
7814                                  * innermost clause.
7815                                  */
7816                                 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)) {
7817                                         int temp;
7818                                         MonoInst *load;
7819
7820                                         NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, clause->handler_offset)->inst_c0);
7821                                         load->cil_code = ip;
7822
7823                                         temp = mono_emit_jit_icall (cfg, bblock, mono_thread_get_undeniable_exception, NULL, ip);
7824                                         NEW_TEMPLOAD (cfg, *sp, temp);
7825                                 
7826                                         MONO_INST_NEW (cfg, ins, OP_THROW_OR_NULL);
7827                                         ins->inst_left = *sp;
7828                                         ins->inst_right = load;
7829                                         ins->cil_code = ip;
7830                                         MONO_ADD_INS (bblock, ins);
7831                                 }
7832                         }
7833
7834                         if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
7835                                 GList *tmp;
7836                                 for (tmp = handlers; tmp; tmp = tmp->next) {
7837                                         tblock = tmp->data;
7838                                         link_bblock (cfg, bblock, tblock);
7839                                         MONO_INST_NEW (cfg, ins, OP_CALL_HANDLER);
7840                                         ins->cil_code = ip;
7841                                         ins->inst_target_bb = tblock;
7842                                         MONO_ADD_INS (bblock, ins);
7843                                 }
7844                                 g_list_free (handlers);
7845                         } 
7846
7847                         MONO_INST_NEW (cfg, ins, OP_BR);
7848                         ins->cil_code = ip;
7849                         MONO_ADD_INS (bblock, ins);
7850                         GET_BBLOCK (cfg, tblock, target);
7851                         link_bblock (cfg, bblock, tblock);
7852                         CHECK_BBLOCK (target, ip, tblock);
7853                         ins->inst_target_bb = tblock;
7854                         start_new_bblock = 1;
7855
7856                         if (*ip == CEE_LEAVE)
7857                                 ip += 5;
7858                         else
7859                                 ip += 2;
7860
7861                         break;
7862                 }
7863                 case CEE_STIND_I:
7864                         CHECK_STACK (2);
7865                         MONO_INST_NEW (cfg, ins, *ip);
7866                         sp -= 2;
7867                         handle_loaded_temps (cfg, bblock, stack_start, sp);
7868                         MONO_ADD_INS (bblock, ins);
7869                         ins->cil_code = ip++;
7870                         ins->inst_i0 = sp [0];
7871                         ins->inst_i1 = sp [1];
7872                         inline_costs += 1;
7873                         break;
7874                 case CEE_CONV_U:
7875                         CHECK_STACK (1);
7876                         ADD_UNOP (*ip);
7877                         ip++;
7878                         break;
7879                 /* trampoline mono specific opcodes */
7880                 case MONO_CUSTOM_PREFIX: {
7881
7882                         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
7883
7884                         CHECK_OPSIZE (2);
7885                         switch (ip [1]) {
7886
7887                         case CEE_MONO_ICALL: {
7888                                 int temp;
7889                                 gpointer func;
7890                                 MonoJitICallInfo *info;
7891
7892                                 token = read32 (ip + 2);
7893                                 func = mono_method_get_wrapper_data (method, token);
7894                                 info = mono_find_jit_icall_by_addr (func);
7895                                 if (info == NULL){
7896                                         g_error ("An attempt has been made to perform an icall to address %p, "
7897                                                  "but the address has not been registered as an icall\n", info);
7898                                         g_assert_not_reached ();
7899                                 }
7900
7901                                 CHECK_STACK (info->sig->param_count);
7902                                 sp -= info->sig->param_count;
7903
7904                                 temp = mono_emit_jit_icall (cfg, bblock, info->func, sp, ip);
7905                                 if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
7906                                         NEW_TEMPLOAD (cfg, *sp, temp);
7907                                         sp++;
7908                                 }
7909
7910                                 ip += 6;
7911                                 inline_costs += 10 * num_calls++;
7912
7913                                 break;
7914                         }
7915                         case CEE_MONO_LDPTR:
7916                                 CHECK_STACK_OVF (1);
7917                                 CHECK_OPSIZE (6);
7918                                 token = read32 (ip + 2);
7919                                 NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
7920                                 ins->cil_code = ip;
7921                                 *sp++ = ins;
7922                                 ip += 6;
7923                                 inline_costs += 10 * num_calls++;
7924                                 /* Can't embed random pointers into AOT code */
7925                                 cfg->disable_aot = 1;
7926                                 break;
7927                         case CEE_MONO_VTADDR:
7928                                 CHECK_STACK (1);
7929                                 --sp;
7930                                 MONO_INST_NEW (cfg, ins, OP_VTADDR);
7931                                 ins->cil_code = ip;
7932                                 ins->type = STACK_MP;
7933                                 ins->inst_left = *sp;
7934                                 *sp++ = ins;
7935                                 ip += 2;
7936                                 break;
7937                         case CEE_MONO_NEWOBJ: {
7938                                 MonoInst *iargs [2];
7939                                 int temp;
7940                                 CHECK_STACK_OVF (1);
7941                                 CHECK_OPSIZE (6);
7942                                 token = read32 (ip + 2);
7943                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
7944                                 mono_class_init (klass);
7945                                 NEW_DOMAINCONST (cfg, iargs [0]);
7946                                 NEW_CLASSCONST (cfg, iargs [1], klass);
7947                                 temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
7948                                 NEW_TEMPLOAD (cfg, *sp, temp);
7949                                 sp++;
7950                                 ip += 6;
7951                                 inline_costs += 10 * num_calls++;
7952                                 break;
7953                         }
7954                         case CEE_MONO_OBJADDR:
7955                                 CHECK_STACK (1);
7956                                 --sp;
7957                                 MONO_INST_NEW (cfg, ins, OP_OBJADDR);
7958                                 ins->cil_code = ip;
7959                                 ins->type = STACK_MP;
7960                                 ins->inst_left = *sp;
7961                                 *sp++ = ins;
7962                                 ip += 2;
7963                                 break;
7964                         case CEE_MONO_LDNATIVEOBJ:
7965                                 CHECK_STACK (1);
7966                                 CHECK_OPSIZE (6);
7967                                 token = read32 (ip + 2);
7968                                 klass = mono_method_get_wrapper_data (method, token);
7969                                 g_assert (klass->valuetype);
7970                                 mono_class_init (klass);
7971                                 NEW_INDLOAD (cfg, ins, sp [-1], &klass->byval_arg);
7972                                 sp [-1] = ins;
7973                                 ip += 6;
7974                                 break;
7975                         case CEE_MONO_RETOBJ:
7976                                 g_assert (cfg->ret);
7977                                 g_assert (mono_method_signature (method)->pinvoke); 
7978                                 CHECK_STACK (1);
7979                                 --sp;
7980                                 
7981                                 CHECK_OPSIZE (6);
7982                                 token = read32 (ip + 2);    
7983                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
7984
7985                                 NEW_RETLOADA (cfg, ins);
7986                                 handle_stobj (cfg, bblock, ins, *sp, ip, klass, FALSE, TRUE, FALSE);
7987                                 
7988                                 if (sp != stack_start)
7989                                         UNVERIFIED;
7990                                 
7991                                 MONO_INST_NEW (cfg, ins, OP_BR);
7992                                 ins->cil_code = ip;
7993                                 ins->inst_target_bb = end_bblock;
7994                                 MONO_ADD_INS (bblock, ins);
7995                                 link_bblock (cfg, bblock, end_bblock);
7996                                 start_new_bblock = 1;
7997                                 ip += 6;
7998                                 break;
7999                         case CEE_MONO_CISINST:
8000                         case CEE_MONO_CCASTCLASS: {
8001                                 int token;
8002                                 CHECK_STACK (1);
8003                                 --sp;
8004                                 CHECK_OPSIZE (6);
8005                                 token = read32 (ip + 2);
8006                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
8007                                 MONO_INST_NEW (cfg, ins, (ip [1] == CEE_MONO_CISINST) ? OP_CISINST : OP_CCASTCLASS);
8008                                 ins->type = STACK_I4;
8009                                 ins->inst_left = *sp;
8010                                 ins->inst_newa_class = klass;
8011                                 ins->cil_code = ip;
8012                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 6);
8013                                 ip += 6;
8014                                 break;
8015                         }
8016                         case CEE_MONO_SAVE_LMF:
8017                         case CEE_MONO_RESTORE_LMF:
8018 #ifdef MONO_ARCH_HAVE_LMF_OPS
8019                                 MONO_INST_NEW (cfg, ins, (ip [1] == CEE_MONO_SAVE_LMF) ? OP_SAVE_LMF : OP_RESTORE_LMF);
8020                                 MONO_ADD_INS (bblock, ins);
8021                                 cfg->need_lmf_area = TRUE;
8022 #endif
8023                                 ip += 2;
8024                                 break;
8025                         case CEE_MONO_CLASSCONST:
8026                                 CHECK_STACK_OVF (1);
8027                                 CHECK_OPSIZE (6);
8028                                 token = read32 (ip + 2);
8029                                 NEW_CLASSCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
8030                                 ins->cil_code = ip;
8031                                 *sp++ = ins;
8032                                 ip += 6;
8033                                 inline_costs += 10 * num_calls++;
8034                                 break;
8035                         case CEE_MONO_NOT_TAKEN:
8036                                 bblock->out_of_line = TRUE;
8037                                 ip += 2;
8038                                 break;
8039                         case CEE_MONO_TLS:
8040                                 CHECK_STACK_OVF (1);
8041                                 CHECK_OPSIZE (6);
8042                                 MONO_INST_NEW (cfg, ins, OP_TLS_GET);
8043                                 ins->inst_offset = (gint32)read32 (ip + 2);
8044                                 ins->cil_code = ip;
8045                                 ins->type = STACK_PTR;
8046                                 *sp++ = ins;
8047                                 ip += 6;
8048                                 break;
8049                         default:
8050                                 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
8051                                 break;
8052                         }
8053                         break;
8054                 }
8055                 case CEE_PREFIX1: {
8056                         CHECK_OPSIZE (2);
8057                         switch (ip [1]) {
8058                         case CEE_ARGLIST: {
8059                                 /* somewhat similar to LDTOKEN */
8060                                 MonoInst *addr, *vtvar;
8061                                 CHECK_STACK_OVF (1);
8062                                 vtvar = mono_compile_create_var (cfg, &mono_defaults.argumenthandle_class->byval_arg, OP_LOCAL); 
8063
8064                                 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
8065                                 addr->cil_code = ip;
8066                                 MONO_INST_NEW (cfg, ins, OP_ARGLIST);
8067                                 ins->cil_code = ip;
8068                                 ins->inst_left = addr;
8069                                 MONO_ADD_INS (bblock, ins);
8070                                 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
8071                                 ins->cil_code = ip;
8072                                 *sp++ = ins;
8073                                 ip += 2;
8074                                 break;
8075                         }
8076                         case CEE_CEQ:
8077                         case CEE_CGT:
8078                         case CEE_CGT_UN:
8079                         case CEE_CLT:
8080                         case CEE_CLT_UN: {
8081                                 MonoInst *cmp;
8082                                 CHECK_STACK (2);
8083                                 /*
8084                                  * The following transforms:
8085                                  *    CEE_CEQ    into OP_CEQ
8086                                  *    CEE_CGT    into OP_CGT
8087                                  *    CEE_CGT_UN into OP_CGT_UN
8088                                  *    CEE_CLT    into OP_CLT
8089                                  *    CEE_CLT_UN into OP_CLT_UN
8090                                  */
8091                                 MONO_INST_NEW (cfg, cmp, 256 + ip [1]);
8092                                 
8093                                 MONO_INST_NEW (cfg, ins, cmp->opcode);
8094                                 sp -= 2;
8095                                 cmp->inst_i0 = sp [0];
8096                                 cmp->inst_i1 = sp [1];
8097                                 cmp->cil_code = ip;
8098                                 type_from_op (cmp);
8099                                 CHECK_TYPE (cmp);
8100                                 ins->cil_code = ip;
8101                                 ins->type = STACK_I4;
8102                                 ins->inst_i0 = cmp;
8103 #if MONO_ARCH_SOFT_FLOAT
8104                                 if (sp [0]->type == STACK_R8) {
8105                                         cmp->type = STACK_I4;
8106                                         *sp++ = emit_tree (cfg, bblock, cmp, ip + 2);
8107                                         ip += 2;
8108                                         break;
8109                                 }
8110 #endif
8111                                 if ((sp [0]->type == STACK_I8) || ((sizeof (gpointer) == 8) && ((sp [0]->type == STACK_PTR) || (sp [0]->type == STACK_OBJ) || (sp [0]->type == STACK_MP))))
8112                                         cmp->opcode = OP_LCOMPARE;
8113                                 else
8114                                         cmp->opcode = OP_COMPARE;
8115                                 *sp++ = ins;
8116                                 /* spill it to reduce the expression complexity
8117                                  * and workaround bug 54209 
8118                                  */
8119                                 if (cmp->inst_left->type == STACK_I8) {
8120                                         --sp;
8121                                         *sp++ = emit_tree (cfg, bblock, ins, ip + 2);
8122                                 }
8123                                 ip += 2;
8124                                 break;
8125                         }
8126                         case CEE_LDFTN: {
8127                                 MonoInst *argconst;
8128                                 MonoMethod *cil_method, *ctor_method;
8129                                 int temp;
8130
8131                                 CHECK_STACK_OVF (1);
8132                                 CHECK_OPSIZE (6);
8133                                 n = read32 (ip + 2);
8134                                 cmethod = mini_get_method (method, n, NULL, generic_context);
8135                                 if (!cmethod)
8136                                         goto load_error;
8137                                 mono_class_init (cmethod->klass);
8138
8139                                 if (cfg->generic_sharing_context && mono_method_check_context_used (cmethod))
8140                                         GENERIC_SHARING_FAILURE (CEE_LDFTN);
8141
8142                                 cil_method = cmethod;
8143                                 if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_method (method, cmethod))
8144                                         METHOD_ACCESS_FAILURE;
8145                                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
8146                                         if (check_linkdemand (cfg, method, cmethod, bblock, ip))
8147                                                 INLINE_FAILURE;
8148                                         CHECK_CFG_EXCEPTION;
8149                                 } else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
8150                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod, bblock, ip);
8151                                 }
8152
8153                                 /* 
8154                                  * Optimize the common case of ldftn+delegate creation
8155                                  */
8156 #if defined(MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE) && !defined(HAVE_WRITE_BARRIERS)
8157                                 /* FIXME: SGEN support */
8158                                 if ((sp > stack_start) && (ip + 6 + 5 < end) && ip_in_bb (cfg, bblock, ip + 6) && (ip [6] == CEE_NEWOBJ) && (ctor_method = mini_get_method (method, read32 (ip + 7), NULL, generic_context)) && (ctor_method->klass->parent == mono_defaults.multicastdelegate_class)) {
8159                                         MonoInst *target_ins;
8160
8161                                         ip += 6;
8162                                         if (cfg->verbose_level > 3)
8163                                                 g_print ("converting (in B%d: stack: %d) %s", bblock->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
8164                                         target_ins = sp [-1];
8165                                         sp --;
8166                                         *sp = handle_delegate_ctor (cfg, bblock, ctor_method->klass, target_ins, cmethod, ip);
8167                                         ip += 5;                                        
8168                                         sp ++;
8169                                         break;
8170                                 }
8171 #endif
8172
8173                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
8174
8175                                 NEW_METHODCONST (cfg, argconst, cmethod);
8176                                 if (method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED)
8177                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn, &argconst, ip);
8178                                 else
8179                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn_nosync, &argconst, ip);
8180                                 NEW_TEMPLOAD (cfg, *sp, temp);
8181                                 sp ++;
8182                                 
8183                                 ip += 6;
8184                                 inline_costs += 10 * num_calls++;
8185                                 break;
8186                         }
8187                         case CEE_LDVIRTFTN: {
8188                                 MonoInst *args [2];
8189                                 int temp;
8190
8191                                 CHECK_STACK (1);
8192                                 CHECK_OPSIZE (6);
8193                                 n = read32 (ip + 2);
8194                                 cmethod = mini_get_method (method, n, NULL, generic_context);
8195                                 if (!cmethod)
8196                                         goto load_error;
8197                                 mono_class_init (cmethod->klass);
8198
8199                                 if (cfg->generic_sharing_context && mono_method_check_context_used (cmethod))
8200                                         GENERIC_SHARING_FAILURE (CEE_LDVIRTFTN);
8201
8202                                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
8203                                         if (check_linkdemand (cfg, method, cmethod, bblock, ip))
8204                                                 INLINE_FAILURE;
8205                                         CHECK_CFG_EXCEPTION;
8206                                 } else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
8207                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod, bblock, ip);
8208                                 }
8209
8210                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
8211
8212                                 --sp;
8213                                 args [0] = *sp;
8214                                 NEW_METHODCONST (cfg, args [1], cmethod);
8215                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldvirtfn, args, ip);
8216                                 NEW_TEMPLOAD (cfg, *sp, temp);
8217                                 sp ++;
8218
8219                                 ip += 6;
8220                                 inline_costs += 10 * num_calls++;
8221                                 break;
8222                         }
8223                         case CEE_LDARG:
8224                                 CHECK_STACK_OVF (1);
8225                                 CHECK_OPSIZE (4);
8226                                 n = read16 (ip + 2);
8227                                 CHECK_ARG (n);
8228                                 NEW_ARGLOAD (cfg, ins, n);
8229                                 LDARG_SOFT_FLOAT (cfg, ins, n, ip);
8230                                 ins->cil_code = ip;
8231                                 *sp++ = ins;
8232                                 ip += 4;
8233                                 break;
8234                         case CEE_LDARGA:
8235                                 CHECK_STACK_OVF (1);
8236                                 CHECK_OPSIZE (4);
8237                                 n = read16 (ip + 2);
8238                                 CHECK_ARG (n);
8239                                 NEW_ARGLOADA (cfg, ins, n);
8240                                 ins->cil_code = ip;
8241                                 *sp++ = ins;
8242                                 ip += 4;
8243                                 break;
8244                         case CEE_STARG:
8245                                 CHECK_STACK (1);
8246                                 --sp;
8247                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
8248                                 CHECK_OPSIZE (4);
8249                                 n = read16 (ip + 2);
8250                                 CHECK_ARG (n);
8251                                 NEW_ARGSTORE (cfg, ins, n, *sp);
8252                                 ins->cil_code = ip;
8253                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [n], *sp))
8254                                         UNVERIFIED;
8255                                 STARG_SOFT_FLOAT (cfg, ins, n, ip);
8256                                 if (ins->opcode == CEE_STOBJ) {
8257                                         NEW_ARGLOADA (cfg, ins, n);
8258                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
8259                                 } else
8260                                         MONO_ADD_INS (bblock, ins);
8261                                 ip += 4;
8262                                 break;
8263                         case CEE_LDLOC:
8264                                 CHECK_STACK_OVF (1);
8265                                 CHECK_OPSIZE (4);
8266                                 n = read16 (ip + 2);
8267                                 CHECK_LOCAL (n);
8268                                 NEW_LOCLOAD (cfg, ins, n);
8269                                 LDLOC_SOFT_FLOAT (cfg, ins, n, ip);
8270                                 ins->cil_code = ip;
8271                                 *sp++ = ins;
8272                                 ip += 4;
8273                                 break;
8274                         case CEE_LDLOCA:
8275                                 CHECK_STACK_OVF (1);
8276                                 CHECK_OPSIZE (4);
8277                                 n = read16 (ip + 2);
8278                                 CHECK_LOCAL (n);
8279                                 NEW_LOCLOADA (cfg, ins, n);
8280                                 ins->cil_code = ip;
8281                                 *sp++ = ins;
8282                                 ip += 4;
8283                                 break;
8284                         case CEE_STLOC:
8285                                 CHECK_STACK (1);
8286                                 --sp;
8287                                 CHECK_OPSIZE (4);
8288                                 n = read16 (ip + 2);
8289                                 CHECK_LOCAL (n);
8290                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
8291                                 NEW_LOCSTORE (cfg, ins, n, *sp);
8292                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
8293                                         UNVERIFIED;
8294                                 ins->cil_code = ip;
8295                                 STLOC_SOFT_FLOAT (cfg, ins, n, ip);
8296                                 if (ins->opcode == CEE_STOBJ) {
8297                                         NEW_LOCLOADA (cfg, ins, n);
8298                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
8299                                 } else
8300                                         MONO_ADD_INS (bblock, ins);
8301                                 ip += 4;
8302                                 inline_costs += 1;
8303                                 break;
8304                         case CEE_LOCALLOC:
8305                                 CHECK_STACK (1);
8306                                 --sp;
8307                                 if (sp != stack_start) 
8308                                         UNVERIFIED;
8309                                 if (cfg->method != method) 
8310                                         /* 
8311                                          * Inlining this into a loop in a parent could lead to 
8312                                          * stack overflows which is different behavior than the
8313                                          * non-inlined case, thus disable inlining in this case.
8314                                          */
8315                                         goto inline_failure;
8316                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
8317                                 ins->inst_left = *sp;
8318                                 ins->cil_code = ip;
8319                                 ins->type = STACK_PTR;
8320
8321                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
8322                                 if (header->init_locals)
8323                                         ins->flags |= MONO_INST_INIT;
8324
8325                                 *sp++ = ins;
8326                                 ip += 2;
8327                                 /* FIXME: set init flag if locals init is set in this method */
8328                                 break;
8329                         case CEE_ENDFILTER: {
8330                                 MonoExceptionClause *clause, *nearest;
8331                                 int cc, nearest_num;
8332
8333                                 CHECK_STACK (1);
8334                                 --sp;
8335                                 if ((sp != stack_start) || (sp [0]->type != STACK_I4)) 
8336                                         UNVERIFIED;
8337                                 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
8338                                 ins->inst_left = *sp;
8339                                 ins->cil_code = ip;
8340                                 MONO_ADD_INS (bblock, ins);
8341                                 start_new_bblock = 1;
8342                                 ip += 2;
8343
8344                                 nearest = NULL;
8345                                 nearest_num = 0;
8346                                 for (cc = 0; cc < header->num_clauses; ++cc) {
8347                                         clause = &header->clauses [cc];
8348                                         if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
8349                                                 ((ip - header->code) > clause->data.filter_offset && (ip - header->code) <= clause->handler_offset) &&
8350                                             (!nearest || (clause->data.filter_offset < nearest->data.filter_offset))) {
8351                                                 nearest = clause;
8352                                                 nearest_num = cc;
8353                                         }
8354                                 }
8355                                 g_assert (nearest);
8356                                 if ((ip - header->code) != nearest->handler_offset)
8357                                         UNVERIFIED;
8358
8359                                 break;
8360                         }
8361                         case CEE_UNALIGNED_:
8362                                 ins_flag |= MONO_INST_UNALIGNED;
8363                                 /* FIXME: record alignment? we can assume 1 for now */
8364                                 CHECK_OPSIZE (3);
8365                                 ip += 3;
8366                                 break;
8367                         case CEE_VOLATILE_:
8368                                 ins_flag |= MONO_INST_VOLATILE;
8369                                 ip += 2;
8370                                 break;
8371                         case CEE_TAIL_:
8372                                 ins_flag   |= MONO_INST_TAILCALL;
8373                                 cfg->flags |= MONO_CFG_HAS_TAIL;
8374                                 /* Can't inline tail calls at this time */
8375                                 inline_costs += 100000;
8376                                 ip += 2;
8377                                 break;
8378                         case CEE_INITOBJ:
8379                                 CHECK_STACK (1);
8380                                 --sp;
8381                                 CHECK_OPSIZE (6);
8382                                 token = read32 (ip + 2);
8383                                 klass = mini_get_class (method, token, generic_context);
8384                                 CHECK_TYPELOAD (klass);
8385
8386                                 if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
8387                                         GENERIC_SHARING_FAILURE (CEE_INITOBJ);
8388
8389                                 if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
8390                                         MonoInst *store, *load;
8391                                         NEW_PCONST (cfg, load, NULL);
8392                                         load->cil_code = ip;
8393                                         load->type = STACK_OBJ;
8394                                         load->klass = klass;
8395                                         MONO_INST_NEW (cfg, store, CEE_STIND_REF);
8396                                         store->cil_code = ip;
8397                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
8398                                         MONO_ADD_INS (bblock, store);
8399                                         store->inst_i0 = sp [0];
8400                                         store->inst_i1 = load;
8401                                 } else {
8402                                         handle_initobj (cfg, bblock, *sp, NULL, klass, stack_start, sp);
8403                                 }
8404                                 ip += 6;
8405                                 inline_costs += 1;
8406                                 break;
8407                         case CEE_CONSTRAINED_:
8408                                 /* FIXME: implement */
8409                                 CHECK_OPSIZE (6);
8410                                 token = read32 (ip + 2);
8411                                 constrained_call = mono_class_get_full (image, token, generic_context);
8412                                 CHECK_TYPELOAD (constrained_call);
8413                                 ip += 6;
8414                                 break;
8415                         case CEE_CPBLK:
8416                         case CEE_INITBLK: {
8417                                 MonoInst *iargs [3];
8418                                 CHECK_STACK (3);
8419                                 sp -= 3;
8420                                 if ((cfg->opt & MONO_OPT_INTRINS) && (ip [1] == CEE_CPBLK) && (sp [2]->opcode == OP_ICONST) && ((n = sp [2]->inst_c0) <= sizeof (gpointer) * 5)) {
8421                                         MonoInst *copy;
8422                                         NEW_MEMCPY (cfg, copy, sp [0], sp [1], n, 0);
8423                                         MONO_ADD_INS (bblock, copy);
8424                                         ip += 2;
8425                                         break;
8426                                 }
8427                                 iargs [0] = sp [0];
8428                                 iargs [1] = sp [1];
8429                                 iargs [2] = sp [2];
8430                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
8431                                 if (ip [1] == CEE_CPBLK) {
8432                                         MonoMethod *memcpy_method = get_memcpy_method ();
8433                                         mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
8434                                 } else {
8435                                         MonoMethod *memset_method = get_memset_method ();
8436                                         mono_emit_method_call_spilled (cfg, bblock, memset_method, memset_method->signature, iargs, ip, NULL);
8437                                 }
8438                                 ip += 2;
8439                                 inline_costs += 1;
8440                                 break;
8441                         }
8442                         case CEE_NO_:
8443                                 CHECK_OPSIZE (3);
8444                                 if (ip [2] & 0x1)
8445                                         ins_flag |= MONO_INST_NOTYPECHECK;
8446                                 if (ip [2] & 0x2)
8447                                         ins_flag |= MONO_INST_NORANGECHECK;
8448                                 /* we ignore the no-nullcheck for now since we
8449                                  * really do it explicitly only when doing callvirt->call
8450                                  */
8451                                 ip += 3;
8452                                 break;
8453                         case CEE_RETHROW: {
8454                                 MonoInst *load;
8455                                 int handler_offset = -1;
8456
8457                                 for (i = 0; i < header->num_clauses; ++i) {
8458                                         MonoExceptionClause *clause = &header->clauses [i];
8459                                         if (MONO_OFFSET_IN_HANDLER (clause, ip - header->code) && !(clause->flags & MONO_EXCEPTION_CLAUSE_FINALLY))
8460                                                 handler_offset = clause->handler_offset;
8461                                 }
8462
8463                                 bblock->flags |= BB_EXCEPTION_UNSAFE;
8464
8465                                 g_assert (handler_offset != -1);
8466
8467                                 NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, handler_offset)->inst_c0);
8468                                 load->cil_code = ip;
8469                                 MONO_INST_NEW (cfg, ins, OP_RETHROW);
8470                                 ins->inst_left = load;
8471                                 ins->cil_code = ip;
8472                                 MONO_ADD_INS (bblock, ins);
8473                                 sp = stack_start;
8474                                 link_bblock (cfg, bblock, end_bblock);
8475                                 start_new_bblock = 1;
8476                                 ip += 2;
8477                                 break;
8478                         }
8479                         case CEE_SIZEOF:
8480                                 GENERIC_SHARING_FAILURE (CEE_SIZEOF);
8481
8482                                 CHECK_STACK_OVF (1);
8483                                 CHECK_OPSIZE (6);
8484                                 token = read32 (ip + 2);
8485                                 /* FIXXME: handle generics. */
8486                                 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC) {
8487                                         MonoType *type = mono_type_create_from_typespec (image, token);
8488                                         token = mono_type_size (type, &ialign);
8489                                 } else {
8490                                         MonoClass *klass = mono_class_get_full (image, token, generic_context);
8491                                         CHECK_TYPELOAD (klass);
8492                                         mono_class_init (klass);
8493                                         token = mono_class_value_size (klass, &align);
8494                                 }
8495                                 NEW_ICONST (cfg, ins, token);
8496                                 ins->cil_code = ip;
8497                                 *sp++= ins;
8498                                 ip += 6;
8499                                 break;
8500                         case CEE_REFANYTYPE:
8501                                 CHECK_STACK (1);
8502                                 MONO_INST_NEW (cfg, ins, OP_REFANYTYPE);
8503                                 --sp;
8504                                 ins->type = STACK_MP;
8505                                 ins->inst_left = *sp;
8506                                 ins->type = STACK_VTYPE;
8507                                 ins->klass = mono_defaults.typehandle_class;
8508                                 ins->cil_code = ip;
8509                                 ip += 2;
8510                                 *sp++ = ins;
8511                                 break;
8512                         case CEE_READONLY_:
8513                                 ip += 2;
8514                                 break;
8515                         default:
8516                                 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
8517                         }
8518                         break;
8519                 }
8520                 default:
8521                         g_error ("opcode 0x%02x not handled", *ip);
8522                 }
8523         }
8524         if (start_new_bblock != 1)
8525                 UNVERIFIED;
8526
8527         bblock->cil_length = ip - bblock->cil_code;
8528         bblock->next_bb = end_bblock;
8529
8530         if (cfg->method == method && cfg->domainvar) {
8531                 MonoInst *store;
8532                 MonoInst *get_domain;
8533                 
8534                 if (! (get_domain = mono_arch_get_domain_intrinsic (cfg))) {
8535                         MonoCallInst *call;
8536                         
8537                         MONO_INST_NEW_CALL (cfg, call, OP_CALL);
8538                         call->signature = helper_sig_domain_get;
8539                         call->inst.type = STACK_PTR;
8540                         call->fptr = mono_domain_get;
8541                         get_domain = (MonoInst*)call;
8542                 }
8543                 
8544                 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, get_domain);
8545                 MONO_ADD_INS (init_localsbb, store);
8546         }
8547
8548         if (cfg->method == method && cfg->got_var)
8549                 mono_emit_load_got_addr (cfg);
8550
8551         if (header->init_locals) {
8552                 MonoInst *store;
8553                 for (i = 0; i < header->num_locals; ++i) {
8554                         MonoType *ptype = header->locals [i];
8555                         int t = ptype->type;
8556                         if (t == MONO_TYPE_VALUETYPE && ptype->data.klass->enumtype)
8557                                 t = ptype->data.klass->enum_basetype->type;
8558                         if (ptype->byref) {
8559                                 NEW_PCONST (cfg, ins, NULL);
8560                                 NEW_LOCSTORE (cfg, store, i, ins);
8561                                 MONO_ADD_INS (init_localsbb, store);
8562                         } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
8563                                 NEW_ICONST (cfg, ins, 0);
8564                                 NEW_LOCSTORE (cfg, store, i, ins);
8565                                 MONO_ADD_INS (init_localsbb, store);
8566                         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
8567                                 MONO_INST_NEW (cfg, ins, OP_I8CONST);
8568                                 ins->type = STACK_I8;
8569                                 ins->inst_l = 0;
8570                                 NEW_LOCSTORE (cfg, store, i, ins);
8571                                 MONO_ADD_INS (init_localsbb, store);
8572                         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
8573 #ifdef MONO_ARCH_SOFT_FLOAT
8574                                 /* FIXME: handle init of R4 */
8575 #else
8576                                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
8577                                 ins->type = STACK_R8;
8578                                 ins->inst_p0 = (void*)&r8_0;
8579                                 NEW_LOCSTORE (cfg, store, i, ins);
8580                                 MONO_ADD_INS (init_localsbb, store);
8581 #endif
8582                         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
8583                                    ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (ptype))) {
8584                                 NEW_LOCLOADA (cfg, ins, i);
8585                                 handle_initobj (cfg, init_localsbb, ins, NULL, mono_class_from_mono_type (ptype), NULL, NULL);
8586                         } else {
8587                                 NEW_PCONST (cfg, ins, NULL);
8588                                 NEW_LOCSTORE (cfg, store, i, ins);
8589                                 MONO_ADD_INS (init_localsbb, store);
8590                         }
8591                 }
8592         }
8593
8594         /* resolve backward branches in the middle of an existing basic block */
8595         for (tmp = bb_recheck; tmp; tmp = tmp->next) {
8596                 bblock = tmp->data;
8597                 /*g_print ("need recheck in %s at IL_%04x\n", method->name, bblock->cil_code - header->code);*/
8598                 tblock = find_previous (cfg->cil_offset_to_bb, header->code_size, start_bblock, bblock->cil_code);
8599                 if (tblock != start_bblock) {
8600                         int l;
8601                         split_bblock (cfg, tblock, bblock);
8602                         l = bblock->cil_code - header->code;
8603                         bblock->cil_length = tblock->cil_length - l;
8604                         tblock->cil_length = l;
8605                 } else {
8606                         g_print ("recheck failed.\n");
8607                 }
8608         }
8609
8610         if (cfg->method == method) {
8611                 MonoBasicBlock *bb;
8612                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
8613                         bb->region = mono_find_block_region (cfg, bb->real_offset);
8614                         if (cfg->spvars)
8615                                 mono_create_spvar_for_region (cfg, bb->region);
8616                         if (cfg->verbose_level > 2)
8617                                 g_print ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
8618                 }
8619         }
8620
8621         g_slist_free (class_inits);
8622         dont_inline = g_list_remove (dont_inline, method);
8623
8624         if (inline_costs < 0) {
8625                 char *mname;
8626
8627                 /* Method is too large */
8628                 mname = mono_method_full_name (method, TRUE);
8629                 cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
8630                 cfg->exception_message = g_strdup_printf ("Method %s is too complex.", mname);
8631                 g_free (mname);
8632                 return -1;
8633         }
8634
8635         return inline_costs;
8636
8637  exception_exit:
8638         g_assert (cfg->exception_type != MONO_EXCEPTION_NONE);
8639         g_slist_free (class_inits);
8640         dont_inline = g_list_remove (dont_inline, method);
8641         return -1;
8642
8643  inline_failure:
8644         g_slist_free (class_inits);
8645         dont_inline = g_list_remove (dont_inline, method);
8646         return -1;
8647
8648  load_error:
8649         g_slist_free (class_inits);
8650         dont_inline = g_list_remove (dont_inline, method);
8651         cfg->exception_type = MONO_EXCEPTION_TYPE_LOAD;
8652         return -1;
8653
8654  unverified:
8655         g_slist_free (class_inits);
8656         dont_inline = g_list_remove (dont_inline, method);
8657         set_exception_type_from_invalid_il (cfg, method, ip);
8658         return -1;
8659 }
8660
8661 void
8662 mono_print_tree (MonoInst *tree) {
8663         int arity;
8664
8665         if (!tree)
8666                 return;
8667
8668         arity = mono_burg_arity [tree->opcode];
8669
8670         printf (" %s%s", arity?"(":"",  mono_inst_name (tree->opcode));
8671
8672         switch (tree->opcode) {
8673         case OP_ICONST:
8674                 printf ("[%d]", (int)tree->inst_c0);
8675                 break;
8676         case OP_I8CONST:
8677                 printf ("[%lld]", (long long)tree->inst_l);
8678                 break;
8679         case OP_R8CONST:
8680                 printf ("[%f]", *(double*)tree->inst_p0);
8681                 break;
8682         case OP_R4CONST:
8683                 printf ("[%f]", *(float*)tree->inst_p0);
8684                 break;
8685         case OP_ARG:
8686         case OP_LOCAL:
8687                 printf ("[%d]", (int)tree->inst_c0);
8688                 break;
8689         case OP_REGOFFSET:
8690                 if (tree->inst_offset < 0)
8691                         printf ("[-0x%x(%s)]", (int)(-tree->inst_offset), mono_arch_regname (tree->inst_basereg));
8692                 else
8693                         printf ("[0x%x(%s)]", (int)(tree->inst_offset), mono_arch_regname (tree->inst_basereg));
8694                 break;
8695         case OP_REGVAR:
8696                 printf ("[%s]", mono_arch_regname (tree->dreg));
8697                 break;
8698         case CEE_NEWARR:
8699                 printf ("[%s]",  tree->inst_newa_class->name);
8700                 mono_print_tree (tree->inst_newa_len);
8701                 break;
8702         case OP_CALL:
8703         case OP_CALLVIRT:
8704         case OP_FCALL:
8705         case OP_FCALLVIRT:
8706         case OP_LCALL:
8707         case OP_LCALLVIRT:
8708         case OP_VCALL:
8709         case OP_VCALLVIRT:
8710         case OP_VOIDCALL:
8711         case OP_VOIDCALLVIRT:
8712         case OP_TRAMPCALL_VTABLE: {
8713                 MonoCallInst *call = (MonoCallInst*)tree;
8714                 if (call->method)
8715                         printf ("[%s]", call->method->name);
8716                 else if (call->fptr) {
8717                         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (call->fptr);
8718                         if (info)
8719                                 printf ("[%s]", info->name);
8720                 }
8721                 break;
8722         }
8723         case OP_PHI: {
8724                 int i;
8725                 printf ("[%d (", (int)tree->inst_c0);
8726                 for (i = 0; i < tree->inst_phi_args [0]; i++) {
8727                         if (i)
8728                                 printf (", ");
8729                         printf ("%d", tree->inst_phi_args [i + 1]);
8730                 }
8731                 printf (")]");
8732                 break;
8733         }
8734         case OP_RENAME:
8735         case OP_RETARG:
8736         case OP_NOP:
8737         case OP_JMP:
8738         case OP_BREAK:
8739                 break;
8740         case OP_LOAD_MEMBASE:
8741         case OP_LOADI4_MEMBASE:
8742         case OP_LOADU4_MEMBASE:
8743         case OP_LOADU1_MEMBASE:
8744         case OP_LOADI1_MEMBASE:
8745         case OP_LOADU2_MEMBASE:
8746         case OP_LOADI2_MEMBASE:
8747                 printf ("[%s] <- [%s + 0x%x]", mono_arch_regname (tree->dreg), mono_arch_regname (tree->inst_basereg), (int)tree->inst_offset);
8748                 break;
8749         case OP_BR:
8750         case OP_CALL_HANDLER:
8751                 printf ("[B%d]", tree->inst_target_bb->block_num);
8752                 break;
8753         case OP_SWITCH:
8754         case CEE_ISINST:
8755         case CEE_CASTCLASS:
8756         case OP_OUTARG:
8757         case OP_CALL_REG:
8758         case OP_FCALL_REG:
8759         case OP_LCALL_REG:
8760         case OP_VCALL_REG:
8761         case OP_VOIDCALL_REG:
8762                 mono_print_tree (tree->inst_left);
8763                 break;
8764         case CEE_BNE_UN:
8765         case CEE_BEQ:
8766         case CEE_BLT:
8767         case CEE_BLT_UN:
8768         case CEE_BGT:
8769         case CEE_BGT_UN:
8770         case CEE_BGE:
8771         case CEE_BGE_UN:
8772         case CEE_BLE:
8773         case CEE_BLE_UN:
8774                 printf ("[B%dB%d]", tree->inst_true_bb->block_num, tree->inst_false_bb->block_num);
8775                 mono_print_tree (tree->inst_left);
8776                 break;
8777         default:
8778                 if (!mono_arch_print_tree(tree, arity)) {
8779                         if (arity) {
8780                                 mono_print_tree (tree->inst_left);
8781                                 if (arity > 1)
8782                                         mono_print_tree (tree->inst_right);
8783                         }
8784                 }
8785                 break;
8786         }
8787
8788         if (arity)
8789                 printf (")");
8790 }
8791
8792 void
8793 mono_print_tree_nl (MonoInst *tree)
8794 {
8795         mono_print_tree (tree);
8796         printf ("\n");
8797 }
8798
8799 static void
8800 create_helper_signature (void)
8801 {
8802         helper_sig_domain_get = mono_create_icall_signature ("ptr");
8803         helper_sig_class_init_trampoline = mono_create_icall_signature ("void");
8804         helper_sig_generic_class_init_trampoline = mono_create_icall_signature ("void");
8805 }
8806
8807 gconstpointer
8808 mono_icall_get_wrapper (MonoJitICallInfo* callinfo)
8809 {
8810         char *name;
8811         MonoMethod *wrapper;
8812         gconstpointer trampoline;
8813         MonoDomain *domain = mono_get_root_domain ();
8814         
8815         if (callinfo->wrapper) {
8816                 return callinfo->wrapper;
8817         }
8818
8819         if (callinfo->trampoline)
8820                 return callinfo->trampoline;
8821
8822         /* 
8823          * We use the lock on the root domain instead of the JIT lock to protect 
8824          * callinfo->trampoline, since we do a lot of stuff inside the critical section.
8825          */
8826         mono_domain_lock (domain);
8827
8828         if (callinfo->trampoline) {
8829                 mono_domain_unlock (domain);
8830                 return callinfo->trampoline;
8831         }
8832
8833         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
8834         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
8835         g_free (name);
8836
8837         trampoline = mono_create_ftnptr (domain, mono_create_jit_trampoline_in_domain (domain, wrapper));
8838         mono_register_jit_icall_wrapper (callinfo, trampoline);
8839
8840         callinfo->trampoline = trampoline;
8841
8842         mono_domain_unlock (domain);
8843         
8844         return callinfo->trampoline;
8845 }
8846
8847 static void
8848 mono_init_trampolines (void)
8849 {
8850         mono_trampoline_code [MONO_TRAMPOLINE_GENERIC] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_GENERIC);
8851         mono_trampoline_code [MONO_TRAMPOLINE_JUMP] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_JUMP);
8852         mono_trampoline_code [MONO_TRAMPOLINE_CLASS_INIT] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_CLASS_INIT);
8853         mono_trampoline_code [MONO_TRAMPOLINE_GENERIC_CLASS_INIT] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_GENERIC_CLASS_INIT);
8854 #ifdef MONO_ARCH_AOT_SUPPORTED
8855         mono_trampoline_code [MONO_TRAMPOLINE_AOT] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_AOT);
8856         mono_trampoline_code [MONO_TRAMPOLINE_AOT_PLT] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_AOT_PLT);
8857 #endif
8858 #ifdef MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE
8859         mono_trampoline_code [MONO_TRAMPOLINE_DELEGATE] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_DELEGATE);
8860 #endif
8861 }
8862
8863 static void
8864 mono_init_exceptions (void)
8865 {
8866 #ifndef CUSTOM_EXCEPTION_HANDLING
8867         mono_arch_get_restore_context ();
8868         mono_arch_get_call_filter ();
8869         mono_arch_get_throw_exception ();
8870         mono_arch_get_rethrow_exception ();
8871 #endif
8872 }
8873
8874 guint8 *
8875 mono_get_trampoline_code (MonoTrampolineType tramp_type)
8876 {
8877         return mono_trampoline_code [tramp_type];
8878 }
8879
8880 gpointer
8881 mono_create_class_init_trampoline (MonoVTable *vtable)
8882 {
8883         gpointer code, ptr;
8884
8885         g_assert (!vtable->klass->generic_container);
8886
8887         /* previously created trampoline code */
8888         mono_domain_lock (vtable->domain);
8889         ptr = 
8890                 g_hash_table_lookup (vtable->domain->class_init_trampoline_hash,
8891                                                                   vtable);
8892         mono_domain_unlock (vtable->domain);
8893         if (ptr)
8894                 return ptr;
8895
8896         code = mono_arch_create_specific_trampoline (vtable, MONO_TRAMPOLINE_CLASS_INIT, vtable->domain, NULL);
8897
8898         ptr = mono_create_ftnptr (vtable->domain, code);
8899
8900         /* store trampoline address */
8901         mono_domain_lock (vtable->domain);
8902         g_hash_table_insert (vtable->domain->class_init_trampoline_hash,
8903                                                           vtable, ptr);
8904         mono_domain_unlock (vtable->domain);
8905
8906         mono_jit_lock ();
8907         if (!class_init_hash_addr)
8908                 class_init_hash_addr = g_hash_table_new (NULL, NULL);
8909         g_hash_table_insert (class_init_hash_addr, ptr, vtable);
8910         mono_jit_unlock ();
8911
8912         return ptr;
8913 }
8914
8915 gpointer
8916 mono_create_jump_trampoline (MonoDomain *domain, MonoMethod *method, 
8917                                                          gboolean add_sync_wrapper)
8918 {
8919         MonoJitInfo *ji;
8920         gpointer code;
8921         guint32 code_size;
8922
8923         if (add_sync_wrapper && method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
8924                 return mono_create_jump_trampoline (domain, mono_marshal_get_synchronized_wrapper (method), FALSE);
8925
8926         code = mono_jit_find_compiled_method (domain, method);
8927         if (code)
8928                 return code;
8929
8930         mono_domain_lock (domain);
8931         code = g_hash_table_lookup (domain->jump_trampoline_hash, method);
8932         mono_domain_unlock (domain);
8933         if (code)
8934                 return code;
8935
8936         code = mono_arch_create_specific_trampoline (method, MONO_TRAMPOLINE_JUMP, mono_domain_get (), &code_size);
8937
8938         mono_domain_lock (domain);
8939         ji = mono_mempool_alloc0 (domain->mp, sizeof (MonoJitInfo));
8940         mono_domain_unlock (domain);
8941         ji->code_start = code;
8942         ji->code_size = code_size;
8943         ji->method = method;
8944
8945         /*
8946          * mono_delegate_ctor needs to find the method metadata from the 
8947          * trampoline address, so we save it here.
8948          */
8949
8950         mono_jit_info_table_add (domain, ji);
8951
8952         mono_domain_lock (domain);
8953         g_hash_table_insert (domain->jump_trampoline_hash, method, ji->code_start);
8954         mono_domain_unlock (domain);
8955
8956         return ji->code_start;
8957 }
8958
8959 static gpointer
8960 mono_create_jit_trampoline_in_domain (MonoDomain *domain, MonoMethod *method)
8961 {
8962         gpointer tramp;
8963
8964         mono_domain_lock (domain);
8965         tramp = g_hash_table_lookup (domain->jit_trampoline_hash, method);
8966         mono_domain_unlock (domain);
8967         if (tramp)
8968                 return tramp;
8969
8970         if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
8971                 return mono_create_jit_trampoline (mono_marshal_get_synchronized_wrapper (method));
8972
8973         tramp = mono_arch_create_specific_trampoline (method, MONO_TRAMPOLINE_GENERIC, domain, NULL);
8974         
8975         mono_domain_lock (domain);
8976         g_hash_table_insert (domain->jit_trampoline_hash, method, tramp);
8977         mono_domain_unlock (domain);
8978
8979         mono_jit_stats.method_trampolines++;
8980
8981         return tramp;
8982 }       
8983
8984 gpointer
8985 mono_create_jit_trampoline (MonoMethod *method)
8986 {
8987         return mono_create_jit_trampoline_in_domain (mono_domain_get (), method);
8988 }
8989
8990 #ifdef MONO_ARCH_HAVE_CREATE_TRAMPOLINE_FROM_TOKEN
8991 gpointer
8992 mono_create_jit_trampoline_from_token (MonoImage *image, guint32 token)
8993 {
8994         gpointer tramp;
8995
8996         MonoDomain *domain = mono_domain_get ();
8997         guint8 *buf, *start;
8998
8999         mono_domain_lock (domain);
9000         buf = start = mono_code_manager_reserve (domain->code_mp, 2 * sizeof (gpointer));
9001         mono_domain_unlock (domain);
9002
9003         *(gpointer*)(gpointer)buf = image;
9004         buf += sizeof (gpointer);
9005         *(guint32*)(gpointer)buf = token;
9006
9007         tramp = mono_arch_create_specific_trampoline (start, MONO_TRAMPOLINE_AOT, domain, NULL);
9008
9009         mono_jit_stats.method_trampolines++;
9010
9011         return tramp;
9012 }       
9013 #endif
9014
9015 gpointer
9016 mono_create_delegate_trampoline (MonoClass *klass)
9017 {
9018 #ifdef MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE
9019         MonoDomain *domain = mono_domain_get ();
9020         gpointer ptr;
9021         guint32 code_size;
9022
9023         mono_domain_lock (domain);
9024         ptr = g_hash_table_lookup (domain->delegate_trampoline_hash, klass);
9025         mono_domain_unlock (domain);
9026         if (ptr)
9027                 return ptr;
9028
9029     ptr = mono_arch_create_specific_trampoline (klass, MONO_TRAMPOLINE_DELEGATE, mono_domain_get (), &code_size);
9030
9031         /* store trampoline address */
9032         mono_domain_lock (domain);
9033         g_hash_table_insert (domain->delegate_trampoline_hash,
9034                                                           klass, ptr);
9035         mono_domain_unlock (domain);
9036
9037         mono_jit_lock ();
9038         if (!delegate_trampoline_hash_addr)
9039                 delegate_trampoline_hash_addr = g_hash_table_new (NULL, NULL);
9040         g_hash_table_insert (delegate_trampoline_hash_addr, ptr, klass);
9041         mono_jit_unlock ();
9042
9043         return ptr;
9044 #else
9045         return NULL;
9046 #endif
9047 }
9048
9049 MonoVTable*
9050 mono_find_class_init_trampoline_by_addr (gconstpointer addr)
9051 {
9052         MonoVTable *res;
9053
9054         mono_jit_lock ();
9055         if (class_init_hash_addr)
9056                 res = g_hash_table_lookup (class_init_hash_addr, addr);
9057         else
9058                 res = NULL;
9059         mono_jit_unlock ();
9060         return res;
9061 }
9062
9063 static MonoClass*
9064 mono_find_delegate_trampoline_by_addr (gconstpointer addr)
9065 {
9066         MonoClass *res;
9067
9068         mono_jit_lock ();
9069         if (delegate_trampoline_hash_addr)
9070                 res = g_hash_table_lookup (delegate_trampoline_hash_addr, addr);
9071         else
9072                 res = NULL;
9073         mono_jit_unlock ();
9074         return res;
9075 }
9076
9077 static void
9078 mono_dynamic_code_hash_insert (MonoDomain *domain, MonoMethod *method, MonoJitDynamicMethodInfo *ji)
9079 {
9080         if (!domain->dynamic_code_hash)
9081                 domain->dynamic_code_hash = g_hash_table_new (NULL, NULL);
9082         g_hash_table_insert (domain->dynamic_code_hash, method, ji);
9083 }
9084
9085 static MonoJitDynamicMethodInfo*
9086 mono_dynamic_code_hash_lookup (MonoDomain *domain, MonoMethod *method)
9087 {
9088         MonoJitDynamicMethodInfo *res;
9089
9090         if (domain->dynamic_code_hash)
9091                 res = g_hash_table_lookup (domain->dynamic_code_hash, method);
9092         else
9093                 res = NULL;
9094         return res;
9095 }
9096
9097 typedef struct {
9098         MonoClass *vtype;
9099         GList *active;
9100         GSList *slots;
9101 } StackSlotInfo;
9102
9103 static inline GSList*
9104 g_slist_prepend_mempool (MonoMemPool *mp, GSList   *list,
9105                                                  gpointer  data)
9106 {
9107   GSList *new_list;
9108
9109   new_list = mono_mempool_alloc (mp, sizeof (GSList));
9110   new_list->data = data;
9111   new_list->next = list;
9112
9113   return new_list;
9114 }
9115
9116 /*
9117  *  mono_allocate_stack_slots_full:
9118  *
9119  *  Allocate stack slots for all non register allocated variables using a
9120  * linear scan algorithm.
9121  * Returns: an array of stack offsets.
9122  * STACK_SIZE is set to the amount of stack space needed.
9123  * STACK_ALIGN is set to the alignment needed by the locals area.
9124  */
9125 gint32*
9126 mono_allocate_stack_slots_full (MonoCompile *m, gboolean backward, guint32 *stack_size, guint32 *stack_align)
9127 {
9128         int i, slot, offset, size;
9129         guint32 align;
9130         MonoMethodVar *vmv;
9131         MonoInst *inst;
9132         gint32 *offsets;
9133         GList *vars = NULL, *l;
9134         StackSlotInfo *scalar_stack_slots, *vtype_stack_slots, *slot_info;
9135         MonoType *t;
9136         int nvtypes;
9137
9138         scalar_stack_slots = mono_mempool_alloc0 (m->mempool, sizeof (StackSlotInfo) * MONO_TYPE_PINNED);
9139         vtype_stack_slots = NULL;
9140         nvtypes = 0;
9141
9142         offsets = mono_mempool_alloc (m->mempool, sizeof (gint32) * m->num_varinfo);
9143         for (i = 0; i < m->num_varinfo; ++i)
9144                 offsets [i] = -1;
9145
9146         for (i = m->locals_start; i < m->num_varinfo; i++) {
9147                 inst = m->varinfo [i];
9148                 vmv = MONO_VARINFO (m, i);
9149
9150                 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR || inst->opcode == OP_REGOFFSET)
9151                         continue;
9152
9153                 vars = g_list_prepend (vars, vmv);
9154         }
9155
9156         vars = mono_varlist_sort (m, vars, 0);
9157         offset = 0;
9158         *stack_align = 0;
9159         for (l = vars; l; l = l->next) {
9160                 vmv = l->data;
9161                 inst = m->varinfo [vmv->idx];
9162
9163                 /* inst->backend.is_pinvoke indicates native sized value types, this is used by the
9164                 * pinvoke wrappers when they call functions returning structures */
9165                 if (inst->backend.is_pinvoke && MONO_TYPE_ISSTRUCT (inst->inst_vtype) && inst->inst_vtype->type != MONO_TYPE_TYPEDBYREF)
9166                         size = mono_class_native_size (inst->inst_vtype->data.klass, &align);
9167                 else {
9168                         int ialign;
9169
9170                         size = mono_type_size (inst->inst_vtype, &ialign);
9171                         align = ialign;
9172                 }
9173
9174                 t = mono_type_get_underlying_type (inst->inst_vtype);
9175                 if (t->byref) {
9176                         slot_info = &scalar_stack_slots [MONO_TYPE_I];
9177                 } else {
9178                         switch (t->type) {
9179                         case MONO_TYPE_GENERICINST:
9180                                 if (!mono_type_generic_inst_is_valuetype (t)) {
9181                                         slot_info = &scalar_stack_slots [t->type];
9182                                         break;
9183                                 }
9184                                 /* Fall through */
9185                         case MONO_TYPE_VALUETYPE:
9186                                 if (!vtype_stack_slots)
9187                                         vtype_stack_slots = mono_mempool_alloc0 (m->mempool, sizeof (StackSlotInfo) * 256);
9188                                 for (i = 0; i < nvtypes; ++i)
9189                                         if (t->data.klass == vtype_stack_slots [i].vtype)
9190                                                 break;
9191                                 if (i < nvtypes)
9192                                         slot_info = &vtype_stack_slots [i];
9193                                 else {
9194                                         g_assert (nvtypes < 256);
9195                                         vtype_stack_slots [nvtypes].vtype = t->data.klass;
9196                                         slot_info = &vtype_stack_slots [nvtypes];
9197                                         nvtypes ++;
9198                                 }
9199                                 break;
9200                         case MONO_TYPE_CLASS:
9201                         case MONO_TYPE_OBJECT:
9202                         case MONO_TYPE_ARRAY:
9203                         case MONO_TYPE_SZARRAY:
9204                         case MONO_TYPE_STRING:
9205                         case MONO_TYPE_PTR:
9206                         case MONO_TYPE_I:
9207                         case MONO_TYPE_U:
9208 #if SIZEOF_VOID_P == 4
9209                         case MONO_TYPE_I4:
9210 #else
9211                         case MONO_TYPE_I8:
9212 #endif
9213                                 /* Share non-float stack slots of the same size */
9214                                 slot_info = &scalar_stack_slots [MONO_TYPE_CLASS];
9215                                 break;
9216                         default:
9217                                 slot_info = &scalar_stack_slots [t->type];
9218                         }
9219                 }
9220
9221                 slot = 0xffffff;
9222                 if (m->comp_done & MONO_COMP_LIVENESS) {
9223                         //printf ("START  %2d %08x %08x\n",  vmv->idx, vmv->range.first_use.abs_pos, vmv->range.last_use.abs_pos);
9224                         
9225                         /* expire old intervals in active */
9226                         while (slot_info->active) {
9227                                 MonoMethodVar *amv = (MonoMethodVar *)slot_info->active->data;
9228
9229                                 if (amv->range.last_use.abs_pos > vmv->range.first_use.abs_pos)
9230                                         break;
9231
9232                                 //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);
9233
9234                                 slot_info->active = g_list_delete_link (slot_info->active, slot_info->active);
9235                                 slot_info->slots = g_slist_prepend_mempool (m->mempool, slot_info->slots, GINT_TO_POINTER (offsets [amv->idx]));
9236                         }
9237
9238                         /* 
9239                          * This also handles the case when the variable is used in an
9240                          * exception region, as liveness info is not computed there.
9241                          */
9242                         /* 
9243                          * FIXME: All valuetypes are marked as INDIRECT because of LDADDR
9244                          * opcodes.
9245                          */
9246                         if (! (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
9247                                 if (slot_info->slots) {
9248                                         slot = GPOINTER_TO_INT (slot_info->slots->data);
9249
9250                                         slot_info->slots = slot_info->slots->next;
9251                                 }
9252
9253                                 slot_info->active = mono_varlist_insert_sorted (m, slot_info->active, vmv, TRUE);
9254                         }
9255                 }
9256
9257                 {
9258                         static int count = 0;
9259                         count ++;
9260
9261                         /*
9262                         if (count == atoi (getenv ("COUNT")))
9263                                 printf ("LAST: %s\n", mono_method_full_name (m->method, TRUE));
9264                         if (count > atoi (getenv ("COUNT")))
9265                                 slot = 0xffffff;
9266                         else {
9267                                 mono_print_tree_nl (inst);
9268                                 }
9269                         */
9270                 }
9271                 if (slot == 0xffffff) {
9272                         /*
9273                          * Allways allocate valuetypes to sizeof (gpointer) to allow more
9274                          * efficient copying (and to work around the fact that OP_MEMCPY
9275                          * and OP_MEMSET ignores alignment).
9276                          */
9277                         if (MONO_TYPE_ISSTRUCT (t))
9278                                 align = sizeof (gpointer);
9279
9280                         if (backward) {
9281                                 offset += size;
9282                                 offset += align - 1;
9283                                 offset &= ~(align - 1);
9284                                 slot = offset;
9285                         }
9286                         else {
9287                                 offset += align - 1;
9288                                 offset &= ~(align - 1);
9289                                 slot = offset;
9290                                 offset += size;
9291                         }
9292
9293                         if (*stack_align == 0)
9294                                 *stack_align = align;
9295                 }
9296
9297                 offsets [vmv->idx] = slot;
9298         }
9299         g_list_free (vars);
9300         for (i = 0; i < MONO_TYPE_PINNED; ++i) {
9301                 if (scalar_stack_slots [i].active)
9302                         g_list_free (scalar_stack_slots [i].active);
9303         }
9304         for (i = 0; i < nvtypes; ++i) {
9305                 if (vtype_stack_slots [i].active)
9306                         g_list_free (vtype_stack_slots [i].active);
9307         }
9308
9309         mono_jit_stats.locals_stack_size += offset;
9310
9311         *stack_size = offset;
9312         return offsets;
9313 }
9314
9315 gint32*
9316 mono_allocate_stack_slots (MonoCompile *m, guint32 *stack_size, guint32 *stack_align)
9317 {
9318         return mono_allocate_stack_slots_full (m, TRUE, stack_size, stack_align);
9319 }
9320
9321 void
9322 mono_register_opcode_emulation (int opcode, const char *name, const char *sigstr, gpointer func, gboolean no_throw)
9323 {
9324         MonoJitICallInfo *info;
9325         MonoMethodSignature *sig = mono_create_icall_signature (sigstr);
9326
9327         if (!emul_opcode_map)
9328                 emul_opcode_map = g_new0 (MonoJitICallInfo*, OP_LAST + 1);
9329
9330         g_assert (!sig->hasthis);
9331         g_assert (sig->param_count < 3);
9332
9333         info = mono_register_jit_icall (func, name, sig, no_throw);
9334
9335         emul_opcode_map [opcode] = info;
9336 }
9337
9338 static void
9339 register_icall (gpointer func, const char *name, const char *sigstr, gboolean save)
9340 {
9341         MonoMethodSignature *sig;
9342
9343         if (sigstr)
9344                 sig = mono_create_icall_signature (sigstr);
9345         else
9346                 sig = NULL;
9347
9348         mono_register_jit_icall (func, name, sig, save);
9349 }
9350
9351 static void
9352 decompose_foreach (MonoInst *tree, gpointer data) 
9353 {
9354         static MonoJitICallInfo *newarr_info = NULL;
9355         static MonoJitICallInfo *newarr_specific_info = NULL;
9356         MonoJitICallInfo *info;
9357         int i;
9358
9359         switch (tree->opcode) {
9360         case CEE_NEWARR: {
9361                 MonoCompile *cfg = data;
9362                 MonoInst *iargs [3];
9363
9364                 if (!newarr_info) {
9365                         newarr_info = mono_find_jit_icall_by_addr (mono_array_new);
9366                         g_assert (newarr_info);
9367                         newarr_specific_info = mono_find_jit_icall_by_addr (mono_array_new_specific);
9368                         g_assert (newarr_specific_info);
9369                 }
9370
9371                 if (cfg->opt & MONO_OPT_SHARED) {
9372                         NEW_DOMAINCONST (cfg, iargs [0]);
9373                         NEW_CLASSCONST (cfg, iargs [1], tree->inst_newa_class);
9374                         iargs [2] = tree->inst_newa_len;
9375
9376                         info = newarr_info;
9377                 }
9378                 else {
9379                         MonoVTable *vtable = mono_class_vtable (cfg->domain, mono_array_class_get (tree->inst_newa_class, 1));
9380
9381                         NEW_VTABLECONST (cfg, iargs [0], vtable);
9382                         iargs [1] = tree->inst_newa_len;
9383
9384                         info = newarr_specific_info;
9385                 }
9386
9387                 mono_emulate_opcode (cfg, tree, iargs, info);
9388
9389                 /* Need to decompose arguments after the the opcode is decomposed */
9390                 for (i = 0; i < info->sig->param_count; ++i)
9391                         dec_foreach (iargs [i], cfg);
9392                 break;
9393         }
9394 #ifdef MONO_ARCH_SOFT_FLOAT
9395         case OP_FBEQ:
9396         case OP_FBGE:
9397         case OP_FBGT:
9398         case OP_FBLE:
9399         case OP_FBLT:
9400         case OP_FBNE_UN:
9401         case OP_FBGE_UN:
9402         case OP_FBGT_UN:
9403         case OP_FBLE_UN:
9404         case OP_FBLT_UN: {
9405                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
9406                         MonoCompile *cfg = data;
9407                         MonoInst *iargs [2];
9408                 
9409                         iargs [0] = tree->inst_i0;
9410                         iargs [1] = tree->inst_i1;
9411                 
9412                         mono_emulate_opcode (cfg, tree, iargs, info);
9413
9414                         dec_foreach (iargs [0], cfg);
9415                         dec_foreach (iargs [1], cfg);
9416                         break;
9417                 } else {
9418                         g_assert_not_reached ();
9419                 }
9420                 break;
9421         }
9422         case OP_FCEQ:
9423         case OP_FCGT:
9424         case OP_FCGT_UN:
9425         case OP_FCLT:
9426         case OP_FCLT_UN: {
9427                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
9428                         MonoCompile *cfg = data;
9429                         MonoInst *iargs [2];
9430
9431                         /* the args are in the compare opcode ... */
9432                         iargs [0] = tree->inst_i0;
9433                         iargs [1] = tree->inst_i1;
9434                 
9435                         mono_emulate_opcode (cfg, tree, iargs, info);
9436
9437                         dec_foreach (iargs [0], cfg);
9438                         dec_foreach (iargs [1], cfg);
9439                         break;
9440                 } else {
9441                         g_assert_not_reached ();
9442                 }
9443                 break;
9444         }
9445 #endif
9446
9447         default:
9448                 break;
9449         }
9450 }
9451
9452 void
9453 mono_inst_foreach (MonoInst *tree, MonoInstFunc func, gpointer data) {
9454
9455         switch (mono_burg_arity [tree->opcode]) {
9456         case 0: break;
9457         case 1: 
9458                 mono_inst_foreach (tree->inst_left, func, data);
9459                 break;
9460         case 2: 
9461                 mono_inst_foreach (tree->inst_left, func, data);
9462                 mono_inst_foreach (tree->inst_right, func, data);
9463                 break;
9464         default:
9465                 g_assert_not_reached ();
9466         }
9467         func (tree, data);
9468 }
9469
9470 G_GNUC_UNUSED
9471 static void
9472 mono_print_bb_code (MonoBasicBlock *bb)
9473 {
9474         MonoInst *c;
9475
9476         MONO_BB_FOR_EACH_INS (bb, c) {
9477                 mono_print_tree (c);
9478                 g_print ("\n");
9479         }
9480 }
9481
9482 static void
9483 print_dfn (MonoCompile *cfg) {
9484         int i, j;
9485         char *code;
9486         MonoBasicBlock *bb;
9487
9488         g_print ("IR code for method %s\n", mono_method_full_name (cfg->method, TRUE));
9489
9490         for (i = 0; i < cfg->num_bblocks; ++i) {
9491                 MonoInst *c;
9492
9493                 bb = cfg->bblocks [i];
9494                 /*if (bb->cil_code) {
9495                         char* code1, *code2;
9496                         code1 = mono_disasm_code_one (NULL, cfg->method, bb->cil_code, NULL);
9497                         if (bb->last_ins->cil_code)
9498                                 code2 = mono_disasm_code_one (NULL, cfg->method, bb->last_ins->cil_code, NULL);
9499                         else
9500                                 code2 = g_strdup ("");
9501
9502                         code1 [strlen (code1) - 1] = 0;
9503                         code = g_strdup_printf ("%s -> %s", code1, code2);
9504                         g_free (code1);
9505                         g_free (code2);
9506                 } else*/
9507                         code = g_strdup ("\n");
9508                 g_print ("\nBB%d DFN%d (len: %d): %s", bb->block_num, i, bb->cil_length, code);
9509                 MONO_BB_FOR_EACH_INS (bb, c) {
9510                         mono_print_tree (c);
9511                         g_print ("\n");
9512                 }
9513
9514                 g_print ("\tprev:");
9515                 for (j = 0; j < bb->in_count; ++j) {
9516                         g_print (" BB%d", bb->in_bb [j]->block_num);
9517                 }
9518                 g_print ("\t\tsucc:");
9519                 for (j = 0; j < bb->out_count; ++j) {
9520                         g_print (" BB%d", bb->out_bb [j]->block_num);
9521                 }
9522                 g_print ("\n\tidom: BB%d\n", bb->idom? bb->idom->block_num: -1);
9523
9524                 if (bb->idom)
9525                         g_assert (mono_bitset_test_fast (bb->dominators, bb->idom->dfn));
9526
9527                 if (bb->dominators)
9528                         mono_blockset_print (cfg, bb->dominators, "\tdominators", bb->idom? bb->idom->dfn: -1);
9529                 if (bb->dfrontier)
9530                         mono_blockset_print (cfg, bb->dfrontier, "\tdfrontier", -1);
9531                 g_free (code);
9532         }
9533
9534         g_print ("\n");
9535 }
9536
9537 void
9538 mono_bblock_add_inst (MonoBasicBlock *bb, MonoInst *inst)
9539 {
9540         MONO_INST_LIST_ADD_TAIL (&inst->node, &bb->ins_list);
9541 }
9542
9543 void
9544 mono_destroy_compile (MonoCompile *cfg)
9545 {
9546         //mono_mempool_stats (cfg->mempool);
9547         mono_free_loop_info (cfg);
9548         if (cfg->rs)
9549                 mono_regstate_free (cfg->rs);
9550         if (cfg->spvars)
9551                 g_hash_table_destroy (cfg->spvars);
9552         if (cfg->exvars)
9553                 g_hash_table_destroy (cfg->exvars);
9554         mono_mempool_destroy (cfg->mempool);
9555         g_list_free (cfg->ldstr_list);
9556         g_hash_table_destroy (cfg->token_info_hash);
9557
9558         g_free (cfg->varinfo);
9559         g_free (cfg->vars);
9560         g_free (cfg->exception_message);
9561         g_free (cfg);
9562 }
9563
9564 #ifdef HAVE_KW_THREAD
9565 static __thread gpointer mono_lmf_addr MONO_TLS_FAST;
9566 #ifdef MONO_ARCH_ENABLE_MONO_LMF_VAR
9567 /* 
9568  * When this is defined, the current lmf is stored in this tls variable instead of in 
9569  * jit_tls->lmf.
9570  */
9571 static __thread gpointer mono_lmf MONO_TLS_FAST;
9572 #endif
9573 #endif
9574
9575 guint32
9576 mono_get_jit_tls_key (void)
9577 {
9578         return mono_jit_tls_id;
9579 }
9580
9581 gint32
9582 mono_get_lmf_tls_offset (void)
9583 {
9584 #if defined(HAVE_KW_THREAD) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
9585         int offset;
9586         MONO_THREAD_VAR_OFFSET(mono_lmf,offset);
9587         return offset;
9588 #else
9589         return -1;
9590 #endif
9591 }
9592
9593 gint32
9594 mono_get_lmf_addr_tls_offset (void)
9595 {
9596         int offset;
9597         MONO_THREAD_VAR_OFFSET(mono_lmf_addr,offset);
9598         return offset;
9599 }
9600
9601 MonoLMF *
9602 mono_get_lmf (void)
9603 {
9604 #if defined(HAVE_KW_THREAD) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
9605         return mono_lmf;
9606 #else
9607         MonoJitTlsData *jit_tls;
9608
9609         if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
9610                 return jit_tls->lmf;
9611
9612         g_assert_not_reached ();
9613         return NULL;
9614 #endif
9615 }
9616
9617 MonoLMF **
9618 mono_get_lmf_addr (void)
9619 {
9620 #ifdef HAVE_KW_THREAD
9621         return mono_lmf_addr;
9622 #else
9623         MonoJitTlsData *jit_tls;
9624
9625         if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
9626                 return &jit_tls->lmf;
9627
9628         g_assert_not_reached ();
9629         return NULL;
9630 #endif
9631 }
9632
9633 /* Called by native->managed wrappers */
9634 void
9635 mono_jit_thread_attach (MonoDomain *domain)
9636 {
9637 #ifdef HAVE_KW_THREAD
9638         if (!mono_lmf_addr) {
9639                 mono_thread_attach (domain);
9640         }
9641 #else
9642         if (!TlsGetValue (mono_jit_tls_id))
9643                 mono_thread_attach (domain);
9644 #endif
9645         if (mono_domain_get () != domain)
9646                 mono_domain_set (domain, TRUE);
9647 }       
9648
9649 /**
9650  * mono_thread_abort:
9651  * @obj: exception object
9652  *
9653  * abort the thread, print exception information and stack trace
9654  */
9655 static void
9656 mono_thread_abort (MonoObject *obj)
9657 {
9658         /* MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id); */
9659         
9660         /* handle_remove should be eventually called for this thread, too
9661         g_free (jit_tls);*/
9662
9663         if ((mono_runtime_unhandled_exception_policy_get () == MONO_UNHANLED_POLICY_LEGACY) ||
9664                         (obj->vtable->klass == mono_defaults.threadabortexception_class)) {
9665                 mono_thread_exit ();
9666         } else {
9667                 exit (mono_environment_exitcode_get ());
9668         }
9669 }
9670
9671 static void*
9672 setup_jit_tls_data (gpointer stack_start, gpointer abort_func)
9673 {
9674         MonoJitTlsData *jit_tls;
9675         MonoLMF *lmf;
9676
9677         jit_tls = TlsGetValue (mono_jit_tls_id);
9678         if (jit_tls)
9679                 return jit_tls;
9680
9681         jit_tls = g_new0 (MonoJitTlsData, 1);
9682
9683         TlsSetValue (mono_jit_tls_id, jit_tls);
9684
9685         jit_tls->abort_func = abort_func;
9686         jit_tls->end_of_stack = stack_start;
9687
9688         lmf = g_new0 (MonoLMF, 1);
9689 #ifdef MONO_ARCH_INIT_TOP_LMF_ENTRY
9690         MONO_ARCH_INIT_TOP_LMF_ENTRY (lmf);
9691 #else
9692         lmf->ebp = -1;
9693 #endif
9694
9695         jit_tls->first_lmf = lmf;
9696
9697 #if defined(HAVE_KW_THREAD) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
9698         /* jit_tls->lmf is unused */
9699         mono_lmf = lmf;
9700         mono_lmf_addr = &mono_lmf;
9701 #else
9702 #if defined(HAVE_KW_THREAD)
9703         mono_lmf_addr = &jit_tls->lmf;  
9704 #endif
9705
9706         jit_tls->lmf = lmf;
9707 #endif
9708
9709         mono_arch_setup_jit_tls_data (jit_tls);
9710         mono_setup_altstack (jit_tls);
9711
9712         return jit_tls;
9713 }
9714
9715 static void
9716 mono_thread_start_cb (gsize tid, gpointer stack_start, gpointer func)
9717 {
9718         MonoThread *thread;
9719         void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort);
9720         thread = mono_thread_current ();
9721         mono_debugger_thread_created (tid, thread, jit_tls);
9722         if (thread)
9723                 thread->jit_data = jit_tls;
9724 }
9725
9726 void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
9727
9728 static void
9729 mono_thread_abort_dummy (MonoObject *obj)
9730 {
9731   if (mono_thread_attach_aborted_cb)
9732     mono_thread_attach_aborted_cb (obj);
9733   else
9734     mono_thread_abort (obj);
9735 }
9736
9737 static void
9738 mono_thread_attach_cb (gsize tid, gpointer stack_start)
9739 {
9740         MonoThread *thread;
9741         void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort_dummy);
9742         thread = mono_thread_current ();
9743         mono_debugger_thread_created (tid, thread, (MonoJitTlsData *) jit_tls);
9744         if (thread)
9745                 thread->jit_data = jit_tls;
9746         if (mono_profiler_get_events () & MONO_PROFILE_STATISTICAL)
9747                 setup_stat_profiler ();
9748 }
9749
9750 static void
9751 mini_thread_cleanup (MonoThread *thread)
9752 {
9753         MonoJitTlsData *jit_tls = thread->jit_data;
9754
9755         if (jit_tls) {
9756                 mono_debugger_thread_cleanup (jit_tls);
9757                 mono_arch_free_jit_tls_data (jit_tls);
9758
9759                 mono_free_altstack (jit_tls);
9760                 g_free (jit_tls->first_lmf);
9761                 g_free (jit_tls);
9762                 thread->jit_data = NULL;
9763                 TlsSetValue (mono_jit_tls_id, NULL);
9764         }
9765 }
9766
9767 void
9768 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
9769 {
9770         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
9771
9772         ji->ip.i = ip;
9773         ji->type = type;
9774         ji->data.target = target;
9775         ji->next = cfg->patch_info;
9776
9777         cfg->patch_info = ji;
9778 }
9779
9780 void
9781 mono_remove_patch_info (MonoCompile *cfg, int ip)
9782 {
9783         MonoJumpInfo **ji = &cfg->patch_info;
9784
9785         while (*ji) {
9786                 if ((*ji)->ip.i == ip)
9787                         *ji = (*ji)->next;
9788                 else
9789                         ji = &((*ji)->next);
9790         }
9791 }
9792
9793 /**
9794  * mono_patch_info_dup_mp:
9795  *
9796  * Make a copy of PATCH_INFO, allocating memory from the mempool MP.
9797  */
9798 MonoJumpInfo*
9799 mono_patch_info_dup_mp (MonoMemPool *mp, MonoJumpInfo *patch_info)
9800 {
9801         MonoJumpInfo *res = mono_mempool_alloc (mp, sizeof (MonoJumpInfo));
9802         memcpy (res, patch_info, sizeof (MonoJumpInfo));
9803
9804         switch (patch_info->type) {
9805         case MONO_PATCH_INFO_RVA:
9806         case MONO_PATCH_INFO_LDSTR:
9807         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
9808         case MONO_PATCH_INFO_LDTOKEN:
9809         case MONO_PATCH_INFO_DECLSEC:
9810                 res->data.token = mono_mempool_alloc (mp, sizeof (MonoJumpInfoToken));
9811                 memcpy (res->data.token, patch_info->data.token, sizeof (MonoJumpInfoToken));
9812                 break;
9813         case MONO_PATCH_INFO_SWITCH:
9814                 res->data.table = mono_mempool_alloc (mp, sizeof (MonoJumpInfoBBTable));
9815                 memcpy (res->data.table, patch_info->data.table, sizeof (MonoJumpInfoBBTable));
9816                 break;
9817         default:
9818                 break;
9819         }
9820
9821         return res;
9822 }
9823
9824 guint
9825 mono_patch_info_hash (gconstpointer data)
9826 {
9827         const MonoJumpInfo *ji = (MonoJumpInfo*)data;
9828
9829         switch (ji->type) {
9830         case MONO_PATCH_INFO_RVA:
9831         case MONO_PATCH_INFO_LDSTR:
9832         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
9833         case MONO_PATCH_INFO_LDTOKEN:
9834         case MONO_PATCH_INFO_DECLSEC:
9835                 return (ji->type << 8) | ji->data.token->token;
9836         case MONO_PATCH_INFO_VTABLE:
9837         case MONO_PATCH_INFO_CLASS:
9838         case MONO_PATCH_INFO_IID:
9839         case MONO_PATCH_INFO_ADJUSTED_IID:
9840                 return (ji->type << 8) | (gssize)ji->data.klass;
9841         case MONO_PATCH_INFO_FIELD:
9842         case MONO_PATCH_INFO_SFLDA:
9843                 return (ji->type << 8) | (gssize)ji->data.field;
9844         case MONO_PATCH_INFO_METHODCONST:
9845         case MONO_PATCH_INFO_METHOD:
9846         case MONO_PATCH_INFO_METHOD_JUMP:
9847                 return (ji->type << 8) | (gssize)ji->data.method;
9848         case MONO_PATCH_INFO_IMAGE:
9849                 return (ji->type << 8) | (gssize)ji->data.image;                
9850         default:
9851                 return (ji->type << 8);
9852         }
9853 }
9854
9855 /* 
9856  * mono_patch_info_equal:
9857  * 
9858  * This might fail to recognize equivalent patches, i.e. floats, so its only
9859  * usable in those cases where this is not a problem, i.e. sharing GOT slots
9860  * in AOT.
9861  */
9862 gint
9863 mono_patch_info_equal (gconstpointer ka, gconstpointer kb)
9864 {
9865         const MonoJumpInfo *ji1 = (MonoJumpInfo*)ka;
9866         const MonoJumpInfo *ji2 = (MonoJumpInfo*)kb;
9867
9868         if (ji1->type != ji2->type)
9869                 return 0;
9870
9871         switch (ji1->type) {
9872         case MONO_PATCH_INFO_RVA:
9873         case MONO_PATCH_INFO_LDSTR:
9874         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
9875         case MONO_PATCH_INFO_LDTOKEN:
9876         case MONO_PATCH_INFO_DECLSEC:
9877                 if ((ji1->data.token->image != ji2->data.token->image) ||
9878                         (ji1->data.token->token != ji2->data.token->token))
9879                         return 0;
9880                 break;
9881         default:
9882                 if (ji1->data.name != ji2->data.name)
9883                         return 0;
9884                 break;
9885         }
9886
9887         return 1;
9888 }
9889
9890 gpointer
9891 mono_resolve_patch_target (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors)
9892 {
9893         unsigned char *ip = patch_info->ip.i + code;
9894         gconstpointer target = NULL;
9895
9896         switch (patch_info->type) {
9897         case MONO_PATCH_INFO_BB:
9898                 target = patch_info->data.bb->native_offset + code;
9899                 break;
9900         case MONO_PATCH_INFO_ABS:
9901                 target = patch_info->data.target;
9902                 break;
9903         case MONO_PATCH_INFO_LABEL:
9904                 target = patch_info->data.inst->inst_c0 + code;
9905                 break;
9906         case MONO_PATCH_INFO_IP:
9907                 target = ip;
9908                 break;
9909         case MONO_PATCH_INFO_METHOD_REL:
9910                 target = code + patch_info->data.offset;
9911                 break;
9912         case MONO_PATCH_INFO_INTERNAL_METHOD: {
9913                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
9914                 if (!mi) {
9915                         g_warning ("unknown MONO_PATCH_INFO_INTERNAL_METHOD %s", patch_info->data.name);
9916                         g_assert_not_reached ();
9917                 }
9918                 target = mono_icall_get_wrapper (mi);
9919                 break;
9920         }
9921         case MONO_PATCH_INFO_METHOD_JUMP: {
9922                 GSList *list;
9923
9924                 /* get the trampoline to the method from the domain */
9925                 target = mono_create_jump_trampoline (domain, patch_info->data.method, TRUE);
9926                 if (!domain->jump_target_hash)
9927                         domain->jump_target_hash = g_hash_table_new (NULL, NULL);
9928                 list = g_hash_table_lookup (domain->jump_target_hash, patch_info->data.method);
9929                 list = g_slist_prepend (list, ip);
9930                 g_hash_table_insert (domain->jump_target_hash, patch_info->data.method, list);
9931                 break;
9932         }
9933         case MONO_PATCH_INFO_METHOD:
9934                 if (patch_info->data.method == method) {
9935                         target = code;
9936                 } else
9937                         /* get the trampoline to the method from the domain */
9938                         target = mono_create_jit_trampoline (patch_info->data.method);
9939                 break;
9940         case MONO_PATCH_INFO_SWITCH: {
9941                 gpointer *jump_table;
9942                 int i;
9943
9944                 if (method && method->dynamic) {
9945                         jump_table = mono_code_manager_reserve (mono_dynamic_code_hash_lookup (domain, method)->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
9946                 } else {
9947                         mono_domain_lock (domain);
9948                         jump_table = mono_code_manager_reserve (domain->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
9949                         mono_domain_unlock (domain);
9950                 }
9951
9952                 for (i = 0; i < patch_info->data.table->table_size; i++) {
9953                         jump_table [i] = code + GPOINTER_TO_INT (patch_info->data.table->table [i]);
9954                 }
9955                 target = jump_table;
9956                 break;
9957         }
9958         case MONO_PATCH_INFO_METHODCONST:
9959         case MONO_PATCH_INFO_CLASS:
9960         case MONO_PATCH_INFO_IMAGE:
9961         case MONO_PATCH_INFO_FIELD:
9962                 target = patch_info->data.target;
9963                 break;
9964         case MONO_PATCH_INFO_IID:
9965                 mono_class_init (patch_info->data.klass);
9966                 target = GINT_TO_POINTER ((int)patch_info->data.klass->interface_id);
9967                 break;
9968         case MONO_PATCH_INFO_ADJUSTED_IID:
9969                 mono_class_init (patch_info->data.klass);
9970                 target = GINT_TO_POINTER ((int)(-((patch_info->data.klass->interface_id + 1) * SIZEOF_VOID_P)));
9971                 break;
9972         case MONO_PATCH_INFO_VTABLE:
9973                 target = mono_class_vtable (domain, patch_info->data.klass);
9974                 break;
9975         case MONO_PATCH_INFO_CLASS_INIT:
9976                 target = mono_create_class_init_trampoline (mono_class_vtable (domain, patch_info->data.klass));
9977                 break;
9978         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
9979                 target = mono_create_delegate_trampoline (patch_info->data.klass);
9980                 break;
9981         case MONO_PATCH_INFO_SFLDA: {
9982                 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.field->parent);
9983                 if (!vtable->initialized && !(vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) && (method && mono_class_needs_cctor_run (vtable->klass, method)))
9984                         /* Done by the generated code */
9985                         ;
9986                 else {
9987                         if (run_cctors)
9988                                 mono_runtime_class_init (vtable);
9989                 }
9990                 target = (char*)vtable->data + patch_info->data.field->offset;
9991                 break;
9992         }
9993         case MONO_PATCH_INFO_RVA:
9994                 target = mono_image_rva_map (patch_info->data.token->image, patch_info->data.token->token);
9995                 break;
9996         case MONO_PATCH_INFO_R4:
9997         case MONO_PATCH_INFO_R8:
9998                 target = patch_info->data.target;
9999                 break;
10000         case MONO_PATCH_INFO_EXC_NAME:
10001                 target = patch_info->data.name;
10002                 break;
10003         case MONO_PATCH_INFO_LDSTR:
10004                 target =
10005                         mono_ldstr (domain, patch_info->data.token->image, 
10006                                                 mono_metadata_token_index (patch_info->data.token->token));
10007                 break;
10008         case MONO_PATCH_INFO_TYPE_FROM_HANDLE: {
10009                 gpointer handle;
10010                 MonoClass *handle_class;
10011
10012                 handle = mono_ldtoken (patch_info->data.token->image, 
10013                                        patch_info->data.token->token, &handle_class, NULL);
10014                 mono_class_init (handle_class);
10015                 mono_class_init (mono_class_from_mono_type (handle));
10016
10017                 target =
10018                         mono_type_get_object (domain, handle);
10019                 break;
10020         }
10021         case MONO_PATCH_INFO_LDTOKEN: {
10022                 gpointer handle;
10023                 MonoClass *handle_class;
10024                 
10025                 handle = mono_ldtoken (patch_info->data.token->image,
10026                                        patch_info->data.token->token, &handle_class, NULL);
10027                 mono_class_init (handle_class);
10028                 
10029                 target = handle;
10030                 break;
10031         }
10032         case MONO_PATCH_INFO_DECLSEC:
10033                 target = (mono_metadata_blob_heap (patch_info->data.token->image, patch_info->data.token->token) + 2);
10034                 break;
10035         case MONO_PATCH_INFO_BB_OVF:
10036         case MONO_PATCH_INFO_EXC_OVF:
10037         case MONO_PATCH_INFO_GOT_OFFSET:
10038         case MONO_PATCH_INFO_NONE:
10039                 break;
10040         default:
10041                 g_assert_not_reached ();
10042         }
10043
10044         return (gpointer)target;
10045 }
10046
10047 static void
10048 dec_foreach (MonoInst *tree, MonoCompile *cfg) {
10049         MonoJitICallInfo *info;
10050
10051         decompose_foreach (tree, cfg);
10052
10053         switch (mono_burg_arity [tree->opcode]) {
10054         case 0: break;
10055         case 1: 
10056                 dec_foreach (tree->inst_left, cfg);
10057
10058                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
10059                         MonoInst *iargs [2];
10060                 
10061                         iargs [0] = tree->inst_left;
10062
10063                         mono_emulate_opcode (cfg, tree, iargs, info);
10064                         return;
10065                 }
10066
10067                 break;
10068         case 2:
10069 #ifdef MONO_ARCH_BIGMUL_INTRINS
10070                 if (tree->opcode == OP_LMUL
10071                                 && (cfg->opt & MONO_OPT_INTRINS)
10072                                 && (tree->inst_left->opcode == CEE_CONV_I8 
10073                                         || tree->inst_left->opcode == CEE_CONV_U8)
10074                                 && tree->inst_left->inst_left->type == STACK_I4
10075                                 && (tree->inst_right->opcode == CEE_CONV_I8 
10076                                         || tree->inst_right->opcode == CEE_CONV_U8)
10077                                 && tree->inst_right->inst_left->type == STACK_I4
10078                                 && tree->inst_left->opcode == tree->inst_right->opcode) {
10079                         tree->opcode = (tree->inst_left->opcode == CEE_CONV_I8 ? OP_BIGMUL: OP_BIGMUL_UN);
10080                         tree->inst_left = tree->inst_left->inst_left;
10081                         tree->inst_right = tree->inst_right->inst_left;
10082                         dec_foreach (tree, cfg);
10083                 } else 
10084 #endif
10085                         if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
10086                         MonoInst *iargs [2];
10087                 
10088                         iargs [0] = tree->inst_i0;
10089                         iargs [1] = tree->inst_i1;
10090                 
10091                         mono_emulate_opcode (cfg, tree, iargs, info);
10092
10093                         dec_foreach (iargs [0], cfg);
10094                         dec_foreach (iargs [1], cfg);
10095                         return;
10096                 } else {
10097                         dec_foreach (tree->inst_left, cfg);
10098                         dec_foreach (tree->inst_right, cfg);
10099                 }
10100                 break;
10101         default:
10102                 g_assert_not_reached ();
10103         }
10104 }
10105
10106 static void
10107 decompose_pass (MonoCompile *cfg) {
10108         MonoBasicBlock *bb;
10109
10110         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
10111                 MonoInst *tree;
10112                 cfg->cbb = bb;
10113                 cfg->prev_ins = NULL;
10114                 MONO_BB_FOR_EACH_INS (cfg->cbb, tree) {
10115                         dec_foreach (tree, cfg);
10116                         cfg->prev_ins = tree;
10117                 }
10118         }
10119 }
10120
10121 static void
10122 nullify_basic_block (MonoBasicBlock *bb) 
10123 {
10124         bb->in_count = 0;
10125         bb->out_count = 0;
10126         bb->in_bb = NULL;
10127         bb->out_bb = NULL;
10128         bb->next_bb = NULL;
10129         MONO_INST_LIST_INIT (&bb->ins_list);
10130         bb->cil_code = NULL;
10131 }
10132
10133 static void 
10134 replace_out_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
10135 {
10136         int i;
10137
10138         for (i = 0; i < bb->out_count; i++) {
10139                 MonoBasicBlock *ob = bb->out_bb [i];
10140                 if (ob == orig) {
10141                         if (!repl) {
10142                                 if (bb->out_count > 1) {
10143                                         bb->out_bb [i] = bb->out_bb [bb->out_count - 1];
10144                                 }
10145                                 bb->out_count--;
10146                         } else {
10147                                 bb->out_bb [i] = repl;
10148                         }
10149                 }
10150         }
10151 }
10152
10153 static void 
10154 replace_in_block (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl)
10155 {
10156         int i;
10157
10158         for (i = 0; i < bb->in_count; i++) {
10159                 MonoBasicBlock *ib = bb->in_bb [i];
10160                 if (ib == orig) {
10161                         if (!repl) {
10162                                 if (bb->in_count > 1) {
10163                                         bb->in_bb [i] = bb->in_bb [bb->in_count - 1];
10164                                 }
10165                                 bb->in_count--;
10166                         } else {
10167                                 bb->in_bb [i] = repl;
10168                         }
10169                 }
10170         }
10171 }
10172
10173 static void
10174 replace_out_block_in_code (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl) {
10175         MonoInst *inst;
10176         
10177         MONO_BB_FOR_EACH_INS (bb, inst) {
10178                 if (inst->opcode == OP_CALL_HANDLER) {
10179                         if (inst->inst_target_bb == orig)
10180                                 inst->inst_target_bb = repl;
10181                 }
10182         }
10183
10184         inst = mono_inst_list_last (&bb->ins_list);
10185         if (!inst)
10186                 return;
10187
10188         switch (inst->opcode) {
10189         case OP_BR:
10190                 if (inst->inst_target_bb == orig)
10191                         inst->inst_target_bb = repl;
10192                 break;
10193         case OP_SWITCH: {
10194                 int i;
10195                 int n = GPOINTER_TO_INT (inst->klass);
10196                 for (i = 0; i < n; i++ ) {
10197                         if (inst->inst_many_bb [i] == orig)
10198                                 inst->inst_many_bb [i] = repl;
10199                 }
10200                 break;
10201         }
10202         case CEE_BNE_UN:
10203         case CEE_BEQ:
10204         case CEE_BLT:
10205         case CEE_BLT_UN:
10206         case CEE_BGT:
10207         case CEE_BGT_UN:
10208         case CEE_BGE:
10209         case CEE_BGE_UN:
10210         case CEE_BLE:
10211         case CEE_BLE_UN:
10212                 if (inst->inst_true_bb == orig)
10213                         inst->inst_true_bb = repl;
10214                 if (inst->inst_false_bb == orig)
10215                         inst->inst_false_bb = repl;
10216                 break;
10217         default:
10218                 break;
10219         }
10220 }
10221
10222 static void 
10223 replace_basic_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
10224 {
10225         int i, j;
10226
10227         for (i = 0; i < bb->out_count; i++) {
10228                 MonoBasicBlock *ob = bb->out_bb [i];
10229                 for (j = 0; j < ob->in_count; j++) {
10230                         if (ob->in_bb [j] == orig) {
10231                                 ob->in_bb [j] = repl;
10232                         }
10233                 }
10234         }
10235
10236 }
10237
10238 /**
10239   * Check if a bb is useless (is just made of NOPs and ends with an
10240   * unconditional branch, or nothing).
10241   * If it is so, unlink it from the CFG and nullify it, and return TRUE.
10242   * Otherwise, return FALSE;
10243   */
10244 static gboolean
10245 remove_block_if_useless (MonoCompile *cfg, MonoBasicBlock *bb, MonoBasicBlock *previous_bb) {
10246         MonoBasicBlock *target_bb = NULL;
10247         MonoInst *inst;
10248         
10249         /* Do not touch handlers */
10250         if (bb->region != -1) {
10251                 bb->not_useless = TRUE;
10252                 return FALSE;
10253         }
10254         
10255         MONO_BB_FOR_EACH_INS (bb, inst) {
10256                 switch (inst->opcode) {
10257                 case OP_NOP:
10258                         break;
10259                 case OP_BR:
10260                         target_bb = inst->inst_target_bb;
10261                         break;
10262                 default:
10263                         bb->not_useless = TRUE;
10264                         return FALSE;
10265                 }
10266         }
10267         
10268         if (target_bb == NULL) {
10269                 if ((bb->out_count == 1) && (bb->out_bb [0] == bb->next_bb)) {
10270                         target_bb = bb->next_bb;
10271                 } else {
10272                         /* Do not touch empty BBs that do not "fall through" to their next BB (like the exit BB) */
10273                         return FALSE;
10274                 }
10275         }
10276         
10277         /* Do not touch BBs following a switch (they are the "default" branch) */
10278         inst = mono_inst_list_last (&previous_bb->ins_list);
10279         if (inst && inst->opcode == OP_SWITCH)
10280                 return FALSE;
10281         
10282         /* Do not touch BBs following the entry BB and jumping to something that is not */
10283         /* thiry "next" bb (the entry BB cannot contain the branch) */
10284         if ((previous_bb == cfg->bb_entry) && (bb->next_bb != target_bb)) {
10285                 return FALSE;
10286         }
10287
10288         /* 
10289          * Do not touch BBs following a try block as the code in 
10290          * mini_method_compile needs them to compute the length of the try block.
10291          */
10292         if (MONO_BBLOCK_IS_IN_REGION (previous_bb, MONO_REGION_TRY))
10293                 return FALSE;
10294         
10295         /* Check that there is a target BB, and that bb is not an empty loop (Bug 75061) */
10296         if ((target_bb != NULL) && (target_bb != bb)) {
10297                 MonoInst *last_ins;
10298                 int i;
10299
10300                 if (cfg->verbose_level > 1) {
10301                         printf ("remove_block_if_useless %s, removed BB%d\n", mono_method_full_name (cfg->method, TRUE), bb->block_num);
10302                 }
10303                 
10304                 /* unlink_bblock () modifies the bb->in_bb array so can't use a for loop here */
10305                 while (bb->in_count) {
10306                         MonoBasicBlock *in_bb = bb->in_bb [0];
10307                         mono_unlink_bblock (cfg, in_bb, bb);
10308                         link_bblock (cfg, in_bb, target_bb);
10309                         replace_out_block_in_code (in_bb, bb, target_bb);
10310                 }
10311                 
10312                 mono_unlink_bblock (cfg, bb, target_bb);
10313                 
10314                 last_ins = mono_inst_list_last (&previous_bb->ins_list);
10315
10316                 if ((previous_bb != cfg->bb_entry) &&
10317                                 (previous_bb->region == bb->region) &&
10318                                 ((last_ins == NULL) ||
10319                                 ((last_ins->opcode != OP_BR) &&
10320                                 (!(MONO_IS_COND_BRANCH_OP (last_ins))) &&
10321                                 (last_ins->opcode != OP_SWITCH)))) {
10322                         for (i = 0; i < previous_bb->out_count; i++) {
10323                                 if (previous_bb->out_bb [i] == target_bb) {
10324                                         MonoInst *jump;
10325                                         MONO_INST_NEW (cfg, jump, OP_BR);
10326                                         MONO_ADD_INS (previous_bb, jump);
10327                                         jump->cil_code = previous_bb->cil_code;
10328                                         jump->inst_target_bb = target_bb;
10329                                         break;
10330                                 }
10331                         }
10332                 }
10333                 
10334                 previous_bb->next_bb = bb->next_bb;
10335                 nullify_basic_block (bb);
10336                 
10337                 return TRUE;
10338         } else {
10339                 return FALSE;
10340         }
10341 }
10342
10343 static void
10344 merge_basic_blocks (MonoBasicBlock *bb, MonoBasicBlock *bbn) 
10345 {
10346         MonoInst *last_ins;
10347
10348         bb->out_count = bbn->out_count;
10349         bb->out_bb = bbn->out_bb;
10350
10351         replace_basic_block (bb, bbn, bb);
10352
10353         last_ins = mono_inst_list_last (&bb->ins_list);
10354
10355         /* Nullify branch at the end of bb */
10356         if (last_ins && MONO_IS_BRANCH_OP (last_ins))
10357                 last_ins->opcode = OP_NOP;
10358
10359         MONO_INST_LIST_SPLICE_TAIL_INIT (&bbn->ins_list, &bb->ins_list);
10360
10361         bb->next_bb = bbn->next_bb;
10362         nullify_basic_block (bbn);
10363 }
10364
10365 static void
10366 move_basic_block_to_end (MonoCompile *cfg, MonoBasicBlock *bb)
10367 {
10368         MonoBasicBlock *bbn, *next;
10369         MonoInst *last_ins;
10370
10371         next = bb->next_bb;
10372
10373         /* Find the previous */
10374         for (bbn = cfg->bb_entry; bbn->next_bb && bbn->next_bb != bb; bbn = bbn->next_bb)
10375                 ;
10376         if (bbn->next_bb) {
10377                 bbn->next_bb = bb->next_bb;
10378         }
10379
10380         /* Find the last */
10381         for (bbn = cfg->bb_entry; bbn->next_bb; bbn = bbn->next_bb)
10382                 ;
10383         bbn->next_bb = bb;
10384         bb->next_bb = NULL;
10385
10386         last_ins = mono_inst_list_last (&bb->ins_list);
10387
10388         /* Add a branch */
10389         if (next && (!last_ins || (last_ins->opcode != OP_NOT_REACHED))) {
10390                 MonoInst *ins;
10391
10392                 MONO_INST_NEW (cfg, ins, OP_BR);
10393                 MONO_ADD_INS (bb, ins);
10394                 link_bblock (cfg, bb, next);
10395                 ins->inst_target_bb = next;
10396         }               
10397 }
10398
10399 /* checks that a and b represent the same instructions, conservatively,
10400  * it can return FALSE also for two trees that are equal.
10401  * FIXME: also make sure there are no side effects.
10402  */
10403 static int
10404 same_trees (MonoInst *a, MonoInst *b)
10405 {
10406         int arity;
10407         if (a->opcode != b->opcode)
10408                 return FALSE;
10409         arity = mono_burg_arity [a->opcode];
10410         if (arity == 1) {
10411                 if (a->ssa_op == b->ssa_op && a->ssa_op == MONO_SSA_LOAD && a->inst_i0 == b->inst_i0)
10412                         return TRUE;
10413                 return same_trees (a->inst_left, b->inst_left);
10414         } else if (arity == 2) {
10415                 return same_trees (a->inst_left, b->inst_left) && same_trees (a->inst_right, b->inst_right);
10416         } else if (arity == 0) {
10417                 switch (a->opcode) {
10418                 case OP_ICONST:
10419                         return a->inst_c0 == b->inst_c0;
10420                 default:
10421                         return FALSE;
10422                 }
10423         }
10424         return FALSE;
10425 }
10426
10427 static int
10428 get_unsigned_condbranch (int opcode)
10429 {
10430         switch (opcode) {
10431         case CEE_BLE: return CEE_BLE_UN;
10432         case CEE_BLT: return CEE_BLT_UN;
10433         case CEE_BGE: return CEE_BGE_UN;
10434         case CEE_BGT: return CEE_BGT_UN;
10435         }
10436         g_assert_not_reached ();
10437         return 0;
10438 }
10439
10440 static int
10441 tree_is_unsigned (MonoInst* ins) {
10442         switch (ins->opcode) {
10443         case OP_ICONST:
10444                 return (int)ins->inst_c0 >= 0;
10445         /* array lengths are positive as are string sizes */
10446         case CEE_LDLEN:
10447         case OP_STRLEN:
10448                 return TRUE;
10449         case CEE_CONV_U1:
10450         case CEE_CONV_U2:
10451         case CEE_CONV_U4:
10452         case CEE_CONV_OVF_U1:
10453         case CEE_CONV_OVF_U2:
10454         case CEE_CONV_OVF_U4:
10455                 return TRUE;
10456         case CEE_LDIND_U1:
10457         case CEE_LDIND_U2:
10458         case CEE_LDIND_U4:
10459                 return TRUE;
10460         default:
10461                 return FALSE;
10462         }
10463 }
10464
10465 /* check if an unsigned compare can be used instead of two signed compares
10466  * for (val < 0 || val > limit) conditionals.
10467  * Returns TRUE if the optimization has been applied.
10468  * Note that this can't be applied if the second arg is not positive...
10469  */
10470 static int
10471 try_unsigned_compare (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *bb_last)
10472 {
10473         MonoBasicBlock *truet, *falset;
10474         MonoInst *cmp_inst = bb_last->inst_left;
10475         MonoInst *condb;
10476         if (!cmp_inst->inst_right->inst_c0 == 0)
10477                 return FALSE;
10478         truet = bb_last->inst_true_bb;
10479         falset = bb_last->inst_false_bb;
10480         if (falset->in_count != 1)
10481                 return FALSE;
10482         condb = mono_inst_list_last (&falset->ins_list);
10483         /* target bb must have one instruction */
10484         if (!condb || (condb->node.next != &falset->ins_list))
10485                 return FALSE;
10486         if ((((condb->opcode == CEE_BLE || condb->opcode == CEE_BLT) && (condb->inst_false_bb == truet))
10487                         || ((condb->opcode == CEE_BGE || condb->opcode == CEE_BGT) && (condb->inst_true_bb == truet)))
10488                         && same_trees (cmp_inst->inst_left, condb->inst_left->inst_left)) {
10489                 if (!tree_is_unsigned (condb->inst_left->inst_right))
10490                         return FALSE;
10491                 condb->opcode = get_unsigned_condbranch (condb->opcode);
10492                 /* change the original condbranch to just point to the new unsigned check */
10493                 bb_last->opcode = OP_BR;
10494                 bb_last->inst_target_bb = falset;
10495                 replace_out_block (bb, truet, NULL);
10496                 replace_in_block (truet, bb, NULL);
10497                 return TRUE;
10498         }
10499         return FALSE;
10500 }
10501
10502 /*
10503  * Optimizes the branches on the Control Flow Graph
10504  *
10505  */
10506 static void
10507 optimize_branches (MonoCompile *cfg)
10508 {
10509         int i, changed = FALSE;
10510         MonoBasicBlock *bb, *bbn;
10511         guint32 niterations;
10512
10513         /*
10514          * Some crazy loops could cause the code below to go into an infinite
10515          * loop, see bug #53003 for an example. To prevent this, we put an upper
10516          * bound on the number of iterations.
10517          */
10518         if (cfg->num_bblocks > 1000)
10519                 niterations = cfg->num_bblocks * 2;
10520         else
10521                 niterations = 1000;
10522
10523         do {
10524                 MonoBasicBlock *previous_bb;
10525                 changed = FALSE;
10526                 niterations --;
10527
10528                 /* we skip the entry block (exit is handled specially instead ) */
10529                 for (previous_bb = cfg->bb_entry, bb = cfg->bb_entry->next_bb; bb; previous_bb = bb, bb = bb->next_bb) {
10530                         MonoInst *last_ins;
10531
10532                         /* dont touch code inside exception clauses */
10533                         if (bb->region != -1)
10534                                 continue;
10535
10536                         if (!bb->not_useless && remove_block_if_useless (cfg, bb, previous_bb)) {
10537                                 changed = TRUE;
10538                                 continue;
10539                         }
10540
10541                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
10542                                 if (cfg->verbose_level > 2)
10543                                         g_print ("nullify block triggered %d\n", bbn->block_num);
10544
10545                                 bb->next_bb = bbn->next_bb;
10546
10547                                 for (i = 0; i < bbn->out_count; i++)
10548                                         replace_in_block (bbn->out_bb [i], bbn, NULL);
10549
10550                                 nullify_basic_block (bbn);                      
10551                                 changed = TRUE;
10552                         }
10553
10554                         last_ins = mono_inst_list_last (&bb->ins_list);
10555                         if (bb->out_count == 1) {
10556                                 bbn = bb->out_bb [0];
10557
10558                                 /* conditional branches where true and false targets are the same can be also replaced with OP_BR */
10559                                 if (last_ins && MONO_IS_COND_BRANCH_OP (last_ins)) {
10560                                         MonoInst *pop;
10561                                         MONO_INST_NEW (cfg, pop, CEE_POP);
10562                                         pop->inst_left = last_ins->inst_left->inst_left;
10563                                         mono_add_ins_to_end (bb, pop);
10564                                         MONO_INST_NEW (cfg, pop, CEE_POP);
10565                                         pop->inst_left = last_ins->inst_left->inst_right;
10566                                         mono_add_ins_to_end (bb, pop);
10567                                         last_ins->opcode = OP_BR;
10568                                         last_ins->inst_target_bb = last_ins->inst_true_bb;
10569                                         changed = TRUE;
10570                                         if (cfg->verbose_level > 2)
10571                                                 g_print ("cond branch removal triggered in %d %d\n", bb->block_num, bb->out_count);
10572                                 }
10573
10574                                 if (bb->region == bbn->region && bb->next_bb == bbn) {
10575                                         /* the block are in sequence anyway ... */
10576
10577                                         /* branches to the following block can be removed */
10578                                         if (last_ins && last_ins->opcode == OP_BR) {
10579                                                 last_ins->opcode = OP_NOP;
10580                                                 changed = TRUE;
10581                                                 if (cfg->verbose_level > 2)
10582                                                         g_print ("br removal triggered %d -> %d\n", bb->block_num, bbn->block_num);
10583                                         }
10584
10585                                         if (bbn->in_count == 1) {
10586
10587                                                 if (bbn != cfg->bb_exit) {
10588                                                         if (cfg->verbose_level > 2)
10589                                                                 g_print ("block merge triggered %d -> %d\n", bb->block_num, bbn->block_num);
10590                                                         merge_basic_blocks (bb, bbn);
10591                                                         changed = TRUE;
10592                                                         continue;
10593                                                 }
10594
10595                                                 //mono_print_bb_code (bb);
10596                                         }
10597                                 }
10598                         }
10599                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
10600                                 if (cfg->verbose_level > 2) {
10601                                         g_print ("nullify block triggered %d\n", bbn->block_num);
10602                                 }
10603                                 bb->next_bb = bbn->next_bb;
10604
10605                                 for (i = 0; i < bbn->out_count; i++)
10606                                         replace_in_block (bbn->out_bb [i], bbn, NULL);
10607
10608                                 nullify_basic_block (bbn);                      
10609                                 changed = TRUE;
10610                                 continue;
10611                         }
10612
10613                         if (bb->out_count == 1) {
10614                                 bbn = bb->out_bb [0];
10615
10616                                 if (last_ins && last_ins->opcode == OP_BR) {
10617                                         MonoInst *bbn_code;
10618
10619                                         bbn = last_ins->inst_target_bb;
10620                                         bbn_code = mono_inst_list_first (&bbn->ins_list);
10621                                         if (bb->region == bbn->region && bbn_code &&
10622                                                         bbn_code->opcode == OP_BR &&
10623                                                         bbn_code->inst_target_bb->region == bb->region) {
10624                                                 if (cfg->verbose_level > 2)
10625                                                         g_print ("in %s branch to branch triggered %d -> %d -> %d\n", cfg->method->name, 
10626                                                                  bb->block_num, bbn->block_num, bbn_code->inst_target_bb->block_num);
10627
10628                                                 replace_in_block (bbn, bb, NULL);
10629                                                 replace_out_block (bb, bbn, bbn_code->inst_target_bb);
10630                                                 link_bblock (cfg, bb, bbn_code->inst_target_bb);
10631                                                 last_ins->inst_target_bb = bbn_code->inst_target_bb;
10632                                                 changed = TRUE;
10633                                                 continue;
10634                                         }
10635                                 }
10636                         } else if (bb->out_count == 2) {
10637                                 if (last_ins && MONO_IS_COND_BRANCH_NOFP (last_ins)) {
10638                                         int branch_result = mono_eval_cond_branch (last_ins);
10639                                         MonoBasicBlock *taken_branch_target = NULL, *untaken_branch_target = NULL;
10640                                         MonoInst *bbn_code;
10641
10642                                         if (branch_result == BRANCH_TAKEN) {
10643                                                 taken_branch_target = last_ins->inst_true_bb;
10644                                                 untaken_branch_target = last_ins->inst_false_bb;
10645                                         } else if (branch_result == BRANCH_NOT_TAKEN) {
10646                                                 taken_branch_target = last_ins->inst_false_bb;
10647                                                 untaken_branch_target = last_ins->inst_true_bb;
10648                                         }
10649                                         if (taken_branch_target) {
10650                                                 /* if mono_eval_cond_branch () is ever taken to handle 
10651                                                  * non-constant values to compare, issue a pop here.
10652                                                  */
10653                                                 last_ins->opcode = OP_BR;
10654                                                 last_ins->inst_target_bb = taken_branch_target;
10655                                                 mono_unlink_bblock (cfg, bb, untaken_branch_target);
10656                                                 changed = TRUE;
10657                                                 continue;
10658                                         }
10659                                         bbn = last_ins->inst_true_bb;
10660                                         bbn_code = mono_inst_list_first (&bbn->ins_list);
10661                                         if (bb->region == bbn->region && bbn_code && bbn_code->opcode == OP_BR &&
10662                                                         bbn_code->inst_target_bb->region == bb->region) {
10663                                                 if (cfg->verbose_level > 2)             
10664                                                         g_print ("cbranch1 to branch triggered %d -> (%d) %d (0x%02x)\n", 
10665                                                                  bb->block_num, bbn->block_num, bbn_code->inst_target_bb->block_num, 
10666                                                                  bbn_code->opcode);
10667
10668                                                 /* 
10669                                                  * Unlink, then relink bblocks to avoid various
10670                                                  * tricky situations when the two targets of the branch
10671                                                  * are equal, or will become equal after the change.
10672                                                  */
10673                                                 mono_unlink_bblock (cfg, bb, last_ins->inst_true_bb);
10674                                                 mono_unlink_bblock (cfg, bb, last_ins->inst_false_bb);
10675
10676                                                 last_ins->inst_true_bb = bbn_code->inst_target_bb;
10677
10678                                                 link_bblock (cfg, bb, last_ins->inst_true_bb);
10679                                                 link_bblock (cfg, bb, last_ins->inst_false_bb);
10680
10681                                                 changed = TRUE;
10682                                                 continue;
10683                                         }
10684
10685                                         bbn = last_ins->inst_false_bb;
10686                                         bbn_code = mono_inst_list_first (&bbn->ins_list);
10687                                         if (bb->region == bbn->region && bbn_code && bbn_code->opcode == OP_BR &&
10688                                                         bbn_code->inst_target_bb->region == bb->region) {
10689                                                 if (cfg->verbose_level > 2)
10690                                                         g_print ("cbranch2 to branch triggered %d -> (%d) %d (0x%02x)\n", 
10691                                                                  bb->block_num, bbn->block_num, bbn_code->inst_target_bb->block_num, 
10692                                                                  bbn_code->opcode);
10693
10694                                                 mono_unlink_bblock (cfg, bb, last_ins->inst_true_bb);
10695                                                 mono_unlink_bblock (cfg, bb, last_ins->inst_false_bb);
10696
10697                                                 last_ins->inst_false_bb = bbn_code->inst_target_bb;
10698
10699                                                 link_bblock (cfg, bb, last_ins->inst_true_bb);
10700                                                 link_bblock (cfg, bb, last_ins->inst_false_bb);
10701
10702                                                 changed = TRUE;
10703                                                 continue;
10704                                         }
10705                                 }
10706
10707                                 /* detect and optimize to unsigned compares checks like: if (v < 0 || v > limit */
10708                                 if (last_ins && last_ins->opcode == CEE_BLT && last_ins->inst_left->inst_right->opcode == OP_ICONST) {
10709                                         if (try_unsigned_compare (cfg, bb, last_ins)) {
10710                                                 /*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));*/
10711                                                 changed = TRUE;
10712                                                 continue;
10713                                         }
10714                                 }
10715
10716                                 if (last_ins && MONO_IS_COND_BRANCH_NOFP (last_ins)) {
10717                                         if (last_ins->inst_false_bb->out_of_line && (bb->region == last_ins->inst_false_bb->region)) {
10718                                                 /* Reverse the branch */
10719                                                 last_ins->opcode = reverse_branch_op (last_ins->opcode);
10720                                                 bbn = last_ins->inst_false_bb;
10721                                                 last_ins->inst_false_bb = last_ins->inst_true_bb;
10722                                                 last_ins->inst_true_bb = bbn;
10723
10724                                                 move_basic_block_to_end (cfg, last_ins->inst_true_bb);
10725                                                 if (cfg->verbose_level > 2)
10726                                                         g_print ("cbranch to throw block triggered %d.\n", 
10727                                                                          bb->block_num);
10728                                         }
10729                                 }
10730                         }
10731                 }
10732         } while (changed && (niterations > 0));
10733
10734 }
10735
10736 static void
10737 mono_compile_create_vars (MonoCompile *cfg)
10738 {
10739         MonoMethodSignature *sig;
10740         MonoMethodHeader *header;
10741         int i;
10742
10743         header = mono_method_get_header (cfg->method);
10744
10745         sig = mono_method_signature (cfg->method);
10746         
10747         if (!MONO_TYPE_IS_VOID (sig->ret)) {
10748                 cfg->ret = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
10749                 cfg->ret->opcode = OP_RETARG;
10750                 cfg->ret->inst_vtype = sig->ret;
10751                 cfg->ret->klass = mono_class_from_mono_type (sig->ret);
10752         }
10753         if (cfg->verbose_level > 2)
10754                 g_print ("creating vars\n");
10755
10756         cfg->args = mono_mempool_alloc0 (cfg->mempool, (sig->param_count + sig->hasthis) * sizeof (MonoInst*));
10757
10758         if (sig->hasthis)
10759                 cfg->args [0] = mono_compile_create_var (cfg, &cfg->method->klass->this_arg, OP_ARG);
10760
10761         for (i = 0; i < sig->param_count; ++i) {
10762                 cfg->args [i + sig->hasthis] = mono_compile_create_var (cfg, sig->params [i], OP_ARG);
10763                 if (sig->params [i]->byref) {
10764                         cfg->disable_ssa = TRUE;
10765                 }
10766         }
10767
10768         cfg->locals_start = cfg->num_varinfo;
10769
10770         if (cfg->verbose_level > 2)
10771                 g_print ("creating locals\n");
10772
10773         for (i = 0; i < header->num_locals; ++i)
10774                 mono_compile_create_var (cfg, header->locals [i], OP_LOCAL);
10775         if (cfg->verbose_level > 2)
10776                 g_print ("locals done\n");
10777
10778 #ifdef MONO_ARCH_HAVE_CREATE_VARS
10779         mono_arch_create_vars (cfg);
10780 #endif
10781 }
10782
10783 void
10784 mono_print_code (MonoCompile *cfg)
10785 {
10786         MonoBasicBlock *bb;
10787         
10788         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
10789                 MonoInst *tree;
10790
10791                 if (!MONO_INST_LIST_EMPTY (&bb->ins_list))
10792                         g_print ("CODE BLOCK %d (nesting %d):\n",
10793                                  bb->block_num, bb->nesting);
10794
10795                 MONO_BB_FOR_EACH_INS (bb, tree) {
10796                         mono_print_tree (tree);
10797                         g_print ("\n");
10798                 }
10799         }
10800 }
10801
10802 extern const char * const mono_burg_rule_string [];
10803
10804 static void
10805 emit_state (MonoCompile *cfg, MBState *state, int goal)
10806 {
10807         MBState *kids [10];
10808         int ern = mono_burg_rule (state, goal);
10809         const guint16 *nts = mono_burg_nts_data + mono_burg_nts [ern];
10810
10811         //g_print ("rule: %s\n", mono_burg_rule_string [ern]);
10812         switch (goal) {
10813         case MB_NTERM_reg:
10814                 //if (state->reg2)
10815                 //      state->reg1 = state->reg2; /* chain rule */
10816                 //else
10817 #ifdef MONO_ARCH_ENABLE_EMIT_STATE_OPT
10818                 if (!state->reg1)
10819 #endif
10820                         state->reg1 = mono_regstate_next_int (cfg->rs);
10821                 //g_print ("alloc symbolic R%d (reg2: R%d) in block %d\n", state->reg1, state->reg2, cfg->cbb->block_num);
10822                 break;
10823         case MB_NTERM_lreg:
10824                 state->reg1 = mono_regstate_next_int (cfg->rs);
10825                 state->reg2 = mono_regstate_next_int (cfg->rs);
10826                 break;
10827         case MB_NTERM_freg:
10828 #ifdef MONO_ARCH_SOFT_FLOAT
10829                 state->reg1 = mono_regstate_next_int (cfg->rs);
10830                 state->reg2 = mono_regstate_next_int (cfg->rs);
10831 #else
10832                 state->reg1 = mono_regstate_next_float (cfg->rs);
10833 #endif
10834                 break;
10835         default:
10836 #ifdef MONO_ARCH_ENABLE_EMIT_STATE_OPT
10837                 /*
10838                  * Enabling this might cause bugs to surface in the local register
10839                  * allocators on some architectures like x86.
10840                  */
10841                 if ((state->tree->ssa_op == MONO_SSA_STORE) && (state->left->tree->opcode == OP_REGVAR)) {
10842                         /* Do not optimize away reg-reg moves */
10843                         if (! ((state->right->tree->ssa_op == MONO_SSA_LOAD) && (state->right->left->tree->opcode == OP_REGVAR))) {
10844                                 state->right->reg1 = state->left->tree->dreg;
10845                         }
10846                 }
10847 #endif
10848
10849                 /* do nothing */
10850                 break;
10851         }
10852         if (nts [0]) {
10853                 mono_burg_kids (state, ern, kids);
10854
10855                 emit_state (cfg, kids [0], nts [0]);
10856                 if (nts [1]) {
10857                         emit_state (cfg, kids [1], nts [1]);
10858                         if (nts [2]) {
10859                                 g_assert (!nts [3]);
10860                                 emit_state (cfg, kids [2], nts [2]);
10861                         }
10862                 }
10863         }
10864
10865 //      g_print ("emit: %s (%p)\n", mono_burg_rule_string [ern], state);
10866         mono_burg_emit (ern, state, state->tree, cfg);
10867 }
10868
10869 #define DEBUG_SELECTION
10870
10871 static void 
10872 mini_select_instructions (MonoCompile *cfg)
10873 {
10874         MonoBasicBlock *bb;
10875         
10876         cfg->state_pool = mono_mempool_new ();
10877         cfg->rs = mono_regstate_new ();
10878
10879         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
10880                 MonoInst *last_ins = mono_inst_list_last (&bb->ins_list);
10881
10882                 if (last_ins && MONO_IS_COND_BRANCH_OP (last_ins) &&
10883                                 bb->next_bb != last_ins->inst_false_bb) {
10884
10885                         /* we are careful when inverting, since bugs like #59580
10886                          * could show up when dealing with NaNs.
10887                          */
10888                         if (MONO_IS_COND_BRANCH_NOFP(last_ins) && bb->next_bb == last_ins->inst_true_bb) {
10889                                 MonoBasicBlock *tmp =  last_ins->inst_true_bb;
10890                                 last_ins->inst_true_bb = last_ins->inst_false_bb;
10891                                 last_ins->inst_false_bb = tmp;
10892
10893                                 last_ins->opcode = reverse_branch_op (last_ins->opcode);
10894                         } else {                        
10895                                 MonoInst *inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
10896                                 inst->opcode = OP_BR;
10897                                 inst->inst_target_bb = last_ins->inst_false_bb;
10898                                 mono_bblock_add_inst (bb, inst);
10899                         }
10900                 }
10901         }
10902
10903 #ifdef DEBUG_SELECTION
10904         if (cfg->verbose_level >= 4) {
10905         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
10906                 MonoInst *tree; 
10907                 g_print ("DUMP BLOCK %d:\n", bb->block_num);
10908
10909                 MONO_BB_FOR_EACH_INS (bb, tree) {
10910                         mono_print_tree (tree);
10911                         g_print ("\n");
10912                 }
10913         }
10914         }
10915 #endif
10916
10917         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
10918                 MonoInst *tree, *n;     
10919                 MonoInstList head;
10920                 MBState *mbstate;
10921
10922                 MONO_INST_LIST_INIT (&head);
10923                 if (MONO_INST_LIST_EMPTY (&bb->ins_list))
10924                         continue;
10925                 MONO_INST_LIST_SPLICE_INIT (&bb->ins_list, &head);
10926                 
10927                 cfg->cbb = bb;
10928                 mono_regstate_reset (cfg->rs);
10929
10930 #ifdef DEBUG_SELECTION
10931                 if (cfg->verbose_level >= 3)
10932                         g_print ("LABEL BLOCK %d:\n", bb->block_num);
10933 #endif
10934                 MONO_INST_LIST_FOR_EACH_ENTRY_SAFE (tree, n, &head, node) {
10935 #ifdef DEBUG_SELECTION
10936                         if (cfg->verbose_level >= 3) {
10937                                 mono_print_tree (tree);
10938                                 g_print ("\n");
10939                         }
10940 #endif
10941
10942                         if (!(mbstate = mono_burg_label (tree, cfg))) {
10943                                 g_warning ("unable to label tree %p", tree);
10944                                 mono_print_tree (tree);
10945                                 g_print ("\n");                         
10946                                 g_assert_not_reached ();
10947                         }
10948                         emit_state (cfg, mbstate, MB_NTERM_stmt);
10949                 }
10950                 bb->max_vreg = cfg->rs->next_vreg;
10951
10952                 mono_mempool_empty (cfg->state_pool); 
10953         }
10954         mono_mempool_destroy (cfg->state_pool); 
10955 }
10956
10957 /*
10958  * mono_normalize_opcodes:
10959  *
10960  *   Replace CEE_ and OP_ opcodes with the corresponding OP_I or OP_L opcodes.
10961  */
10962
10963 static gint16 *remap_table;
10964
10965 #if SIZEOF_VOID_P == 8
10966 #define REMAP_OPCODE(opcode) OP_L ## opcode
10967 #else
10968 #define REMAP_OPCODE(opcode) OP_I ## opcode
10969 #endif
10970
10971 static G_GNUC_UNUSED void
10972 mono_normalize_opcodes (MonoCompile *cfg, MonoBasicBlock *bb)
10973 {
10974         MonoInst *ins;
10975
10976         if (!remap_table) {
10977                 remap_table = g_new0 (gint16, OP_LAST);
10978
10979 #if SIZEOF_VOID_P == 8
10980                 remap_table [CEE_CONV_U8] = OP_ZEXT_I4;
10981                 remap_table [CEE_CONV_U] = OP_ZEXT_I4;
10982                 remap_table [CEE_CONV_I8] = OP_SEXT_I4;
10983                 remap_table [CEE_CONV_I] = OP_SEXT_I4;
10984                 remap_table [CEE_CONV_OVF_U4] = OP_LCONV_TO_OVF_U4;
10985                 remap_table [CEE_CONV_OVF_I4_UN] = OP_LCONV_TO_OVF_I4_UN;
10986 #else
10987 #endif
10988                 remap_table [CEE_CONV_R4] = OP_ICONV_TO_R4;
10989                 remap_table [CEE_CONV_R8] = OP_ICONV_TO_R8;
10990                 remap_table [CEE_CONV_I4] = OP_MOVE;
10991                 remap_table [CEE_CONV_U4] = OP_MOVE;
10992                 remap_table [CEE_CONV_I1] = REMAP_OPCODE (CONV_TO_I1);
10993                 remap_table [CEE_CONV_I2] = REMAP_OPCODE (CONV_TO_I2);
10994                 remap_table [CEE_CONV_U1] = REMAP_OPCODE (CONV_TO_U1);
10995                 remap_table [CEE_CONV_U2] = REMAP_OPCODE (CONV_TO_U2);
10996                 remap_table [CEE_CONV_R_UN] = REMAP_OPCODE (CONV_TO_R_UN);
10997                 remap_table [CEE_ADD] = REMAP_OPCODE (ADD);
10998                 remap_table [CEE_SUB] = REMAP_OPCODE (SUB);
10999                 remap_table [CEE_MUL] = REMAP_OPCODE (MUL);
11000                 remap_table [CEE_DIV] = REMAP_OPCODE (DIV);
11001                 remap_table [CEE_REM] = REMAP_OPCODE (REM);
11002                 remap_table [CEE_DIV_UN] = REMAP_OPCODE (DIV_UN);
11003                 remap_table [CEE_REM_UN] = REMAP_OPCODE (REM_UN);
11004                 remap_table [CEE_AND] = REMAP_OPCODE (AND);
11005                 remap_table [CEE_OR] = REMAP_OPCODE (OR);
11006                 remap_table [CEE_XOR] = REMAP_OPCODE (XOR);
11007                 remap_table [CEE_SHL] = REMAP_OPCODE (SHL);
11008                 remap_table [CEE_SHR] = REMAP_OPCODE (SHR);
11009                 remap_table [CEE_SHR_UN] = REMAP_OPCODE (SHR_UN);
11010                 remap_table [CEE_NOT] = REMAP_OPCODE (NOT);
11011                 remap_table [CEE_NEG] = REMAP_OPCODE (NEG);
11012                 remap_table [CEE_CALL] = OP_CALL;
11013                 remap_table [CEE_BEQ] = REMAP_OPCODE (BEQ);
11014                 remap_table [CEE_BNE_UN] = REMAP_OPCODE (BNE_UN);
11015                 remap_table [CEE_BLT] = REMAP_OPCODE (BLT);
11016                 remap_table [CEE_BLT_UN] = REMAP_OPCODE (BLT_UN);
11017                 remap_table [CEE_BGT] = REMAP_OPCODE (BGT);
11018                 remap_table [CEE_BGT_UN] = REMAP_OPCODE (BGT_UN);
11019                 remap_table [CEE_BGE] = REMAP_OPCODE (BGE);
11020                 remap_table [CEE_BGE_UN] = REMAP_OPCODE (BGE_UN);
11021                 remap_table [CEE_BLE] = REMAP_OPCODE (BLE);
11022                 remap_table [CEE_BLE_UN] = REMAP_OPCODE (BLE_UN);
11023                 remap_table [CEE_ADD_OVF] = REMAP_OPCODE (ADD_OVF);
11024                 remap_table [CEE_ADD_OVF_UN] = REMAP_OPCODE (ADD_OVF_UN);
11025                 remap_table [CEE_SUB_OVF] = REMAP_OPCODE (SUB_OVF);
11026                 remap_table [CEE_SUB_OVF_UN] = REMAP_OPCODE (SUB_OVF_UN);
11027                 remap_table [CEE_MUL_OVF] = REMAP_OPCODE (MUL_OVF);
11028                 remap_table [CEE_MUL_OVF_UN] = REMAP_OPCODE (MUL_OVF_UN);
11029         }
11030
11031         MONO_BB_FOR_EACH_INS (bb, ins) {
11032                 int remapped = remap_table [ins->opcode];
11033                 if (remapped)
11034                         ins->opcode = remapped;
11035         }
11036 }
11037
11038 void
11039 mono_codegen (MonoCompile *cfg)
11040 {
11041         MonoJumpInfo *patch_info;
11042         MonoBasicBlock *bb;
11043         int i, max_epilog_size;
11044         guint8 *code;
11045
11046         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11047                 cfg->spill_count = 0;
11048                 /* we reuse dfn here */
11049                 /* bb->dfn = bb_count++; */
11050 #ifdef MONO_ARCH_ENABLE_NORMALIZE_OPCODES
11051                 mono_normalize_opcodes (cfg, bb);
11052 #endif
11053
11054                 mono_arch_lowering_pass (cfg, bb);
11055
11056                 if (cfg->opt & MONO_OPT_PEEPHOLE)
11057                         mono_arch_peephole_pass_1 (cfg, bb);
11058
11059                 mono_local_regalloc (cfg, bb);
11060
11061                 if (cfg->opt & MONO_OPT_PEEPHOLE)
11062                         mono_arch_peephole_pass_2 (cfg, bb);
11063         }
11064
11065         if (cfg->prof_options & MONO_PROFILE_COVERAGE)
11066                 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, cfg->num_bblocks);
11067
11068         code = mono_arch_emit_prolog (cfg);
11069
11070         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
11071                 code = mono_arch_instrument_prolog (cfg, mono_profiler_method_enter, code, FALSE);
11072
11073         cfg->code_len = code - cfg->native_code;
11074         cfg->prolog_end = cfg->code_len;
11075
11076         mono_debug_open_method (cfg);
11077
11078         /* emit code all basic blocks */
11079         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11080                 bb->native_offset = cfg->code_len;
11081                 mono_arch_output_basic_block (cfg, bb);
11082
11083                 if (bb == cfg->bb_exit) {
11084                         cfg->epilog_begin = cfg->code_len;
11085
11086                         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE) {
11087                                 code = cfg->native_code + cfg->code_len;
11088                                 code = mono_arch_instrument_epilog (cfg, mono_profiler_method_leave, code, FALSE);
11089                                 cfg->code_len = code - cfg->native_code;
11090                                 g_assert (cfg->code_len < cfg->code_size);
11091                         }
11092
11093                         mono_arch_emit_epilog (cfg);
11094                 }
11095         }
11096
11097         mono_arch_emit_exceptions (cfg);
11098
11099         max_epilog_size = 0;
11100
11101         code = cfg->native_code + cfg->code_len;
11102
11103         /* we always allocate code in cfg->domain->code_mp to increase locality */
11104         cfg->code_size = cfg->code_len + max_epilog_size;
11105         /* fixme: align to MONO_ARCH_CODE_ALIGNMENT */
11106
11107         if (cfg->method->dynamic) {
11108                 /* Allocate the code into a separate memory pool so it can be freed */
11109                 cfg->dynamic_info = g_new0 (MonoJitDynamicMethodInfo, 1);
11110                 cfg->dynamic_info->code_mp = mono_code_manager_new_dynamic ();
11111                 mono_domain_lock (cfg->domain);
11112                 mono_dynamic_code_hash_insert (cfg->domain, cfg->method, cfg->dynamic_info);
11113                 mono_domain_unlock (cfg->domain);
11114
11115                 code = mono_code_manager_reserve (cfg->dynamic_info->code_mp, cfg->code_size);
11116         } else {
11117                 mono_domain_lock (cfg->domain);
11118                 code = mono_code_manager_reserve (cfg->domain->code_mp, cfg->code_size);
11119                 mono_domain_unlock (cfg->domain);
11120         }
11121
11122         memcpy (code, cfg->native_code, cfg->code_len);
11123         g_free (cfg->native_code);
11124         cfg->native_code = code;
11125         code = cfg->native_code + cfg->code_len;
11126   
11127         /* g_assert (((int)cfg->native_code & (MONO_ARCH_CODE_ALIGNMENT - 1)) == 0); */
11128         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
11129                 switch (patch_info->type) {
11130                 case MONO_PATCH_INFO_ABS: {
11131                         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (patch_info->data.target);
11132                         if (info) {
11133                                 //printf ("TEST %s %p\n", info->name, patch_info->data.target);
11134                                 if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && 
11135                                         strstr (cfg->method->name, info->name))
11136                                         /*
11137                                          * This is an icall wrapper, and this is a call to the
11138                                          * wrapped function.
11139                                          */
11140                                         ;
11141                                 else {
11142                                         /* for these array methods we currently register the same function pointer
11143                                          * since it's a vararg function. But this means that mono_find_jit_icall_by_addr ()
11144                                          * will return the incorrect one depending on the order they are registered.
11145                                          * See tests/test-arr.cs
11146                                          */
11147                                         if (strstr (info->name, "ves_array_new_va_") == NULL && strstr (info->name, "ves_array_element_address_") == NULL) {
11148                                                 patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
11149                                                 patch_info->data.name = info->name;
11150                                         }
11151                                 }
11152                         }
11153                         else {
11154                                 MonoVTable *vtable = mono_find_class_init_trampoline_by_addr (patch_info->data.target);
11155                                 if (vtable) {
11156                                         patch_info->type = MONO_PATCH_INFO_CLASS_INIT;
11157                                         patch_info->data.klass = vtable->klass;
11158                                 } else {
11159                                         MonoClass *klass = mono_find_delegate_trampoline_by_addr (patch_info->data.target);
11160                                         if (klass) {
11161                                                 patch_info->type = MONO_PATCH_INFO_DELEGATE_TRAMPOLINE;
11162                                                 patch_info->data.klass = klass;
11163                                         }
11164                                 }
11165                         }
11166                         break;
11167                 }
11168                 case MONO_PATCH_INFO_SWITCH: {
11169                         gpointer *table;
11170                         if (cfg->method->dynamic) {
11171                                 table = mono_code_manager_reserve (cfg->dynamic_info->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
11172                         } else {
11173                                 mono_domain_lock (cfg->domain);
11174                                 table = mono_code_manager_reserve (cfg->domain->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
11175                                 mono_domain_unlock (cfg->domain);
11176                         }
11177
11178                         if (!cfg->compile_aot)
11179                                 /* In the aot case, the patch already points to the correct location */
11180                                 patch_info->ip.i = patch_info->ip.label->inst_c0;
11181                         for (i = 0; i < patch_info->data.table->table_size; i++) {
11182                                 table [i] = GINT_TO_POINTER (patch_info->data.table->table [i]->native_offset);
11183                         }
11184                         patch_info->data.table->table = (MonoBasicBlock**)table;
11185                         break;
11186                 }
11187                 default:
11188                         /* do nothing */
11189                         break;
11190                 }
11191         }
11192
11193 #ifdef VALGRIND_JIT_REGISTER_MAP
11194 if (valgrind_register){
11195                 char* nm = mono_method_full_name (cfg->method, TRUE);
11196                 VALGRIND_JIT_REGISTER_MAP (nm, cfg->native_code, cfg->native_code + cfg->code_len);
11197                 g_free (nm);
11198         }
11199 #endif
11200  
11201         if (cfg->verbose_level > 0) {
11202                 char* nm = mono_method_full_name (cfg->method, TRUE);
11203                 g_print ("Method %s emitted at %p to %p (code length %d) [%s]\n", 
11204                                  nm, 
11205                                  cfg->native_code, cfg->native_code + cfg->code_len, cfg->code_len, cfg->domain->friendly_name);
11206                 g_free (nm);
11207         }
11208
11209 #ifdef MONO_ARCH_HAVE_SAVE_UNWIND_INFO
11210         mono_arch_save_unwind_info (cfg);
11211 #endif
11212         
11213         mono_arch_patch_code (cfg->method, cfg->domain, cfg->native_code, cfg->patch_info, cfg->run_cctors);
11214
11215         if (cfg->method->dynamic) {
11216                 mono_code_manager_commit (cfg->dynamic_info->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
11217         } else {
11218                 mono_domain_lock (cfg->domain);
11219                 mono_code_manager_commit (cfg->domain->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
11220                 mono_domain_unlock (cfg->domain);
11221         }
11222         
11223         mono_arch_flush_icache (cfg->native_code, cfg->code_len);
11224
11225         mono_debug_close_method (cfg);
11226 }
11227
11228
11229
11230 static void
11231 remove_critical_edges (MonoCompile *cfg) {
11232         MonoBasicBlock *bb;
11233         MonoBasicBlock *previous_bb;
11234         
11235         if (cfg->verbose_level > 3) {
11236                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11237                         MonoInst *last_ins;
11238                         int i;
11239                         printf ("remove_critical_edges %s, BEFORE BB%d (in:", mono_method_full_name (cfg->method, TRUE), bb->block_num);
11240                         for (i = 0; i < bb->in_count; i++) {
11241                                 printf (" %d", bb->in_bb [i]->block_num);
11242                         }
11243                         printf (") (out:");
11244                         for (i = 0; i < bb->out_count; i++) {
11245                                 printf (" %d", bb->out_bb [i]->block_num);
11246                         }
11247                         printf (")");
11248                         last_ins = mono_inst_list_last (&bb->ins_list);
11249                         if (last_ins) {
11250                                 printf (" ");
11251                                 mono_print_tree (last_ins);
11252                         }
11253                         printf ("\n");
11254                 }
11255         }
11256         
11257         for (previous_bb = cfg->bb_entry, bb = previous_bb->next_bb; bb != NULL; previous_bb = previous_bb->next_bb, bb = bb->next_bb) {
11258                 if (bb->in_count > 1) {
11259                         int in_bb_index;
11260                         for (in_bb_index = 0; in_bb_index < bb->in_count; in_bb_index++) {
11261                                 MonoBasicBlock *in_bb = bb->in_bb [in_bb_index];
11262                                 if (in_bb->out_count > 1) {
11263                                         MonoBasicBlock *new_bb = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock));
11264                                         MONO_INST_LIST_INIT (&new_bb->ins_list);
11265                                         new_bb->block_num = cfg->num_bblocks++;
11266 //                                      new_bb->real_offset = bb->real_offset;
11267                                         new_bb->region = bb->region;
11268                                         
11269                                         /* Do not alter the CFG while altering the BB list */
11270                                         if (previous_bb->region == bb->region) {
11271                                                 if (previous_bb != cfg->bb_entry) {
11272                                                         MonoInst *last_ins;
11273                                                         /* If previous_bb "followed through" to bb, */
11274                                                         /* keep it linked with a OP_BR */
11275                                                         last_ins = mono_inst_list_last (&previous_bb->ins_list);
11276                                                         if ((last_ins == NULL) ||
11277                                                                         ((last_ins->opcode != OP_BR) &&
11278                                                                         (!(MONO_IS_COND_BRANCH_OP (last_ins))) &&
11279                                                                         (last_ins->opcode != OP_SWITCH))) {
11280                                                                 int i;
11281                                                                 /* Make sure previous_bb really falls through bb */
11282                                                                 for (i = 0; i < previous_bb->out_count; i++) {
11283                                                                         if (previous_bb->out_bb [i] == bb) {
11284                                                                                 MonoInst *jump;
11285                                                                                 MONO_INST_NEW (cfg, jump, OP_BR);
11286                                                                                 MONO_ADD_INS (previous_bb, jump);
11287                                                                                 jump->cil_code = previous_bb->cil_code;
11288                                                                                 jump->inst_target_bb = bb;
11289                                                                                 break;
11290                                                                         }
11291                                                                 }
11292                                                         }
11293                                                 } else {
11294                                                         /* We cannot add any inst to the entry BB, so we must */
11295                                                         /* put a new BB in the middle to hold the OP_BR */
11296                                                         MonoInst *jump;
11297                                                         MonoBasicBlock *new_bb_after_entry = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock));
11298                                                         MONO_INST_LIST_INIT (&new_bb_after_entry->ins_list);
11299                                                         new_bb_after_entry->block_num = cfg->num_bblocks++;
11300 //                                                      new_bb_after_entry->real_offset = bb->real_offset;
11301                                                         new_bb_after_entry->region = bb->region;
11302                                                         
11303                                                         MONO_INST_NEW (cfg, jump, OP_BR);
11304                                                         MONO_ADD_INS (new_bb_after_entry, jump);
11305                                                         jump->cil_code = bb->cil_code;
11306                                                         jump->inst_target_bb = bb;
11307                                                         
11308                                                         previous_bb->next_bb = new_bb_after_entry;
11309                                                         previous_bb = new_bb_after_entry;
11310                                                         
11311                                                         if (cfg->verbose_level > 2) {
11312                                                                 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);
11313                                                         }
11314                                                 }
11315                                         }
11316                                         
11317                                         /* Insert new_bb in the BB list */
11318                                         previous_bb->next_bb = new_bb;
11319                                         new_bb->next_bb = bb;
11320                                         previous_bb = new_bb;
11321                                         
11322                                         /* Setup in_bb and out_bb */
11323                                         new_bb->in_bb = mono_mempool_alloc ((cfg)->mempool, sizeof (MonoBasicBlock*));
11324                                         new_bb->in_bb [0] = in_bb;
11325                                         new_bb->in_count = 1;
11326                                         new_bb->out_bb = mono_mempool_alloc ((cfg)->mempool, sizeof (MonoBasicBlock*));
11327                                         new_bb->out_bb [0] = bb;
11328                                         new_bb->out_count = 1;
11329                                         
11330                                         /* Relink in_bb and bb to (from) new_bb */
11331                                         replace_out_block (in_bb, bb, new_bb);
11332                                         replace_out_block_in_code (in_bb, bb, new_bb);
11333                                         replace_in_block (bb, in_bb, new_bb);
11334                                         
11335                                         if (cfg->verbose_level > 2) {
11336                                                 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);
11337                                         }
11338                                 }
11339                         }
11340                 }
11341         }
11342         
11343         if (cfg->verbose_level > 3) {
11344                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11345                         MonoInst *last_ins;
11346                         int i;
11347                         printf ("remove_critical_edges %s, AFTER BB%d (in:", mono_method_full_name (cfg->method, TRUE), bb->block_num);
11348                         for (i = 0; i < bb->in_count; i++) {
11349                                 printf (" %d", bb->in_bb [i]->block_num);
11350                         }
11351                         printf (") (out:");
11352                         for (i = 0; i < bb->out_count; i++) {
11353                                 printf (" %d", bb->out_bb [i]->block_num);
11354                         }
11355                         printf (")");
11356                         last_ins = mono_inst_list_last (&bb->ins_list);
11357                         if (last_ins) {
11358                                 printf (" ");
11359                                 mono_print_tree (last_ins);
11360                         }
11361                         printf ("\n");
11362                 }
11363         }
11364 }
11365
11366 /*
11367  * mini_method_compile:
11368  * @method: the method to compile
11369  * @opts: the optimization flags to use
11370  * @domain: the domain where the method will be compiled in
11371  * @run_cctors: whether we should run type ctors if possible
11372  * @compile_aot: whether this is an AOT compilation
11373  * @parts: debug flag
11374  *
11375  * Returns: a MonoCompile* pointer. Caller must check the exception_type
11376  * field in the returned struct to see if compilation succeded.
11377  */
11378 MonoCompile*
11379 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gboolean run_cctors, gboolean compile_aot, int parts)
11380 {
11381         MonoMethodHeader *header = mono_method_get_header (method);
11382         guint8 *ip;
11383         MonoCompile *cfg;
11384         MonoJitInfo *jinfo;
11385         int dfn = 0, i, code_size_ratio;
11386         gboolean deadce_has_run = FALSE;
11387         gboolean try_generic_shared;
11388         MonoMethod *method_to_compile;
11389         int gsctx_size;
11390
11391         mono_jit_stats.methods_compiled++;
11392         if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)
11393                 mono_profiler_method_jit (method);
11394  
11395         if (compile_aot)
11396                 /* We are passed the original generic method definition */
11397                 try_generic_shared = mono_class_generic_sharing_enabled (method->klass) &&
11398                         (opts & MONO_OPT_GSHARED) && (method->generic_container || method->klass->generic_container);
11399         else
11400                 try_generic_shared = mono_class_generic_sharing_enabled (method->klass) &&
11401                         (opts & MONO_OPT_GSHARED) && mono_method_is_generic_sharable_impl (method);
11402
11403         if (opts & MONO_OPT_GSHARED) {
11404                 if (try_generic_shared)
11405                         mono_stats.generics_sharable_methods++;
11406                 else if (mono_method_is_generic_impl (method))
11407                         mono_stats.generics_unsharable_methods++;
11408         }
11409
11410  restart_compile:
11411         if (try_generic_shared) {
11412                 MonoMethod *declaring_method;
11413                 MonoGenericContext *shared_context;
11414
11415                 if (compile_aot) {
11416                         declaring_method = method;
11417                 } else {
11418                         declaring_method = mono_method_get_declaring_generic_method (method);
11419                         g_assert (method->klass->generic_class->container_class == declaring_method->klass);
11420                 }
11421
11422                 if (declaring_method->generic_container)
11423                         shared_context = &declaring_method->generic_container->context;
11424                 else
11425                         shared_context = &declaring_method->klass->generic_container->context;
11426
11427                 method_to_compile = mono_class_inflate_generic_method (declaring_method, shared_context);
11428                 g_assert (method_to_compile);
11429         } else {
11430                 method_to_compile = method;
11431         }
11432
11433         cfg = g_new0 (MonoCompile, 1);
11434         cfg->method = method_to_compile;
11435         cfg->mempool = mono_mempool_new ();
11436         cfg->opt = opts;
11437         cfg->prof_options = mono_profiler_get_events ();
11438         cfg->run_cctors = run_cctors;
11439         cfg->domain = domain;
11440         cfg->verbose_level = mini_verbose;
11441         cfg->compile_aot = compile_aot;
11442         cfg->skip_visibility = method->skip_visibility;
11443         if (try_generic_shared)
11444                 cfg->generic_sharing_context = (MonoGenericSharingContext*)&cfg->generic_sharing_context;
11445         cfg->token_info_hash = g_hash_table_new (NULL, NULL);
11446         if (!header) {
11447                 cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
11448                 cfg->exception_message = g_strdup_printf ("Missing or incorrect header for method %s", cfg->method->name);
11449                 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
11450                         mono_profiler_method_end_jit (method, NULL, MONO_PROFILE_FAILED);
11451                 return cfg;
11452         }
11453
11454         ip = (guint8 *)header->code;
11455
11456         cfg->intvars = mono_mempool_alloc0 (cfg->mempool, sizeof (guint16) * STACK_MAX * header->max_stack);
11457         cfg->aliasing_info = NULL;
11458         
11459         if (cfg->verbose_level > 2)
11460                 g_print ("converting method %s\n", mono_method_full_name (method, TRUE));
11461
11462         /*
11463          * create MonoInst* which represents arguments and local variables
11464          */
11465         mono_compile_create_vars (cfg);
11466
11467         if ((i = mono_method_to_ir (cfg, method_to_compile, NULL, NULL, cfg->locals_start, NULL, NULL, NULL, 0, FALSE)) < 0) {
11468                 if (try_generic_shared && cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
11469                         if (compile_aot)
11470                                 return cfg;
11471                         mono_destroy_compile (cfg);
11472                         try_generic_shared = FALSE;
11473                         goto restart_compile;
11474                 }
11475                 g_assert (cfg->exception_type != MONO_EXCEPTION_GENERIC_SHARING_FAILED);
11476
11477                 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
11478                         mono_profiler_method_end_jit (method, NULL, MONO_PROFILE_FAILED);
11479                 /* cfg contains the details of the failure, so let the caller cleanup */
11480                 return cfg;
11481         }
11482
11483         mono_jit_stats.basic_blocks += cfg->num_bblocks;
11484         mono_jit_stats.max_basic_blocks = MAX (cfg->num_bblocks, mono_jit_stats.max_basic_blocks);
11485
11486         if ((cfg->num_varinfo > 2000) && !cfg->compile_aot) {
11487                 /* 
11488                  * we disable some optimizations if there are too many variables
11489                  * because JIT time may become too expensive. The actual number needs 
11490                  * to be tweaked and eventually the non-linear algorithms should be fixed.
11491                  */
11492                 cfg->opt &= ~ (MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP);
11493                 cfg->disable_ssa = TRUE;
11494         }
11495
11496         /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/
11497
11498         if (cfg->opt & MONO_OPT_BRANCH)
11499                 optimize_branches (cfg);
11500
11501         if (cfg->opt & MONO_OPT_SSAPRE) {
11502                 remove_critical_edges (cfg);
11503         }
11504
11505         /* Depth-first ordering on basic blocks */
11506         cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
11507
11508         df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
11509         if (cfg->num_bblocks != dfn + 1) {
11510                 MonoBasicBlock *bb;
11511
11512                 cfg->num_bblocks = dfn + 1;
11513
11514                 if (!header->clauses) {
11515                         /* remove unreachable code, because the code in them may be 
11516                          * inconsistent  (access to dead variables for example) */
11517                         for (bb = cfg->bb_entry; bb;) {
11518                                 MonoBasicBlock *bbn = bb->next_bb;
11519
11520                                 if (bbn && bbn->region == -1 && !bbn->dfn) {
11521                                         if (cfg->verbose_level > 1)
11522                                                 g_print ("found unreachable code in BB%d\n", bbn->block_num);
11523                                         bb->next_bb = bbn->next_bb;
11524                                         nullify_basic_block (bbn);                      
11525                                 } else {
11526                                         bb = bb->next_bb;
11527                                 }
11528                         }
11529                 }
11530         }
11531
11532         if (cfg->opt & MONO_OPT_LOOP) {
11533                 mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM);
11534                 mono_compute_natural_loops (cfg);
11535         }
11536
11537         /* after method_to_ir */
11538         if (parts == 1)
11539                 return cfg;
11540
11541 //#define DEBUGSSA "logic_run"
11542 #define DEBUGSSA_CLASS "Tests"
11543 #ifdef DEBUGSSA
11544
11545         if (!header->num_clauses && !cfg->disable_ssa) {
11546                 mono_local_cprop (cfg);
11547 #ifndef DISABLE_SSA
11548                 mono_ssa_compute (cfg);
11549 #endif
11550         }
11551 #else 
11552
11553         /* fixme: add all optimizations which requires SSA */
11554         if (cfg->opt & (MONO_OPT_SSA | MONO_OPT_ABCREM | MONO_OPT_SSAPRE)) {
11555                 if (!(cfg->comp_done & MONO_COMP_SSA) && !header->num_clauses && !cfg->disable_ssa) {
11556                         mono_local_cprop (cfg);
11557 #ifndef DISABLE_SSA
11558                         mono_ssa_compute (cfg);
11559 #endif
11560
11561                         if (cfg->verbose_level >= 2) {
11562                                 print_dfn (cfg);
11563                         }
11564                 }
11565         }
11566 #endif
11567
11568         /* after SSA translation */
11569         if (parts == 2)
11570                 return cfg;
11571
11572         if ((cfg->opt & MONO_OPT_CONSPROP) || (cfg->opt & MONO_OPT_COPYPROP)) {
11573                 if (cfg->comp_done & MONO_COMP_SSA) {
11574 #ifndef DISABLE_SSA
11575                         mono_ssa_cprop (cfg);
11576 #endif
11577                 } else {
11578                         mono_local_cprop (cfg);
11579                 }
11580         }
11581
11582 #ifndef DISABLE_SSA
11583         if (cfg->comp_done & MONO_COMP_SSA) {                   
11584                 //mono_ssa_deadce (cfg);
11585
11586                 //mono_ssa_strength_reduction (cfg);
11587
11588                 if (cfg->opt & MONO_OPT_SSAPRE) {
11589                         mono_perform_ssapre (cfg);
11590                         //mono_local_cprop (cfg);
11591                 }
11592                 
11593                 if (cfg->opt & MONO_OPT_DEADCE) {
11594                         mono_ssa_deadce (cfg);
11595                         deadce_has_run = TRUE;
11596                 }
11597                 
11598                 if ((cfg->flags & MONO_CFG_HAS_LDELEMA) && (cfg->opt & MONO_OPT_ABCREM))
11599                         mono_perform_abc_removal (cfg);
11600                 
11601                 mono_ssa_remove (cfg);
11602
11603                 if (cfg->opt & MONO_OPT_BRANCH)
11604                         optimize_branches (cfg);
11605         }
11606 #endif
11607
11608         /* after SSA removal */
11609         if (parts == 3)
11610                 return cfg;
11611
11612         if (cfg->verbose_level > 4) {
11613                 printf ("BEFORE DECOMPSE START\n");
11614                 mono_print_code (cfg);
11615                 printf ("BEFORE DECOMPSE END\n");
11616         }
11617         
11618         decompose_pass (cfg);
11619
11620         if (cfg->got_var) {
11621                 GList *regs;
11622
11623                 g_assert (cfg->got_var_allocated);
11624
11625                 /* 
11626                  * Allways allocate the GOT var to a register, because keeping it
11627                  * in memory will increase the number of live temporaries in some
11628                  * code created by inssel.brg, leading to the well known spills+
11629                  * branches problem. Testcase: mcs crash in 
11630                  * System.MonoCustomAttrs:GetCustomAttributes.
11631                  */
11632                 regs = mono_arch_get_global_int_regs (cfg);
11633                 g_assert (regs);
11634                 cfg->got_var->opcode = OP_REGVAR;
11635                 cfg->got_var->dreg = GPOINTER_TO_INT (regs->data);
11636                 cfg->used_int_regs |= 1LL << cfg->got_var->dreg;
11637                 
11638                 g_list_free (regs);
11639         }
11640
11641         /* todo: remove code when we have verified that the liveness for try/catch blocks
11642          * works perfectly 
11643          */
11644         /* 
11645          * Currently, this can't be commented out since exception blocks are not
11646          * processed during liveness analysis.
11647          */
11648         mono_liveness_handle_exception_clauses (cfg);
11649
11650         if (cfg->opt & MONO_OPT_LINEARS) {
11651                 GList *vars, *regs;
11652                 
11653                 /* For now, compute aliasing info only if needed for deadce... */
11654                 if ((cfg->opt & MONO_OPT_DEADCE) && (! deadce_has_run) && (header->num_clauses == 0)) {
11655                         cfg->aliasing_info = mono_build_aliasing_information (cfg);
11656                 }
11657
11658                 /* fixme: maybe we can avoid to compute livenesss here if already computed ? */
11659                 cfg->comp_done &= ~MONO_COMP_LIVENESS;
11660                 if (!(cfg->comp_done & MONO_COMP_LIVENESS))
11661                         mono_analyze_liveness (cfg);
11662
11663                 if (cfg->aliasing_info != NULL) {
11664                         mono_aliasing_deadce (cfg->aliasing_info);
11665                         deadce_has_run = TRUE;
11666                 }
11667                 
11668                 if ((vars = mono_arch_get_allocatable_int_vars (cfg))) {
11669                         regs = mono_arch_get_global_int_regs (cfg);
11670                         if (cfg->got_var)
11671                                 regs = g_list_delete_link (regs, regs);
11672                         mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs);
11673                 }
11674                 
11675                 if (cfg->aliasing_info != NULL) {
11676                         mono_destroy_aliasing_information (cfg->aliasing_info);
11677                         cfg->aliasing_info = NULL;
11678                 }
11679         }
11680
11681         //mono_print_code (cfg);
11682
11683     //print_dfn (cfg);
11684         
11685         /* variables are allocated after decompose, since decompose could create temps */
11686         mono_arch_allocate_vars (cfg);
11687
11688         if (cfg->opt & MONO_OPT_CFOLD)
11689                 mono_constant_fold (cfg);
11690
11691         mini_select_instructions (cfg);
11692
11693         mono_codegen (cfg);
11694         if (cfg->verbose_level >= 2) {
11695                 char *id =  mono_method_full_name (cfg->method, FALSE);
11696                 mono_disassemble_code (cfg, cfg->native_code, cfg->code_len, id + 3);
11697                 g_free (id);
11698         }
11699
11700         if (cfg->generic_sharing_context)
11701                 gsctx_size = sizeof (MonoGenericSharingContext*);
11702         else
11703                 gsctx_size = 0;
11704
11705         if (cfg->method->dynamic) {
11706                 jinfo = g_malloc0 (sizeof (MonoJitInfo) + (header->num_clauses * sizeof (MonoJitExceptionInfo)) +
11707                                 gsctx_size);
11708         } else {
11709                 /* we access cfg->domain->mp */
11710                 mono_domain_lock (cfg->domain);
11711                 jinfo = mono_mempool_alloc0 (cfg->domain->mp, sizeof (MonoJitInfo) +
11712                                 (header->num_clauses * sizeof (MonoJitExceptionInfo)) +
11713                                 gsctx_size);
11714                 mono_domain_unlock (cfg->domain);
11715         }
11716
11717         jinfo->method = method;
11718         jinfo->code_start = cfg->native_code;
11719         jinfo->code_size = cfg->code_len;
11720         jinfo->used_regs = cfg->used_int_regs;
11721         jinfo->domain_neutral = (cfg->opt & MONO_OPT_SHARED) != 0;
11722         jinfo->cas_inited = FALSE; /* initialization delayed at the first stalk walk using this method */
11723         jinfo->num_clauses = header->num_clauses;
11724
11725         if (cfg->generic_sharing_context) {
11726                 jinfo->has_generic_sharing_context = 1;
11727                 mono_jit_info_set_generic_sharing_context (jinfo, cfg->generic_sharing_context);
11728         }
11729
11730         if (header->num_clauses) {
11731                 int i;
11732
11733                 for (i = 0; i < header->num_clauses; i++) {
11734                         MonoExceptionClause *ec = &header->clauses [i];
11735                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
11736                         MonoBasicBlock *tblock;
11737                         MonoInst *exvar;
11738
11739                         ei->flags = ec->flags;
11740
11741                         exvar = mono_find_exvar_for_offset (cfg, ec->handler_offset);
11742                         ei->exvar_offset = exvar ? exvar->inst_offset : 0;
11743
11744                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
11745                                 tblock = cfg->cil_offset_to_bb [ec->data.filter_offset];
11746                                 g_assert (tblock);
11747                                 ei->data.filter = cfg->native_code + tblock->native_offset;
11748                         } else {
11749                                 ei->data.catch_class = ec->data.catch_class;
11750                         }
11751
11752                         tblock = cfg->cil_offset_to_bb [ec->try_offset];
11753                         g_assert (tblock);
11754                         ei->try_start = cfg->native_code + tblock->native_offset;
11755                         g_assert (tblock->native_offset);
11756                         tblock = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
11757                         g_assert (tblock);
11758                         ei->try_end = cfg->native_code + tblock->native_offset;
11759                         g_assert (tblock->native_offset);
11760                         tblock = cfg->cil_offset_to_bb [ec->handler_offset];
11761                         g_assert (tblock);
11762                         ei->handler_start = cfg->native_code + tblock->native_offset;
11763                 }
11764         }
11765
11766         cfg->jit_info = jinfo;
11767 #if defined(__arm__)
11768         mono_arch_fixup_jinfo (cfg);
11769 #endif
11770
11771         mono_domain_lock (cfg->domain);
11772         mono_jit_info_table_add (cfg->domain, jinfo);
11773
11774         if (cfg->method->dynamic)
11775                 mono_dynamic_code_hash_lookup (cfg->domain, cfg->method)->ji = jinfo;
11776         mono_domain_unlock (cfg->domain);
11777
11778         /* collect statistics */
11779         mono_jit_stats.allocated_code_size += cfg->code_len;
11780         code_size_ratio = cfg->code_len;
11781         if (code_size_ratio > mono_jit_stats.biggest_method_size) {
11782                         mono_jit_stats.biggest_method_size = code_size_ratio;
11783                         mono_jit_stats.biggest_method = method;
11784         }
11785         code_size_ratio = (code_size_ratio * 100) / mono_method_get_header (method)->code_size;
11786         if (code_size_ratio > mono_jit_stats.max_code_size_ratio) {
11787                 mono_jit_stats.max_code_size_ratio = code_size_ratio;
11788                 mono_jit_stats.max_ratio_method = method;
11789         }
11790         mono_jit_stats.native_code_size += cfg->code_len;
11791
11792         if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
11793                 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
11794
11795         return cfg;
11796 }
11797
11798 static MonoJitInfo*
11799 lookup_generic_method (MonoDomain *domain, MonoMethod *method)
11800 {
11801         MonoMethod *open_method;
11802
11803         if (!mono_method_is_generic_sharable_impl (method))
11804                 return NULL;
11805
11806         open_method = mono_method_get_declaring_generic_method (method);
11807
11808         return mono_domain_lookup_shared_generic (domain, open_method);
11809 }
11810
11811 static MonoJitInfo*
11812 lookup_method (MonoDomain *domain, MonoMethod *method)
11813 {
11814         MonoJitInfo *ji = mono_internal_hash_table_lookup (&domain->jit_code_hash, method);
11815
11816         if (ji != NULL)
11817                 return ji;
11818
11819         return lookup_generic_method (domain, method);
11820 }
11821
11822 static gpointer
11823 mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain, int opt)
11824 {
11825         MonoCompile *cfg;
11826         gpointer code = NULL;
11827         MonoJitInfo *info;
11828
11829 #ifdef MONO_USE_AOT_COMPILER
11830         if ((opt & MONO_OPT_AOT) && !(mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)) {
11831                 MonoDomain *domain = mono_domain_get ();
11832
11833                 mono_class_init (method->klass);
11834
11835                 mono_domain_lock (domain);
11836                 if ((code = mono_aot_get_method (domain, method))) {
11837                         mono_domain_unlock (domain);
11838                         mono_runtime_class_init (mono_class_vtable (domain, method->klass));
11839                         return code;
11840                 }
11841
11842                 mono_domain_unlock (domain);
11843         }
11844 #endif
11845
11846         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
11847             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
11848                 MonoMethod *nm;
11849                 MonoMethodPInvoke* piinfo = (MonoMethodPInvoke *) method;
11850
11851                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE && !MONO_CLASS_IS_IMPORT(method->klass))
11852                         g_error ("Method '%s' in assembly '%s' contains native code and mono can't run it. The assembly was probably created by Managed C++.\n", mono_method_full_name (method, TRUE), method->klass->image->name);
11853
11854                 if (!piinfo->addr) {
11855                         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
11856                                 piinfo->addr = mono_lookup_internal_call (method);
11857                         else
11858                                 if (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)
11859                                         mono_lookup_pinvoke_call (method, NULL, NULL);
11860                 }
11861                         nm = mono_marshal_get_native_wrapper (method, check_for_pending_exc);
11862                         return mono_get_addr_from_ftnptr (mono_compile_method (nm));
11863
11864                         //if (mono_debug_format != MONO_DEBUG_FORMAT_NONE) 
11865                         //mono_debug_add_wrapper (method, nm);
11866         } else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
11867                 const char *name = method->name;
11868                 MonoMethod *nm;
11869
11870                 if (method->klass->parent == mono_defaults.multicastdelegate_class) {
11871                         if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
11872                                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name ("mono_delegate_ctor");
11873                                 g_assert (mi);
11874                                 return mono_get_addr_from_ftnptr ((gpointer)mono_icall_get_wrapper (mi));
11875                         } else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
11876 #ifdef MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE
11877                                 return mono_create_delegate_trampoline (method->klass);
11878 #else
11879                                 nm = mono_marshal_get_delegate_invoke (method, NULL);
11880                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
11881 #endif
11882                         } else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
11883                                 nm = mono_marshal_get_delegate_begin_invoke (method);
11884                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
11885                         } else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
11886                                 nm = mono_marshal_get_delegate_end_invoke (method);
11887                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
11888                         }
11889                 }
11890                 return NULL;
11891         }
11892
11893         cfg = mini_method_compile (method, opt, target_domain, TRUE, FALSE, 0);
11894
11895         switch (cfg->exception_type) {
11896         case MONO_EXCEPTION_NONE: break;
11897         case MONO_EXCEPTION_TYPE_LOAD:
11898         case MONO_EXCEPTION_MISSING_FIELD:
11899         case MONO_EXCEPTION_MISSING_METHOD:
11900         case MONO_EXCEPTION_FILE_NOT_FOUND: {
11901                 /* Throw a type load exception if needed */
11902                 MonoLoaderError *error = mono_loader_get_last_error ();
11903                 MonoException *ex;
11904
11905                 if (error) {
11906                         ex = mono_loader_error_prepare_exception (error);
11907                 } else {
11908                         if (cfg->exception_ptr) {
11909                                 ex = mono_class_get_exception_for_failure (cfg->exception_ptr);
11910                         } else {
11911                                 if (cfg->exception_type == MONO_EXCEPTION_MISSING_FIELD)
11912                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingFieldException", cfg->exception_message);
11913                                 else if (cfg->exception_type == MONO_EXCEPTION_MISSING_METHOD)
11914                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingMethodException", cfg->exception_message);
11915                                 else if (cfg->exception_type == MONO_EXCEPTION_TYPE_LOAD)
11916                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "TypeLoadException", cfg->exception_message);
11917                                 else if (cfg->exception_type == MONO_EXCEPTION_FILE_NOT_FOUND)
11918                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "FileNotFoundException", cfg->exception_message);
11919                                 else
11920                                         g_assert_not_reached ();
11921                         }
11922                 }
11923                 mono_destroy_compile (cfg);
11924                 mono_raise_exception (ex);
11925                 break;
11926         }
11927         case MONO_EXCEPTION_INVALID_PROGRAM: {
11928                 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "InvalidProgramException", cfg->exception_message);
11929                 mono_destroy_compile (cfg);
11930                 mono_raise_exception (ex);
11931                 break;
11932         }
11933         case MONO_EXCEPTION_UNVERIFIABLE_IL: {
11934                 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System.Security", "VerificationException", cfg->exception_message);
11935                 mono_destroy_compile (cfg);
11936                 mono_raise_exception (ex);
11937                 break;
11938         }
11939         case MONO_EXCEPTION_METHOD_ACCESS: {
11940                 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MethodAccessException", cfg->exception_message);
11941                 mono_destroy_compile (cfg);
11942                 mono_raise_exception (ex);
11943                 break;
11944         }
11945         case MONO_EXCEPTION_FIELD_ACCESS: {
11946                 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "FieldAccessException", cfg->exception_message);
11947                 mono_destroy_compile (cfg);
11948                 mono_raise_exception (ex);
11949                 break;
11950         }
11951         /* this can only be set if the security manager is active */
11952         case MONO_EXCEPTION_SECURITY_LINKDEMAND: {
11953                 MonoSecurityManager* secman = mono_security_manager_get_methods ();
11954                 MonoObject *exc = NULL;
11955                 gpointer args [2];
11956
11957                 args [0] = &cfg->exception_data;
11958                 args [1] = &method;
11959                 mono_runtime_invoke (secman->linkdemandsecurityexception, NULL, args, &exc);
11960
11961                 mono_destroy_compile (cfg);
11962                 cfg = NULL;
11963
11964                 mono_raise_exception ((MonoException*)exc);
11965         }
11966         default:
11967                 g_assert_not_reached ();
11968         }
11969
11970         mono_domain_lock (target_domain);
11971
11972         /* Check if some other thread already did the job. In this case, we can
11973        discard the code this thread generated. */
11974
11975         if ((info = lookup_method (target_domain, method))) {
11976                 /* We can't use a domain specific method in another domain */
11977                 if ((target_domain == mono_domain_get ()) || info->domain_neutral) {
11978                         code = info->code_start;
11979 //                      printf("Discarding code for method %s\n", method->name);
11980                 }
11981         }
11982         
11983         if (code == NULL) {
11984                 mono_internal_hash_table_insert (&target_domain->jit_code_hash, method, cfg->jit_info);
11985                 code = cfg->native_code;
11986
11987                 if (cfg->generic_sharing_context && mono_method_is_generic_sharable_impl (method)) {
11988                         /* g_print ("inserting method %s.%s.%s\n", method->klass->name_space, method->klass->name, method->name); */
11989                         mono_domain_register_shared_generic (target_domain, 
11990                                 mono_method_get_declaring_generic_method (method), cfg->jit_info);
11991                         mono_stats.generics_shared_methods++;
11992                 }
11993         }
11994
11995         mono_destroy_compile (cfg);
11996
11997         if (target_domain->jump_target_hash) {
11998                 MonoJumpInfo patch_info;
11999                 GSList *list, *tmp;
12000                 list = g_hash_table_lookup (target_domain->jump_target_hash, method);
12001                 if (list) {
12002                         patch_info.next = NULL;
12003                         patch_info.ip.i = 0;
12004                         patch_info.type = MONO_PATCH_INFO_METHOD_JUMP;
12005                         patch_info.data.method = method;
12006                         g_hash_table_remove (target_domain->jump_target_hash, method);
12007                 }
12008                 for (tmp = list; tmp; tmp = tmp->next)
12009                         mono_arch_patch_code (NULL, target_domain, tmp->data, &patch_info, TRUE);
12010                 g_slist_free (list);
12011         }
12012
12013         mono_domain_unlock (target_domain);
12014
12015         mono_runtime_class_init (mono_class_vtable (target_domain, method->klass));
12016         return code;
12017 }
12018
12019 static gpointer
12020 mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt)
12021 {
12022         MonoDomain *target_domain, *domain = mono_domain_get ();
12023         MonoJitInfo *info;
12024         gpointer p;
12025         MonoJitICallInfo *callinfo = NULL;
12026
12027         /*
12028          * ICALL wrappers are handled specially, since there is only one copy of them
12029          * shared by all appdomains.
12030          */
12031         if ((method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && (strstr (method->name, "__icall_wrapper_") == method->name)) {
12032                 const char *icall_name;
12033
12034                 icall_name = method->name + strlen ("__icall_wrapper_");
12035                 g_assert (icall_name);
12036                 callinfo = mono_find_jit_icall_by_name (icall_name);
12037                 g_assert (callinfo);
12038
12039                 /* Must be domain neutral since there is only one copy */
12040                 opt |= MONO_OPT_SHARED;
12041         }
12042
12043         if (opt & MONO_OPT_SHARED)
12044                 target_domain = mono_get_root_domain ();
12045         else 
12046                 target_domain = domain;
12047
12048         mono_domain_lock (target_domain);
12049
12050         if ((info = lookup_method (target_domain, method))) {
12051                 /* We can't use a domain specific method in another domain */
12052                 if (! ((domain != target_domain) && !info->domain_neutral)) {
12053                         mono_domain_unlock (target_domain);
12054                         mono_jit_stats.methods_lookups++;
12055                         mono_runtime_class_init (mono_class_vtable (domain, method->klass));
12056                         return mono_create_ftnptr (target_domain, info->code_start);
12057                 }
12058         }
12059
12060         mono_domain_unlock (target_domain);
12061         p = mono_create_ftnptr (target_domain, mono_jit_compile_method_inner (method, target_domain, opt));
12062
12063         if (callinfo) {
12064                 mono_jit_lock ();
12065                 if (!callinfo->wrapper) {
12066                         callinfo->wrapper = p;
12067                         mono_register_jit_icall_wrapper (callinfo, p);
12068                         mono_debug_add_icall_wrapper (method, callinfo);
12069                 }
12070                 mono_jit_unlock ();
12071         }
12072
12073         return p;
12074 }
12075
12076 static gpointer
12077 mono_jit_compile_method (MonoMethod *method)
12078 {
12079         return mono_jit_compile_method_with_opt (method, default_opt);
12080 }
12081
12082 static void
12083 invalidated_delegate_trampoline (char *desc)
12084 {
12085         g_error ("Unmanaged code called delegate of type %s which was already garbage collected.\n"
12086                  "See http://www.go-mono.com/delegate.html for an explanation and ways to fix this.",
12087                  desc);
12088 }
12089
12090 /*
12091  * mono_jit_free_method:
12092  *
12093  *  Free all memory allocated by the JIT for METHOD.
12094  */
12095 static void
12096 mono_jit_free_method (MonoDomain *domain, MonoMethod *method)
12097 {
12098         MonoJitDynamicMethodInfo *ji;
12099         gboolean destroy = TRUE;
12100
12101         g_assert (method->dynamic);
12102
12103         mono_domain_lock (domain);
12104         ji = mono_dynamic_code_hash_lookup (domain, method);
12105         mono_domain_unlock (domain);
12106
12107         if (!ji)
12108                 return;
12109         mono_domain_lock (domain);
12110         g_hash_table_remove (domain->dynamic_code_hash, method);
12111         mono_internal_hash_table_remove (&domain->jit_code_hash, method);
12112         g_hash_table_remove (domain->jump_trampoline_hash, method);
12113         mono_domain_unlock (domain);
12114
12115 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
12116         if (debug_options.keep_delegates && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
12117                 /*
12118                  * Instead of freeing the code, change it to call an error routine
12119                  * so people can fix their code.
12120                  */
12121                 char *type = mono_type_full_name (&method->klass->byval_arg);
12122                 char *type_and_method = g_strdup_printf ("%s.%s", type, method->name);
12123
12124                 g_free (type);
12125                 mono_arch_invalidate_method (ji->ji, invalidated_delegate_trampoline, type_and_method);
12126                 destroy = FALSE;
12127         }
12128 #endif
12129
12130         /* 
12131          * This needs to be done before freeing code_mp, since the code address is the
12132          * key in the table, so if we free the code_mp first, another thread can grab the
12133          * same code address and replace our entry in the table.
12134          */
12135         mono_jit_info_table_remove (domain, ji->ji);
12136
12137         if (destroy)
12138                 mono_code_manager_destroy (ji->code_mp);
12139         mono_thread_hazardous_free_or_queue (ji->ji, g_free);
12140         g_free (ji);
12141 }
12142
12143 static gpointer
12144 mono_jit_find_compiled_method (MonoDomain *domain, MonoMethod *method)
12145 {
12146         MonoDomain *target_domain;
12147         MonoJitInfo *info;
12148
12149         if (default_opt & MONO_OPT_SHARED)
12150                 target_domain = mono_get_root_domain ();
12151         else 
12152                 target_domain = domain;
12153
12154         mono_domain_lock (target_domain);
12155
12156         if ((info = lookup_method (target_domain, method))) {
12157                 /* We can't use a domain specific method in another domain */
12158                 if (! ((domain != target_domain) && !info->domain_neutral)) {
12159                         mono_domain_unlock (target_domain);
12160                         mono_jit_stats.methods_lookups++;
12161                         return info->code_start;
12162                 }
12163         }
12164
12165         mono_domain_unlock (target_domain);
12166
12167         return NULL;
12168 }
12169
12170 /**
12171  * mono_jit_runtime_invoke:
12172  * @method: the method to invoke
12173  * @obj: this pointer
12174  * @params: array of parameter values.
12175  * @exc: used to catch exceptions objects
12176  */
12177 static MonoObject*
12178 mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
12179 {
12180         MonoMethod *invoke;
12181         MonoObject *(*runtime_invoke) (MonoObject *this, void **params, MonoObject **exc, void* compiled_method);
12182         void* compiled_method;
12183
12184         if (obj == NULL && !(method->flags & METHOD_ATTRIBUTE_STATIC) && !method->string_ctor && (method->wrapper_type == 0)) {
12185                 g_warning ("Ignoring invocation of an instance method on a NULL instance.\n");
12186                 return NULL;
12187         }
12188
12189         invoke = mono_marshal_get_runtime_invoke (method);
12190         runtime_invoke = mono_jit_compile_method (invoke);
12191         
12192         /* We need this here becuase mono_marshal_get_runtime_invoke can be place 
12193          * the helper method in System.Object and not the target class
12194          */
12195         mono_runtime_class_init (mono_class_vtable (mono_domain_get (), method->klass));
12196
12197         if (method->klass->rank && (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
12198                 (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
12199                 /* 
12200                  * Array Get/Set/Address methods. The JIT implements them using inline code 
12201                  * inside the runtime invoke wrappers, so no need to compile them.
12202                  */
12203                 compiled_method = NULL;
12204         } else {
12205                 compiled_method = mono_jit_compile_method (method);
12206         }
12207         return runtime_invoke (obj, params, exc, compiled_method);
12208 }
12209
12210 #ifdef MONO_GET_CONTEXT
12211 #define GET_CONTEXT MONO_GET_CONTEXT
12212 #endif
12213
12214 #ifndef GET_CONTEXT
12215 #ifdef PLATFORM_WIN32
12216 #define GET_CONTEXT \
12217         struct sigcontext *ctx = (struct sigcontext*)_dummy;
12218 #else
12219 #ifdef MONO_ARCH_USE_SIGACTION
12220 #define GET_CONTEXT \
12221     void *ctx = context;
12222 #elif defined(__sparc__)
12223 #define GET_CONTEXT \
12224     void *ctx = sigctx;
12225 #else
12226 #define GET_CONTEXT \
12227         void **_p = (void **)&_dummy; \
12228         struct sigcontext *ctx = (struct sigcontext *)++_p;
12229 #endif
12230 #endif
12231 #endif
12232
12233 #ifdef MONO_ARCH_USE_SIGACTION
12234 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy, siginfo_t *info, void *context)
12235 #elif defined(__sparc__)
12236 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy, void *sigctx)
12237 #else
12238 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy)
12239 #endif
12240
12241 static void
12242 SIG_HANDLER_SIGNATURE (sigfpe_signal_handler)
12243 {
12244         MonoException *exc = NULL;
12245 #ifndef MONO_ARCH_USE_SIGACTION
12246         void *info = NULL;
12247 #endif
12248         GET_CONTEXT;
12249
12250 #if defined(MONO_ARCH_HAVE_IS_INT_OVERFLOW)
12251         if (mono_arch_is_int_overflow (ctx, info))
12252                 exc = mono_get_exception_arithmetic ();
12253         else
12254                 exc = mono_get_exception_divide_by_zero ();
12255 #else
12256         exc = mono_get_exception_divide_by_zero ();
12257 #endif
12258         
12259         mono_arch_handle_exception (ctx, exc, FALSE);
12260 }
12261
12262 static void
12263 SIG_HANDLER_SIGNATURE (sigill_signal_handler)
12264 {
12265         MonoException *exc;
12266         GET_CONTEXT;
12267
12268         exc = mono_get_exception_execution_engine ("SIGILL");
12269         
12270         mono_arch_handle_exception (ctx, exc, FALSE);
12271 }
12272
12273 static void
12274 SIG_HANDLER_SIGNATURE (sigsegv_signal_handler)
12275 {
12276 #ifndef MONO_ARCH_SIGSEGV_ON_ALTSTACK
12277         MonoException *exc = NULL;
12278 #endif
12279         MonoJitInfo *ji;
12280
12281 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
12282         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
12283 #endif
12284         GET_CONTEXT;
12285
12286 #ifdef MONO_ARCH_USE_SIGACTION
12287         if (debug_options.collect_pagefault_stats) {
12288                 if (mono_raw_buffer_is_pagefault (info->si_addr)) {
12289                         mono_raw_buffer_handle_pagefault (info->si_addr);
12290                         return;
12291                 }
12292                 if (mono_aot_is_pagefault (info->si_addr)) {
12293                         mono_aot_handle_pagefault (info->si_addr);
12294                         return;
12295                 }
12296         }
12297 #endif
12298
12299         ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context (ctx));
12300
12301 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
12302         /* we got a stack overflow in the soft-guard pages
12303          * There are two cases:
12304          * 1) managed code caused the overflow: we unprotect the soft-guard page
12305          * and let the arch-specific code trigger the exception handling mechanism
12306          * in the thread stack. The soft-guard pages will be protected again as the stack is unwound.
12307          * 2) unmanaged code caused the overflow: we unprotect the soft-guard page
12308          * and hope we can continue with those enabled, at least until the hard-guard page
12309          * is hit. The alternative to continuing here is to just print a message and abort.
12310          * We may add in the future the code to protect the pages again in the codepath
12311          * when we return from unmanaged to managed code.
12312          */
12313         if (jit_tls->stack_ovf_guard_size && (guint8*)info->si_addr >= (guint8*)jit_tls->stack_ovf_guard_base &&
12314                         (guint8*)info->si_addr < (guint8*)jit_tls->stack_ovf_guard_base + jit_tls->stack_ovf_guard_size) {
12315                 mono_mprotect (jit_tls->stack_ovf_guard_base, jit_tls->stack_ovf_guard_size, MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
12316                 if (ji) {
12317                         mono_arch_handle_altstack_exception (ctx, info->si_addr, TRUE);
12318                 } else {
12319                         /* We print a message: after this even managed stack overflows
12320                          * may crash the runtime
12321                          */
12322                         fprintf (stderr, "Stack overflow in unmanaged: IP: %p, fault addr: %p\n", mono_arch_ip_from_context (ctx), (gpointer)info->si_addr);
12323                 }
12324                 return;
12325         }
12326         /* The hard-guard page has been hit: there is not much we can do anymore
12327          * Print a hopefully clear message and abort.
12328          */
12329         if (jit_tls->stack_size && 
12330                         ABS ((guint8*)info->si_addr - ((guint8*)jit_tls->end_of_stack - jit_tls->stack_size)) < 32768) {
12331                 const char *method;
12332                 /* we don't do much now, but we can warn the user with a useful message */
12333                 fprintf (stderr, "Stack overflow: IP: %p, fault addr: %p\n", mono_arch_ip_from_context (ctx), (gpointer)info->si_addr);
12334                 if (ji && ji->method)
12335                         method = mono_method_full_name (ji->method, TRUE);
12336                 else
12337                         method = "Unmanaged";
12338                 fprintf (stderr, "At %s\n", method);
12339                 abort ();
12340         } else {
12341                 mono_arch_handle_altstack_exception (ctx, info->si_addr, FALSE);
12342         }
12343 #else
12344
12345         if (!ji) {
12346                 mono_handle_native_sigsegv (SIGSEGV, ctx);
12347         }
12348                         
12349         mono_arch_handle_exception (ctx, exc, FALSE);
12350 #endif
12351 }
12352
12353 #ifndef PLATFORM_WIN32
12354
12355 static void
12356 SIG_HANDLER_SIGNATURE (sigabrt_signal_handler)
12357 {
12358         MonoJitInfo *ji;
12359         GET_CONTEXT;
12360
12361         ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
12362         if (!ji) {
12363                 mono_handle_native_sigsegv (SIGABRT, ctx);
12364         }
12365 }
12366
12367 static void
12368 SIG_HANDLER_SIGNATURE (sigusr1_signal_handler)
12369 {
12370         gboolean running_managed;
12371         MonoException *exc;
12372         MonoThread *thread = mono_thread_current ();
12373         void *ji;
12374         
12375         GET_CONTEXT;
12376
12377         if (thread->thread_dump_requested) {
12378                 thread->thread_dump_requested = FALSE;
12379
12380                 mono_print_thread_dump (ctx);
12381         }
12382
12383         /*
12384          * FIXME:
12385          * This is an async signal, so the code below must not call anything which
12386          * is not async safe. That includes the pthread locking functions. If we
12387          * know that we interrupted managed code, then locking is safe.
12388          */
12389         ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
12390         running_managed = ji != NULL;
12391         
12392         exc = mono_thread_request_interruption (running_managed); 
12393         if (!exc) return;
12394
12395         mono_arch_handle_exception (ctx, exc, FALSE);
12396 }
12397
12398 static void
12399 SIG_HANDLER_SIGNATURE (sigprof_signal_handler)
12400 {
12401         GET_CONTEXT;
12402
12403         mono_profiler_stat_hit (mono_arch_ip_from_context (ctx), ctx);
12404 }
12405
12406 static void
12407 SIG_HANDLER_SIGNATURE (sigquit_signal_handler)
12408 {
12409         GET_CONTEXT;
12410
12411         printf ("Full thread dump:\n");
12412
12413         mono_threads_request_thread_dump ();
12414
12415         /*
12416          * print_thread_dump () skips the current thread, since sending a signal
12417          * to it would invoke the signal handler below the sigquit signal handler,
12418          * and signal handlers don't create an lmf, so the stack walk could not
12419          * be performed.
12420          */
12421         mono_print_thread_dump (ctx);
12422 }
12423
12424 static void
12425 SIG_HANDLER_SIGNATURE (sigusr2_signal_handler)
12426 {
12427         gboolean enabled = mono_trace_is_enabled ();
12428
12429         mono_trace_enable (!enabled);
12430 }
12431
12432 #endif
12433
12434 static void
12435 SIG_HANDLER_SIGNATURE (sigint_signal_handler)
12436 {
12437         MonoException *exc;
12438         GET_CONTEXT;
12439
12440         exc = mono_get_exception_execution_engine ("Interrupted (SIGINT).");
12441         
12442         mono_arch_handle_exception (ctx, exc, FALSE);
12443 }
12444
12445 #ifdef PLATFORM_MACOSX
12446
12447 /*
12448  * This code disables the CrashReporter of MacOS X by installing
12449  * a dummy Mach exception handler.
12450  */
12451
12452 /*
12453  * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/exc_server.html
12454  */
12455 extern
12456 boolean_t
12457 exc_server (mach_msg_header_t *request_msg,
12458             mach_msg_header_t *reply_msg);
12459
12460 /*
12461  * The exception message
12462  */
12463 typedef struct {
12464         mach_msg_base_t msg;  /* common mach message header */
12465         char payload [1024];  /* opaque */
12466 } mach_exception_msg_t;
12467
12468 /* The exception port */
12469 static mach_port_t mach_exception_port = VM_MAP_NULL;
12470
12471 /*
12472  * Implicitly called by exc_server. Must be public.
12473  *
12474  * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/catch_exception_raise.html
12475  */
12476 kern_return_t
12477 catch_exception_raise (
12478         mach_port_t exception_port,
12479         mach_port_t thread,
12480         mach_port_t task,
12481         exception_type_t exception,
12482         exception_data_t code,
12483         mach_msg_type_number_t code_count)
12484 {
12485         /* consume the exception */
12486         return KERN_FAILURE;
12487 }
12488
12489 /*
12490  * Exception thread handler.
12491  */
12492 static
12493 void *
12494 mach_exception_thread (void *arg)
12495 {
12496         for (;;) {
12497                 mach_exception_msg_t request;
12498                 mach_exception_msg_t reply;
12499                 mach_msg_return_t result;
12500
12501                 /* receive from "mach_exception_port" */
12502                 result = mach_msg (&request.msg.header,
12503                                    MACH_RCV_MSG | MACH_RCV_LARGE,
12504                                    0,
12505                                    sizeof (request),
12506                                    mach_exception_port,
12507                                    MACH_MSG_TIMEOUT_NONE,
12508                                    MACH_PORT_NULL);
12509
12510                 g_assert (result == MACH_MSG_SUCCESS);
12511
12512                 /* dispatch to catch_exception_raise () */
12513                 exc_server (&request.msg.header, &reply.msg.header);
12514
12515                 /* send back to sender */
12516                 result = mach_msg (&reply.msg.header,
12517                                    MACH_SEND_MSG,
12518                                    reply.msg.header.msgh_size,
12519                                    0,
12520                                    MACH_PORT_NULL,
12521                                    MACH_MSG_TIMEOUT_NONE,
12522                                    MACH_PORT_NULL);
12523
12524                 g_assert (result == MACH_MSG_SUCCESS);
12525         }
12526         return NULL;
12527 }
12528
12529 static void
12530 macosx_register_exception_handler ()
12531 {
12532         mach_port_t task;
12533         pthread_attr_t attr;
12534         pthread_t thread;
12535
12536         if (mach_exception_port != VM_MAP_NULL)
12537                 return;
12538
12539         task = mach_task_self ();
12540
12541         /* create the "mach_exception_port" with send & receive rights */
12542         g_assert (mach_port_allocate (task, MACH_PORT_RIGHT_RECEIVE,
12543                                       &mach_exception_port) == KERN_SUCCESS);
12544         g_assert (mach_port_insert_right (task, mach_exception_port, mach_exception_port,
12545                                           MACH_MSG_TYPE_MAKE_SEND) == KERN_SUCCESS);
12546
12547         /* create the exception handler thread */
12548         g_assert (!pthread_attr_init (&attr));
12549         g_assert (!pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED));
12550         g_assert (!pthread_create (&thread, &attr, mach_exception_thread, NULL));
12551         pthread_attr_destroy (&attr);
12552
12553         /*
12554          * register "mach_exception_port" as a receiver for the
12555          * EXC_BAD_ACCESS exception
12556          *
12557          * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/task_set_exception_ports.html
12558          */
12559         g_assert (task_set_exception_ports (task, EXC_MASK_BAD_ACCESS,
12560                                             mach_exception_port,
12561                                             EXCEPTION_DEFAULT,
12562                                             MACHINE_THREAD_STATE) == KERN_SUCCESS);
12563 }
12564 #endif
12565
12566 #ifndef PLATFORM_WIN32
12567 static void
12568 add_signal_handler (int signo, gpointer handler)
12569 {
12570         struct sigaction sa;
12571
12572 #ifdef MONO_ARCH_USE_SIGACTION
12573         sa.sa_sigaction = handler;
12574         sigemptyset (&sa.sa_mask);
12575         sa.sa_flags = SA_SIGINFO;
12576 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
12577         if (signo == SIGSEGV)
12578                 sa.sa_flags |= SA_ONSTACK;
12579 #endif
12580 #else
12581         sa.sa_handler = handler;
12582         sigemptyset (&sa.sa_mask);
12583         sa.sa_flags = 0;
12584 #endif
12585         g_assert (sigaction (signo, &sa, NULL) != -1);
12586 }
12587
12588 static void
12589 remove_signal_handler (int signo)
12590 {
12591         struct sigaction sa;
12592
12593         sa.sa_handler = SIG_DFL;
12594         sigemptyset (&sa.sa_mask);
12595         sa.sa_flags = 0;
12596
12597         g_assert (sigaction (signo, &sa, NULL) != -1);
12598 }
12599 #endif
12600
12601 static void
12602 mono_runtime_install_handlers (void)
12603 {
12604 #ifdef PLATFORM_WIN32
12605         win32_seh_init();
12606         win32_seh_set_handler(SIGFPE, sigfpe_signal_handler);
12607         win32_seh_set_handler(SIGILL, sigill_signal_handler);
12608         win32_seh_set_handler(SIGSEGV, sigsegv_signal_handler);
12609         if (debug_options.handle_sigint)
12610                 win32_seh_set_handler(SIGINT, sigint_signal_handler);
12611
12612 #else /* !PLATFORM_WIN32 */
12613
12614
12615 #ifdef PLATFORM_MACOSX
12616         macosx_register_exception_handler ();
12617 #endif
12618
12619         if (debug_options.handle_sigint)
12620                 add_signal_handler (SIGINT, sigint_signal_handler);
12621
12622         add_signal_handler (SIGFPE, sigfpe_signal_handler);
12623         add_signal_handler (SIGQUIT, sigquit_signal_handler);
12624         add_signal_handler (SIGILL, sigill_signal_handler);
12625         add_signal_handler (SIGBUS, sigsegv_signal_handler);
12626         if (mono_jit_trace_calls != NULL)
12627                 add_signal_handler (SIGUSR2, sigusr2_signal_handler);
12628
12629         add_signal_handler (mono_thread_get_abort_signal (), sigusr1_signal_handler);
12630         signal (SIGPIPE, SIG_IGN);
12631
12632         add_signal_handler (SIGABRT, sigabrt_signal_handler);
12633
12634         /* catch SIGSEGV */
12635         add_signal_handler (SIGSEGV, sigsegv_signal_handler);
12636 #endif /* PLATFORM_WIN32 */
12637 }
12638
12639 static void
12640 mono_runtime_cleanup_handlers (void)
12641 {
12642 #ifdef PLATFORM_WIN32
12643         win32_seh_cleanup();
12644 #else
12645         if (debug_options.handle_sigint)
12646                 remove_signal_handler (SIGINT);
12647
12648         remove_signal_handler (SIGFPE);
12649         remove_signal_handler (SIGQUIT);
12650         remove_signal_handler (SIGILL);
12651         remove_signal_handler (SIGBUS);
12652         if (mono_jit_trace_calls != NULL)
12653                 remove_signal_handler (SIGUSR2);
12654
12655         remove_signal_handler (mono_thread_get_abort_signal ());
12656
12657         remove_signal_handler (SIGABRT);
12658
12659         remove_signal_handler (SIGSEGV);
12660 #endif /* PLATFORM_WIN32 */
12661 }
12662
12663
12664 #ifdef HAVE_LINUX_RTC_H
12665 #include <linux/rtc.h>
12666 #include <sys/ioctl.h>
12667 #include <fcntl.h>
12668 static int rtc_fd = -1;
12669
12670 static int
12671 enable_rtc_timer (gboolean enable)
12672 {
12673         int flags;
12674         flags = fcntl (rtc_fd, F_GETFL);
12675         if (flags < 0) {
12676                 perror ("getflags");
12677                 return 0;
12678         }
12679         if (enable)
12680                 flags |= FASYNC;
12681         else
12682                 flags &= ~FASYNC;
12683         if (fcntl (rtc_fd, F_SETFL, flags) == -1) {
12684                 perror ("setflags");
12685                 return 0;
12686         }
12687         return 1;
12688 }
12689 #endif
12690
12691 #ifdef PLATFORM_WIN32
12692 static HANDLE win32_main_thread;
12693 static MMRESULT win32_timer;
12694
12695 static void CALLBACK
12696 win32_time_proc (UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2)
12697 {
12698         CONTEXT context;
12699
12700         context.ContextFlags = CONTEXT_CONTROL;
12701         if (GetThreadContext (win32_main_thread, &context)) {
12702 #ifdef _WIN64
12703                 mono_profiler_stat_hit ((guchar *) context.Rip, &context);
12704 #else
12705                 mono_profiler_stat_hit ((guchar *) context.Eip, &context);
12706 #endif
12707         }
12708 }
12709 #endif
12710
12711 static void
12712 setup_stat_profiler (void)
12713 {
12714 #ifdef ITIMER_PROF
12715         struct itimerval itval;
12716         static int inited = 0;
12717 #ifdef HAVE_LINUX_RTC_H
12718         const char *rtc_freq;
12719         if (!inited && (rtc_freq = g_getenv ("MONO_RTC"))) {
12720                 int freq = 0;
12721                 inited = 1;
12722                 if (*rtc_freq)
12723                         freq = atoi (rtc_freq);
12724                 if (!freq)
12725                         freq = 1024;
12726                 rtc_fd = open ("/dev/rtc", O_RDONLY);
12727                 if (rtc_fd == -1) {
12728                         perror ("open /dev/rtc");
12729                         return;
12730                 }
12731                 add_signal_handler (SIGPROF, sigprof_signal_handler);
12732                 if (ioctl (rtc_fd, RTC_IRQP_SET, freq) == -1) {
12733                         perror ("set rtc freq");
12734                         return;
12735                 }
12736                 if (ioctl (rtc_fd, RTC_PIE_ON, 0) == -1) {
12737                         perror ("start rtc");
12738                         return;
12739                 }
12740                 if (fcntl (rtc_fd, F_SETSIG, SIGPROF) == -1) {
12741                         perror ("setsig");
12742                         return;
12743                 }
12744                 if (fcntl (rtc_fd, F_SETOWN, getpid ()) == -1) {
12745                         perror ("setown");
12746                         return;
12747                 }
12748                 enable_rtc_timer (TRUE);
12749                 return;
12750         }
12751         if (rtc_fd >= 0)
12752                 return;
12753 #endif
12754
12755         itval.it_interval.tv_usec = 999;
12756         itval.it_interval.tv_sec = 0;
12757         itval.it_value = itval.it_interval;
12758         setitimer (ITIMER_PROF, &itval, NULL);
12759         if (inited)
12760                 return;
12761         inited = 1;
12762         add_signal_handler (SIGPROF, sigprof_signal_handler);
12763 #elif defined (PLATFORM_WIN32)
12764         static int inited = 0;
12765         TIMECAPS timecaps;
12766
12767         if (inited)
12768                 return;
12769
12770         inited = 1;
12771         if (timeGetDevCaps (&timecaps, sizeof (timecaps)) != TIMERR_NOERROR)
12772                 return;
12773
12774         if ((win32_main_thread = OpenThread (READ_CONTROL | THREAD_GET_CONTEXT, FALSE, GetCurrentThreadId ())) == NULL)
12775                 return;
12776
12777         if (timeBeginPeriod (1) != TIMERR_NOERROR)
12778                 return;
12779
12780         if ((win32_timer = timeSetEvent (1, 0, win32_time_proc, 0, TIME_PERIODIC)) == 0) {
12781                 timeEndPeriod (1);
12782                 return;
12783         }
12784 #endif
12785 }
12786
12787 /* mono_jit_create_remoting_trampoline:
12788  * @method: pointer to the method info
12789  *
12790  * Creates a trampoline which calls the remoting functions. This
12791  * is used in the vtable of transparent proxies.
12792  * 
12793  * Returns: a pointer to the newly created code 
12794  */
12795 static gpointer
12796 mono_jit_create_remoting_trampoline (MonoMethod *method, MonoRemotingTarget target)
12797 {
12798         MonoMethod *nm;
12799         guint8 *addr = NULL;
12800
12801         if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) || 
12802             (mono_method_signature (method)->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class))) {
12803                 nm = mono_marshal_get_remoting_invoke_for_target (method, target);
12804                 addr = mono_compile_method (nm);
12805         } else {
12806                 addr = mono_compile_method (method);
12807         }
12808         return mono_get_addr_from_ftnptr (addr);
12809 }
12810
12811 #ifdef MONO_ARCH_HAVE_IMT
12812 static gpointer
12813 mini_get_imt_trampoline (void)
12814 {
12815         static gpointer tramp = NULL;
12816         if (!tramp)
12817                 tramp =  mono_arch_create_specific_trampoline (MONO_FAKE_IMT_METHOD, MONO_TRAMPOLINE_GENERIC, mono_get_root_domain (), NULL);
12818         return tramp;
12819 }
12820 #endif
12821
12822 #ifdef MONO_ARCH_COMMON_VTABLE_TRAMPOLINE
12823 gpointer
12824 mini_get_vtable_trampoline (void)
12825 {
12826         static gpointer tramp = NULL;
12827         if (!tramp)
12828                 tramp =  mono_arch_create_specific_trampoline (MONO_FAKE_VTABLE_METHOD, MONO_TRAMPOLINE_GENERIC, mono_get_root_domain (), NULL);
12829         return tramp;
12830 }
12831 #endif
12832
12833 static void
12834 mini_parse_debug_options (void)
12835 {
12836         char *options = getenv ("MONO_DEBUG");
12837         gchar **args, **ptr;
12838         
12839         if (!options)
12840                 return;
12841
12842         args = g_strsplit (options, ",", -1);
12843
12844         for (ptr = args; ptr && *ptr; ptr++) {
12845                 const char *arg = *ptr;
12846
12847                 if (!strcmp (arg, "handle-sigint"))
12848                         debug_options.handle_sigint = TRUE;
12849                 else if (!strcmp (arg, "keep-delegates"))
12850                         debug_options.keep_delegates = TRUE;
12851                 else if (!strcmp (arg, "collect-pagefault-stats"))
12852                         debug_options.collect_pagefault_stats = TRUE;
12853                 else if (!strcmp (arg, "break-on-unverified"))
12854                         debug_options.break_on_unverified = TRUE;
12855                 else {
12856                         fprintf (stderr, "Invalid option for the MONO_DEBUG env variable: %s\n", arg);
12857                         fprintf (stderr, "Available options: 'handle-sigint', 'keep-delegates', 'collect-pagefault-stats', 'break-on-unverified'\n");
12858                         exit (1);
12859                 }
12860         }
12861 }
12862
12863 MonoDomain *
12864 mini_init (const char *filename, const char *runtime_version)
12865 {
12866         MonoDomain *domain;
12867
12868 #ifdef __linux__
12869         if (access ("/proc/self/maps", F_OK) != 0) {
12870                 g_print ("Mono requires /proc to be mounted.\n");
12871                 exit (1);
12872         }
12873 #endif
12874
12875         /* Happens when using the embedding interface */
12876         if (!default_opt_set)
12877                 default_opt = mono_parse_default_optimizations (NULL);
12878
12879         InitializeCriticalSection (&jit_mutex);
12880
12881         if (!global_codeman)
12882                 global_codeman = mono_code_manager_new ();
12883         jit_icall_name_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
12884
12885         mono_arch_cpu_init ();
12886
12887         mono_arch_init ();
12888
12889         mono_init_trampolines ();
12890
12891         mono_init_exceptions ();
12892
12893         if (!g_thread_supported ())
12894                 g_thread_init (NULL);
12895
12896         if (getenv ("MONO_DEBUG") != NULL)
12897                 mini_parse_debug_options ();
12898
12899         mono_gc_base_init ();
12900
12901         mono_jit_tls_id = TlsAlloc ();
12902         setup_jit_tls_data ((gpointer)-1, mono_thread_abort);
12903
12904         mono_burg_init ();
12905
12906         if (default_opt & MONO_OPT_AOT)
12907                 mono_aot_init ();
12908
12909         mono_runtime_install_handlers ();
12910         mono_threads_install_cleanup (mini_thread_cleanup);
12911
12912 #ifdef MONO_ARCH_HAVE_NOTIFY_PENDING_EXC
12913         // This is experimental code so provide an env var to switch it off
12914         if (getenv ("MONO_DISABLE_PENDING_EXCEPTIONS")) {
12915                 printf ("MONO_DISABLE_PENDING_EXCEPTIONS env var set.\n");
12916         } else {
12917                 check_for_pending_exc = FALSE;
12918                 mono_threads_install_notify_pending_exc (mono_arch_notify_pending_exc);
12919         }
12920 #endif
12921
12922 #define JIT_TRAMPOLINES_WORK
12923 #ifdef JIT_TRAMPOLINES_WORK
12924         mono_install_compile_method (mono_jit_compile_method);
12925         mono_install_free_method (mono_jit_free_method);
12926         mono_install_trampoline (mono_create_jit_trampoline);
12927         mono_install_jump_trampoline (mono_create_jump_trampoline);
12928         mono_install_remoting_trampoline (mono_jit_create_remoting_trampoline);
12929         mono_install_delegate_trampoline (mono_create_delegate_trampoline);
12930 #endif
12931 #define JIT_INVOKE_WORKS
12932 #ifdef JIT_INVOKE_WORKS
12933         mono_install_runtime_invoke (mono_jit_runtime_invoke);
12934         mono_install_handler (mono_arch_get_throw_exception ());
12935 #endif
12936         mono_install_stack_walk (mono_jit_walk_stack);
12937         mono_install_init_vtable (mono_aot_init_vtable);
12938         mono_install_get_cached_class_info (mono_aot_get_cached_class_info);
12939         mono_install_get_class_from_name (mono_aot_get_class_from_name);
12940         mono_install_jit_info_find_in_aot (mono_aot_find_jit_info);
12941
12942         if (debug_options.collect_pagefault_stats) {
12943                 mono_raw_buffer_set_make_unreadable (TRUE);
12944                 mono_aot_set_make_unreadable (TRUE);
12945         }
12946
12947         if (runtime_version)
12948                 domain = mono_init_version (filename, runtime_version);
12949         else
12950                 domain = mono_init_from_assembly (filename, filename);
12951 #ifdef MONO_ARCH_HAVE_IMT
12952         mono_install_imt_thunk_builder (mono_arch_build_imt_thunk);
12953         mono_install_imt_trampoline (mini_get_imt_trampoline ());
12954 #if MONO_ARCH_COMMON_VTABLE_TRAMPOLINE
12955         mono_install_vtable_trampoline (mini_get_vtable_trampoline ());
12956 #endif
12957 #endif
12958         mono_icall_init ();
12959
12960         mono_add_internal_call ("System.Diagnostics.StackFrame::get_frame_info", 
12961                                 ves_icall_get_frame_info);
12962         mono_add_internal_call ("System.Diagnostics.StackTrace::get_trace", 
12963                                 ves_icall_get_trace);
12964         mono_add_internal_call ("System.Exception::get_trace", 
12965                                 ves_icall_System_Exception_get_trace);
12966         mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityFrame",
12967                                 ves_icall_System_Security_SecurityFrame_GetSecurityFrame);
12968         mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityStack",
12969                                 ves_icall_System_Security_SecurityFrame_GetSecurityStack);
12970         mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers", 
12971                                 mono_runtime_install_handlers);
12972
12973
12974         create_helper_signature ();
12975
12976 #define JIT_CALLS_WORK
12977 #ifdef JIT_CALLS_WORK
12978         /* Needs to be called here since register_jit_icall depends on it */
12979         mono_marshal_init ();
12980
12981         mono_arch_register_lowlevel_calls ();
12982         register_icall (mono_profiler_method_enter, "mono_profiler_method_enter", NULL, TRUE);
12983         register_icall (mono_profiler_method_leave, "mono_profiler_method_leave", NULL, TRUE);
12984         register_icall (mono_trace_enter_method, "mono_trace_enter_method", NULL, TRUE);
12985         register_icall (mono_trace_leave_method, "mono_trace_leave_method", NULL, TRUE);
12986         register_icall (mono_get_lmf_addr, "mono_get_lmf_addr", "ptr", TRUE);
12987         register_icall (mono_jit_thread_attach, "mono_jit_thread_attach", "void", TRUE);
12988         register_icall (mono_domain_get, "mono_domain_get", "ptr", TRUE);
12989
12990         register_icall (mono_arch_get_throw_exception (), "mono_arch_throw_exception", "void object", TRUE);
12991         register_icall (mono_arch_get_rethrow_exception (), "mono_arch_rethrow_exception", "void object", TRUE);
12992         register_icall (mono_arch_get_throw_exception_by_name (), "mono_arch_throw_exception_by_name", "void ptr", TRUE); 
12993 #if MONO_ARCH_HAVE_THROW_CORLIB_EXCEPTION
12994         register_icall (mono_arch_get_throw_corlib_exception (), "mono_arch_throw_corlib_exception", 
12995                                  "void ptr", TRUE);
12996 #endif
12997         register_icall (mono_thread_get_undeniable_exception, "mono_thread_get_undeniable_exception", "object", FALSE);
12998         register_icall (mono_thread_interruption_checkpoint, "mono_thread_interruption_checkpoint", "void", FALSE);
12999         register_icall (mono_thread_force_interruption_checkpoint, "mono_thread_force_interruption_checkpoint", "void", FALSE);
13000         register_icall (mono_load_remote_field_new, "mono_load_remote_field_new", "object object ptr ptr", FALSE);
13001         register_icall (mono_store_remote_field_new, "mono_store_remote_field_new", "void object ptr ptr object", FALSE);
13002
13003         /* 
13004          * NOTE, NOTE, NOTE, NOTE:
13005          * when adding emulation for some opcodes, remember to also add a dummy
13006          * rule to the burg files, because we need the arity information to be correct.
13007          */
13008 #ifndef MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS
13009         mono_register_opcode_emulation (OP_LMUL, "__emul_lmul", "long long long", mono_llmult, TRUE);
13010         mono_register_opcode_emulation (OP_LDIV, "__emul_ldiv", "long long long", mono_lldiv, FALSE);
13011         mono_register_opcode_emulation (OP_LDIV_UN, "__emul_ldiv_un", "long long long", mono_lldiv_un, FALSE);
13012         mono_register_opcode_emulation (OP_LREM, "__emul_lrem", "long long long", mono_llrem, FALSE);
13013         mono_register_opcode_emulation (OP_LREM_UN, "__emul_lrem_un", "long long long", mono_llrem_un, FALSE);
13014         mono_register_opcode_emulation (OP_LMUL_OVF_UN, "__emul_lmul_ovf_un", "long long long", mono_llmult_ovf_un, FALSE);
13015         mono_register_opcode_emulation (OP_LMUL_OVF, "__emul_lmul_ovf", "long long long", mono_llmult_ovf, FALSE);
13016 #endif
13017
13018 #ifndef MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS
13019         mono_register_opcode_emulation (OP_LSHL, "__emul_lshl", "long long int32", mono_lshl, TRUE);
13020         mono_register_opcode_emulation (OP_LSHR, "__emul_lshr", "long long int32", mono_lshr, TRUE);
13021         mono_register_opcode_emulation (OP_LSHR_UN, "__emul_lshr_un", "long long int32", mono_lshr_un, TRUE);
13022 #endif
13023
13024 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
13025         mono_register_opcode_emulation (CEE_DIV, "__emul_idiv", "int32 int32 int32", mono_idiv, FALSE);
13026         mono_register_opcode_emulation (CEE_DIV_UN, "__emul_idiv_un", "int32 int32 int32", mono_idiv_un, FALSE);
13027         mono_register_opcode_emulation (CEE_REM, "__emul_irem", "int32 int32 int32", mono_irem, FALSE);
13028         mono_register_opcode_emulation (CEE_REM_UN, "__emul_irem_un", "int32 int32 int32", mono_irem_un, FALSE);
13029 #endif
13030
13031 #ifdef MONO_ARCH_EMULATE_MUL_DIV
13032         mono_register_opcode_emulation (CEE_MUL_OVF, "__emul_imul_ovf", "int32 int32 int32", mono_imul_ovf, FALSE);
13033         mono_register_opcode_emulation (CEE_MUL_OVF_UN, "__emul_imul_ovf_un", "int32 int32 int32", mono_imul_ovf_un, FALSE);
13034         mono_register_opcode_emulation (CEE_MUL, "__emul_imul", "int32 int32 int32", mono_imul, TRUE);
13035 #endif
13036 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_SOFT_FLOAT)
13037         mono_register_opcode_emulation (OP_FDIV, "__emul_fdiv", "double double double", mono_fdiv, FALSE);
13038 #endif
13039
13040         mono_register_opcode_emulation (OP_FCONV_TO_U8, "__emul_fconv_to_u8", "ulong double", mono_fconv_u8, FALSE);
13041         mono_register_opcode_emulation (OP_FCONV_TO_U4, "__emul_fconv_to_u4", "uint32 double", mono_fconv_u4, FALSE);
13042         mono_register_opcode_emulation (OP_FCONV_TO_OVF_I8, "__emul_fconv_to_ovf_i8", "long double", mono_fconv_ovf_i8, FALSE);
13043         mono_register_opcode_emulation (OP_FCONV_TO_OVF_U8, "__emul_fconv_to_ovf_u8", "ulong double", mono_fconv_ovf_u8, FALSE);
13044
13045 #ifdef MONO_ARCH_EMULATE_FCONV_TO_I8
13046         mono_register_opcode_emulation (OP_FCONV_TO_I8, "__emul_fconv_to_i8", "long double", mono_fconv_i8, FALSE);
13047 #endif
13048 #ifdef MONO_ARCH_EMULATE_CONV_R8_UN
13049         mono_register_opcode_emulation (CEE_CONV_R_UN, "__emul_conv_r_un", "double int32", mono_conv_to_r8_un, FALSE);
13050 #endif
13051 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8
13052         mono_register_opcode_emulation (OP_LCONV_TO_R8, "__emul_lconv_to_r8", "double long", mono_lconv_to_r8, FALSE);
13053 #endif
13054 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R4
13055         mono_register_opcode_emulation (OP_LCONV_TO_R4, "__emul_lconv_to_r4", "float long", mono_lconv_to_r4, FALSE);
13056 #endif
13057 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8_UN
13058         mono_register_opcode_emulation (OP_LCONV_TO_R_UN, "__emul_lconv_to_r8_un", "double long", mono_lconv_to_r8_un, FALSE);
13059 #endif
13060 #ifdef MONO_ARCH_EMULATE_FREM
13061         mono_register_opcode_emulation (OP_FREM, "__emul_frem", "double double double", fmod, FALSE);
13062 #endif
13063
13064 #ifdef MONO_ARCH_SOFT_FLOAT
13065         mono_register_opcode_emulation (OP_FSUB, "__emul_fsub", "double double double", mono_fsub, FALSE);
13066         mono_register_opcode_emulation (OP_FADD, "__emul_fadd", "double double double", mono_fadd, FALSE);
13067         mono_register_opcode_emulation (OP_FMUL, "__emul_fmul", "double double double", mono_fmul, FALSE);
13068         mono_register_opcode_emulation (OP_FNEG, "__emul_fneg", "double double", mono_fneg, FALSE);
13069         mono_register_opcode_emulation (CEE_CONV_R8, "__emul_conv_r8", "double int32", mono_conv_to_r8, FALSE);
13070         mono_register_opcode_emulation (CEE_CONV_R4, "__emul_conv_r4", "double int32", mono_conv_to_r4, FALSE);
13071         mono_register_opcode_emulation (OP_FCONV_TO_R4, "__emul_fconv_to_r4", "double double", mono_fconv_r4, FALSE);
13072         mono_register_opcode_emulation (OP_FCONV_TO_I1, "__emul_fconv_to_i1", "int8 double", mono_fconv_i1, FALSE);
13073         mono_register_opcode_emulation (OP_FCONV_TO_I2, "__emul_fconv_to_i2", "int16 double", mono_fconv_i2, FALSE);
13074         mono_register_opcode_emulation (OP_FCONV_TO_I4, "__emul_fconv_to_i4", "int32 double", mono_fconv_i4, FALSE);
13075         mono_register_opcode_emulation (OP_FCONV_TO_U1, "__emul_fconv_to_u1", "uint8 double", mono_fconv_u1, FALSE);
13076         mono_register_opcode_emulation (OP_FCONV_TO_U2, "__emul_fconv_to_u2", "uint16 double", mono_fconv_u2, FALSE);
13077
13078         mono_register_opcode_emulation (OP_FBEQ, "__emul_fcmp_eq", "uint32 double double", mono_fcmp_eq, FALSE);
13079         mono_register_opcode_emulation (OP_FBLT, "__emul_fcmp_lt", "uint32 double double", mono_fcmp_lt, FALSE);
13080         mono_register_opcode_emulation (OP_FBGT, "__emul_fcmp_gt", "uint32 double double", mono_fcmp_gt, FALSE);
13081         mono_register_opcode_emulation (OP_FBLE, "__emul_fcmp_le", "uint32 double double", mono_fcmp_le, FALSE);
13082         mono_register_opcode_emulation (OP_FBGE, "__emul_fcmp_ge", "uint32 double double", mono_fcmp_ge, FALSE);
13083         mono_register_opcode_emulation (OP_FBNE_UN, "__emul_fcmp_ne_un", "uint32 double double", mono_fcmp_ne_un, FALSE);
13084         mono_register_opcode_emulation (OP_FBLT_UN, "__emul_fcmp_lt_un", "uint32 double double", mono_fcmp_lt_un, FALSE);
13085         mono_register_opcode_emulation (OP_FBGT_UN, "__emul_fcmp_gt_un", "uint32 double double", mono_fcmp_gt_un, FALSE);
13086         mono_register_opcode_emulation (OP_FBLE_UN, "__emul_fcmp_le_un", "uint32 double double", mono_fcmp_le_un, FALSE);
13087         mono_register_opcode_emulation (OP_FBGE_UN, "__emul_fcmp_ge_un", "uint32 double double", mono_fcmp_ge_un, FALSE);
13088
13089         mono_register_opcode_emulation (OP_FCEQ, "__emul_fcmp_ceq", "uint32 double double", mono_fceq, FALSE);
13090         mono_register_opcode_emulation (OP_FCGT, "__emul_fcmp_cgt", "uint32 double double", mono_fcgt, FALSE);
13091         mono_register_opcode_emulation (OP_FCGT_UN, "__emul_fcmp_cgt_un", "uint32 double double", mono_fcgt_un, FALSE);
13092         mono_register_opcode_emulation (OP_FCLT, "__emul_fcmp_clt", "uint32 double double", mono_fclt, FALSE);
13093         mono_register_opcode_emulation (OP_FCLT_UN, "__emul_fcmp_clt_un", "uint32 double double", mono_fclt_un, FALSE);
13094
13095         register_icall (mono_fload_r4, "mono_fload_r4", "double ptr", FALSE);
13096         register_icall (mono_fstore_r4, "mono_fstore_r4", "void double ptr", FALSE);
13097         register_icall (mono_fload_r4_arg, "mono_fload_r4_arg", "uint32 double", FALSE);
13098 #endif
13099
13100 #if SIZEOF_VOID_P == 4
13101         mono_register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", "uint32 double", mono_fconv_u4, TRUE);
13102 #endif
13103
13104         /* other jit icalls */
13105         register_icall (mono_delegate_ctor, "mono_delegate_ctor", "void object object ptr", FALSE);
13106         register_icall (mono_class_static_field_address , "mono_class_static_field_address", 
13107                                  "ptr ptr ptr", FALSE);
13108         register_icall (mono_ldtoken_wrapper, "mono_ldtoken_wrapper", "ptr ptr ptr ptr", FALSE);
13109         register_icall (mono_get_special_static_data, "mono_get_special_static_data", "ptr int", FALSE);
13110         register_icall (mono_ldstr, "mono_ldstr", "object ptr ptr int32", FALSE);
13111         register_icall (mono_helper_stelem_ref_check, "helper_stelem_ref_check", "void object object", FALSE);
13112         register_icall (mono_object_new, "mono_object_new", "object ptr ptr", FALSE);
13113         register_icall (mono_object_new_specific, "mono_object_new_specific", "object ptr", FALSE);
13114         register_icall (mono_array_new, "mono_array_new", "object ptr ptr int32", FALSE);
13115         register_icall (mono_array_new_specific, "mono_array_new_specific", "object ptr int32", FALSE);
13116         register_icall (mono_runtime_class_init, "mono_runtime_class_init", "void ptr", FALSE);
13117         register_icall (mono_ldftn, "mono_ldftn", "ptr ptr", FALSE);
13118         register_icall (mono_ldftn_nosync, "mono_ldftn_nosync", "ptr ptr", FALSE);
13119         register_icall (mono_ldvirtfn, "mono_ldvirtfn", "ptr object ptr", FALSE);
13120         register_icall (mono_helper_compile_generic_method, "compile_generic_method", "ptr object ptr ptr ptr", FALSE);
13121         register_icall (mono_helper_ldstr, "helper_ldstr", "object ptr int", FALSE);
13122         register_icall (mono_helper_ldstr_mscorlib, "helper_ldstr_mscorlib", "object int", FALSE);
13123         register_icall (mono_helper_newobj_mscorlib, "helper_newobj_mscorlib", "object int", FALSE);
13124         register_icall (mono_value_copy, "mono_value_copy", "void ptr ptr ptr", FALSE);
13125         register_icall (mono_helper_get_rgctx_other_ptr, "get_rgctx_other_ptr", "ptr ptr ptr int32 int32", FALSE);
13126         register_icall (mono_break, "mono_break", NULL, TRUE);
13127 #endif
13128
13129 #define JIT_RUNTIME_WORKS
13130 #ifdef JIT_RUNTIME_WORKS
13131         mono_install_runtime_cleanup ((MonoDomainFunc)mini_cleanup);
13132         mono_runtime_init (domain, mono_thread_start_cb, mono_thread_attach_cb);
13133 #endif
13134
13135         mono_generic_sharing_init ();
13136
13137         mono_thread_attach (domain);
13138         return domain;
13139 }
13140
13141 MonoJitStats mono_jit_stats = {0};
13142
13143 static void 
13144 print_jit_stats (void)
13145 {
13146         if (mono_jit_stats.enabled) {
13147                 g_print ("Mono Jit statistics\n");
13148                 g_print ("Compiled methods:       %ld\n", mono_jit_stats.methods_compiled);
13149                 g_print ("Methods from AOT:       %ld\n", mono_jit_stats.methods_aot);
13150                 g_print ("Methods cache lookup:   %ld\n", mono_jit_stats.methods_lookups);
13151                 g_print ("Method trampolines:     %ld\n", mono_jit_stats.method_trampolines);
13152                 g_print ("Basic blocks:           %ld\n", mono_jit_stats.basic_blocks);
13153                 g_print ("Max basic blocks:       %ld\n", mono_jit_stats.max_basic_blocks);
13154                 g_print ("Allocated vars:         %ld\n", mono_jit_stats.allocate_var);
13155                 g_print ("Analyze stack repeat:   %ld\n", mono_jit_stats.analyze_stack_repeat);
13156                 g_print ("Compiled CIL code size: %ld\n", mono_jit_stats.cil_code_size);
13157                 g_print ("Native code size:       %ld\n", mono_jit_stats.native_code_size);
13158                 g_print ("Max code size ratio:    %.2f (%s::%s)\n", mono_jit_stats.max_code_size_ratio/100.0,
13159                                 mono_jit_stats.max_ratio_method->klass->name, mono_jit_stats.max_ratio_method->name);
13160                 g_print ("Biggest method:         %ld (%s::%s)\n", mono_jit_stats.biggest_method_size,
13161                                 mono_jit_stats.biggest_method->klass->name, mono_jit_stats.biggest_method->name);
13162                 g_print ("Code reallocs:          %ld\n", mono_jit_stats.code_reallocs);
13163                 g_print ("Allocated code size:    %ld\n", mono_jit_stats.allocated_code_size);
13164                 g_print ("Inlineable methods:     %ld\n", mono_jit_stats.inlineable_methods);
13165                 g_print ("Inlined methods:        %ld\n", mono_jit_stats.inlined_methods);
13166                 g_print ("Locals stack size:      %ld\n", mono_jit_stats.locals_stack_size);
13167
13168                 g_print ("\nCreated object count:   %ld\n", mono_stats.new_object_count);
13169                 g_print ("Delegates created:      %ld\n", mono_stats.delegate_creations);
13170                 g_print ("Initialized classes:    %ld\n", mono_stats.initialized_class_count);
13171                 g_print ("Used classes:           %ld\n", mono_stats.used_class_count);
13172                 g_print ("Generic vtables:        %ld\n", mono_stats.generic_vtable_count);
13173                 g_print ("Methods:                %ld\n", mono_stats.method_count);
13174                 g_print ("Static data size:       %ld\n", mono_stats.class_static_data_size);
13175                 g_print ("VTable data size:       %ld\n", mono_stats.class_vtable_size);
13176                 g_print ("Mscorlib mempool size:  %d\n", mono_mempool_get_allocated (mono_defaults.corlib->mempool));
13177
13178                 g_print ("\nGeneric instances:      %ld\n", mono_stats.generic_instance_count);
13179                 g_print ("Initialized classes:    %ld\n", mono_stats.generic_class_count);
13180                 g_print ("Inflated methods:       %ld / %ld\n", mono_stats.inflated_method_count_2,
13181                          mono_stats.inflated_method_count);
13182                 g_print ("Inflated types:         %ld\n", mono_stats.inflated_type_count);
13183                 g_print ("Generics metadata size: %ld\n", mono_stats.generics_metadata_size);
13184                 g_print ("Generics virtual invokes: %ld\n", mono_jit_stats.generic_virtual_invocations);
13185
13186                 g_print ("Sharable generic methods: %ld\n", mono_stats.generics_sharable_methods);
13187                 g_print ("Unsharable generic methods: %ld\n", mono_stats.generics_unsharable_methods);
13188                 g_print ("Shared generic methods: %ld\n", mono_stats.generics_shared_methods);
13189
13190                 g_print ("Dynamic code allocs:    %ld\n", mono_stats.dynamic_code_alloc_count);
13191                 g_print ("Dynamic code bytes:     %ld\n", mono_stats.dynamic_code_bytes_count);
13192                 g_print ("Dynamic code frees:     %ld\n", mono_stats.dynamic_code_frees_count);
13193
13194                 g_print ("IMT tables size:        %ld\n", mono_stats.imt_tables_size);
13195                 g_print ("IMT number of tables:   %ld\n", mono_stats.imt_number_of_tables);
13196                 g_print ("IMT number of methods:  %ld\n", mono_stats.imt_number_of_methods);
13197                 g_print ("IMT used slots:         %ld\n", mono_stats.imt_used_slots);
13198                 g_print ("IMT colliding slots:    %ld\n", mono_stats.imt_slots_with_collisions);
13199                 g_print ("IMT max collisions:     %ld\n", mono_stats.imt_max_collisions_in_slot);
13200                 g_print ("IMT methods at max col: %ld\n", mono_stats.imt_method_count_when_max_collisions);
13201                 g_print ("IMT thunks size:        %ld\n", mono_stats.imt_thunks_size);
13202
13203                 g_print ("JIT info table inserts: %ld\n", mono_stats.jit_info_table_insert_count);
13204                 g_print ("JIT info table removes: %ld\n", mono_stats.jit_info_table_remove_count);
13205                 g_print ("JIT info table lookups: %ld\n", mono_stats.jit_info_table_lookup_count);
13206
13207                 g_print ("Hazardous pointers:     %ld\n", mono_stats.hazardous_pointer_count);
13208 #ifdef HAVE_SGEN_GC
13209                 g_print ("Minor GC collections:   %ld\n", mono_stats.minor_gc_count);
13210                 g_print ("Major GC collections:   %ld\n", mono_stats.major_gc_count);
13211                 g_print ("Minor GC time in msecs: %lf\n", (double)mono_stats.minor_gc_time_usecs / 1000.0);
13212                 g_print ("Major GC time in msecs: %lf\n", (double)mono_stats.major_gc_time_usecs / 1000.0);
13213 #endif
13214                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
13215                         g_print ("\nDecl security check   : %ld\n", mono_jit_stats.cas_declsec_check);
13216                         g_print ("LinkDemand (user)     : %ld\n", mono_jit_stats.cas_linkdemand);
13217                         g_print ("LinkDemand (icall)    : %ld\n", mono_jit_stats.cas_linkdemand_icall);
13218                         g_print ("LinkDemand (pinvoke)  : %ld\n", mono_jit_stats.cas_linkdemand_pinvoke);
13219                         g_print ("LinkDemand (aptc)     : %ld\n", mono_jit_stats.cas_linkdemand_aptc);
13220                         g_print ("Demand (code gen)     : %ld\n", mono_jit_stats.cas_demand_generation);
13221                 }
13222                 if (debug_options.collect_pagefault_stats) {
13223                         g_print ("Metadata pagefaults   : %d\n", mono_raw_buffer_get_n_pagefaults ());
13224                         g_print ("AOT pagefaults        : %d\n", mono_aot_get_n_pagefaults ());
13225                 }
13226         }
13227 }
13228
13229 void
13230 mini_cleanup (MonoDomain *domain)
13231 {
13232 #ifdef HAVE_LINUX_RTC_H
13233         if (rtc_fd >= 0)
13234                 enable_rtc_timer (FALSE);
13235 #endif
13236
13237         /* 
13238          * mono_runtime_cleanup() and mono_domain_finalize () need to
13239          * be called early since they need the execution engine still
13240          * fully working (mono_domain_finalize may invoke managed finalizers
13241          * and mono_runtime_cleanup will wait for other threads to finish).
13242          */
13243         mono_domain_finalize (domain, 2000);
13244
13245         /* This accesses metadata so needs to be called before runtime shutdown */
13246         print_jit_stats ();
13247
13248         mono_runtime_cleanup (domain);
13249
13250         mono_profiler_shutdown ();
13251
13252         mono_icall_cleanup ();
13253
13254         mono_runtime_cleanup_handlers ();
13255
13256         mono_domain_free (domain, TRUE);
13257
13258         mono_debugger_cleanup ();
13259
13260         mono_code_manager_destroy (global_codeman);
13261         g_hash_table_destroy (jit_icall_name_hash);
13262         if (class_init_hash_addr)
13263                 g_hash_table_destroy (class_init_hash_addr);
13264         if (delegate_trampoline_hash_addr)
13265                 g_hash_table_destroy (delegate_trampoline_hash_addr);
13266         g_free (emul_opcode_map);
13267
13268         mono_arch_cleanup ();
13269
13270         mono_cleanup ();
13271
13272         mono_trace_cleanup ();
13273
13274         mono_counters_dump (-1, stdout);
13275
13276         if (mono_inject_async_exc_method)
13277                 mono_method_desc_free (mono_inject_async_exc_method);
13278
13279         TlsFree(mono_jit_tls_id);
13280
13281         DeleteCriticalSection (&jit_mutex);
13282
13283         DeleteCriticalSection (&mono_delegate_section);
13284 }
13285
13286 void
13287 mono_set_defaults (int verbose_level, guint32 opts)
13288 {
13289         mini_verbose = verbose_level;
13290         default_opt = opts;
13291         default_opt_set = TRUE;
13292 }
13293
13294 static void
13295 mono_precompile_assembly (MonoAssembly *ass, void *user_data)
13296 {
13297         GHashTable *assemblies = (GHashTable*)user_data;
13298         MonoImage *image = mono_assembly_get_image (ass);
13299         MonoMethod *method, *invoke;
13300         int i, count = 0;
13301
13302         if (g_hash_table_lookup (assemblies, ass))
13303                 return;
13304
13305         g_hash_table_insert (assemblies, ass, ass);
13306
13307         if (mini_verbose > 0)
13308                 printf ("PRECOMPILE: %s.\n", mono_image_get_filename (image));
13309
13310         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
13311                 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
13312                 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
13313                         continue;
13314
13315                 count++;
13316                 if (mini_verbose > 1) {
13317                         char * desc = mono_method_full_name (method, TRUE);
13318                         g_print ("Compiling %d %s\n", count, desc);
13319                         g_free (desc);
13320                 }
13321                 mono_compile_method (method);
13322                 if (strcmp (method->name, "Finalize") == 0) {
13323                         invoke = mono_marshal_get_runtime_invoke (method);
13324                         mono_compile_method (invoke);
13325                 }
13326                 if (method->klass->marshalbyref && mono_method_signature (method)->hasthis) {
13327                         invoke = mono_marshal_get_remoting_invoke_with_check (method);
13328                         mono_compile_method (invoke);
13329                 }
13330         }
13331
13332         /* Load and precompile referenced assemblies as well */
13333         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_ASSEMBLYREF); ++i) {
13334                 mono_assembly_load_reference (image, i);
13335                 if (image->references [i])
13336                         mono_precompile_assembly (image->references [i], assemblies);
13337         }
13338 }
13339
13340 void mono_precompile_assemblies ()
13341 {
13342         GHashTable *assemblies = g_hash_table_new (NULL, NULL);
13343
13344         mono_assembly_foreach ((GFunc)mono_precompile_assembly, assemblies);
13345
13346         g_hash_table_destroy (assemblies);
13347 }