2008-03-23 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mono / mini / mini.c
1 /*
2  * mini.c: The new Mono code generator.
3  *
4  * Author:
5  *   Paolo Molaro (lupus@ximian.com)
6  *   Dietmar Maurer (dietmar@ximian.com)
7  *
8  * (C) 2002 Ximian, Inc.
9  */
10
11 #include <config.h>
12 #include <signal.h>
13 #ifdef HAVE_UNISTD_H
14 #include <unistd.h>
15 #endif
16 #include <math.h>
17 #ifdef HAVE_SYS_TIME_H
18 #include <sys/time.h>
19 #endif
20
21 #ifdef PLATFORM_MACOSX
22 #include <mach/mach.h>
23 #include <mach/mach_error.h>
24 #include <mach/exception.h>
25 #include <mach/task.h>
26 #include <pthread.h>
27 #endif
28
29 #ifdef HAVE_VALGRIND_MEMCHECK_H
30 #include <valgrind/memcheck.h>
31 #endif
32
33 #include <mono/metadata/assembly.h>
34 #include <mono/metadata/loader.h>
35 #include <mono/metadata/tabledefs.h>
36 #include <mono/metadata/class.h>
37 #include <mono/metadata/object.h>
38 #include <mono/metadata/exception.h>
39 #include <mono/metadata/opcodes.h>
40 #include <mono/metadata/mono-endian.h>
41 #include <mono/metadata/tokentype.h>
42 #include <mono/metadata/tabledefs.h>
43 #include <mono/metadata/threads.h>
44 #include <mono/metadata/marshal.h>
45 #include <mono/metadata/socket-io.h>
46 #include <mono/metadata/appdomain.h>
47 #include <mono/metadata/debug-helpers.h>
48 #include <mono/io-layer/io-layer.h>
49 #include "mono/metadata/profiler.h"
50 #include <mono/metadata/profiler-private.h>
51 #include <mono/metadata/mono-config.h>
52 #include <mono/metadata/environment.h>
53 #include <mono/metadata/mono-debug.h>
54 #include <mono/metadata/monitor.h>
55 #include <mono/metadata/gc-internal.h>
56 #include <mono/metadata/security-manager.h>
57 #include <mono/metadata/threads-types.h>
58 #include <mono/metadata/rawbuffer.h>
59 #include <mono/metadata/security-core-clr.h>
60 #include <mono/metadata/verify.h>
61 #include <mono/utils/mono-math.h>
62 #include <mono/utils/mono-compiler.h>
63 #include <mono/utils/mono-counters.h>
64 #include <mono/utils/mono-logger.h>
65 #include <mono/utils/mono-mmap.h>
66
67 #include "mini.h"
68 #include <string.h>
69 #include <ctype.h>
70 #include "inssel.h"
71 #include "trace.h"
72
73 #include "jit-icalls.h"
74
75 #include "aliasing.h"
76
77 #include "debug-mini.h"
78
79 #define BRANCH_COST 100
80 #define INLINE_LENGTH_LIMIT 20
81 #define INLINE_FAILURE do {\
82                 if ((cfg->method != method) && (method->wrapper_type == MONO_WRAPPER_NONE))\
83                         goto inline_failure;\
84         } while (0)
85 #define CHECK_CFG_EXCEPTION do {\
86                 if (cfg->exception_type != MONO_EXCEPTION_NONE)\
87                         goto exception_exit;\
88         } while (0)
89 #define METHOD_ACCESS_FAILURE do {      \
90                 char *method_fname = mono_method_full_name (method, TRUE);      \
91                 char *cil_method_fname = mono_method_full_name (cil_method, TRUE);      \
92                 cfg->exception_type = MONO_EXCEPTION_METHOD_ACCESS;     \
93                 cfg->exception_message = g_strdup_printf ("Method `%s' is inaccessible from method `%s'\n", cil_method_fname, method_fname);    \
94                 g_free (method_fname);  \
95                 g_free (cil_method_fname);      \
96                 goto exception_exit;    \
97         } while (0)
98 #define FIELD_ACCESS_FAILURE do {       \
99                 char *method_fname = mono_method_full_name (method, TRUE);      \
100                 char *field_fname = mono_field_full_name (field);       \
101                 cfg->exception_type = MONO_EXCEPTION_FIELD_ACCESS;      \
102                 cfg->exception_message = g_strdup_printf ("Field `%s' is inaccessible from method `%s'\n", field_fname, method_fname);  \
103                 g_free (method_fname);  \
104                 g_free (field_fname);   \
105                 goto exception_exit;    \
106         } while (0)
107 #define GENERIC_SHARING_FAILURE(opcode) do {            \
108                 if (cfg->generic_sharing_context) {     \
109                         /*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__)*/; \
110                         cfg->exception_type = MONO_EXCEPTION_GENERIC_SHARING_FAILED;    \
111                         goto exception_exit;    \
112                 }                       \
113         } while (0)
114 #define GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD(opcode) do {                        \
115                 if (method->klass->valuetype)   \
116                         GENERIC_SHARING_FAILURE ((opcode)); \
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 inline static int mono_emit_jit_icall (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoInst **args, const guint8 *ip);
126
127 static void handle_stobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, MonoInst *src, 
128                           const unsigned char *ip, MonoClass *klass, gboolean to_end, gboolean native, gboolean write_barrier);
129
130 static void dec_foreach (MonoInst *tree, MonoCompile *cfg);
131
132 static int mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
133                    int locals_offset, MonoInst *return_var, GList *dont_inline, MonoInst **inline_args, 
134                    guint inline_offset, gboolean is_virtual_call);
135
136 #ifdef MONO_ARCH_SOFT_FLOAT
137 static void
138 handle_store_float (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ptr, MonoInst *val, const unsigned char *ip);
139 #endif
140
141 /* helper methods signature */
142 static MonoMethodSignature *helper_sig_class_init_trampoline = NULL;
143 static MonoMethodSignature *helper_sig_generic_class_init_trampoline = NULL;
144 static MonoMethodSignature *helper_sig_rgctx_lazy_fetch_trampoline = NULL;
145 static MonoMethodSignature *helper_sig_domain_get = NULL;
146
147 static guint32 default_opt = 0;
148 static gboolean default_opt_set = FALSE;
149
150 guint32 mono_jit_tls_id = -1;
151 MonoTraceSpec *mono_jit_trace_calls = NULL;
152 gboolean mono_break_on_exc = FALSE;
153 #ifndef DISABLE_AOT
154 gboolean mono_compile_aot = FALSE;
155 #endif
156 MonoMethodDesc *mono_inject_async_exc_method = NULL;
157 int mono_inject_async_exc_pos;
158 MonoMethodDesc *mono_break_at_bb_method = NULL;
159 int mono_break_at_bb_bb_num;
160
161 static int mini_verbose = 0;
162
163 #define mono_jit_lock() EnterCriticalSection (&jit_mutex)
164 #define mono_jit_unlock() LeaveCriticalSection (&jit_mutex)
165 static CRITICAL_SECTION jit_mutex;
166
167 static GHashTable *rgctx_lazy_fetch_trampoline_hash = NULL;
168
169 static MonoCodeManager *global_codeman = NULL;
170
171 static GHashTable *jit_icall_name_hash = NULL;
172
173 static MonoDebugOptions debug_options;
174
175 #ifdef VALGRIND_JIT_REGISTER_MAP
176 static int valgrind_register = 0;
177 #endif
178
179 /*
180  * Table written to by the debugger with a 1-based index into the
181  * mono_breakpoint_info table, which contains changes made to
182  * the JIT instructions by the debugger.
183  */
184 gssize
185 mono_breakpoint_info_index [MONO_BREAKPOINT_ARRAY_SIZE];
186
187 /* Whenever to check for pending exceptions in managed-to-native wrappers */
188 gboolean check_for_pending_exc = TRUE;
189
190 gboolean
191 mono_running_on_valgrind (void)
192 {
193 #ifdef HAVE_VALGRIND_MEMCHECK_H
194                 if (RUNNING_ON_VALGRIND){
195 #ifdef VALGRIND_JIT_REGISTER_MAP
196                         valgrind_register = TRUE;
197 #endif
198                         return TRUE;
199                 } else
200                         return FALSE;
201 #else
202                 return FALSE;
203 #endif
204 }
205
206 typedef struct {
207         void *ip;
208         MonoMethod *method;
209 } FindTrampUserData;
210
211 static void
212 find_tramp (gpointer key, gpointer value, gpointer user_data)
213 {
214         FindTrampUserData *ud = (FindTrampUserData*)user_data;
215
216         if (value == ud->ip)
217                 ud->method = (MonoMethod*)key;
218 }
219
220 /* debug function */
221 G_GNUC_UNUSED static char*
222 get_method_from_ip (void *ip)
223 {
224         MonoJitInfo *ji;
225         char *method;
226         char *res;
227         MonoDomain *domain = mono_domain_get ();
228         MonoDebugSourceLocation *location;
229         FindTrampUserData user_data;
230         
231         ji = mono_jit_info_table_find (domain, ip);
232         if (!ji) {
233                 user_data.ip = ip;
234                 user_data.method = NULL;
235                 mono_domain_lock (domain);
236                 g_hash_table_foreach (domain->jit_trampoline_hash, find_tramp, &user_data);
237                 mono_domain_unlock (domain);
238                 if (user_data.method) {
239                         char *mname = mono_method_full_name (user_data.method, TRUE);
240                         res = g_strdup_printf ("<%p - JIT trampoline for %s>", ip, mname);
241                         g_free (mname);
242                         return res;
243                 }
244                 else
245                         return NULL;
246         }
247         method = mono_method_full_name (ji->method, TRUE);
248         /* FIXME: unused ? */
249         location = mono_debug_lookup_source_location (ji->method, (guint32)((guint8*)ip - (guint8*)ji->code_start), domain);
250
251         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);
252
253         mono_debug_free_source_location (location);
254         g_free (method);
255
256         return res;
257 }
258
259 /** 
260  * mono_pmip:
261  * @ip: an instruction pointer address
262  *
263  * This method is used from a debugger to get the name of the
264  * method at address @ip.   This routine is typically invoked from
265  * a debugger like this:
266  *
267  * (gdb) print mono_pmip ($pc)
268  *
269  * Returns: the name of the method at address @ip.
270  */
271 G_GNUC_UNUSED char *
272 mono_pmip (void *ip)
273 {
274         return get_method_from_ip (ip);
275 }
276
277 /** 
278  * mono_print_method_from_ip
279  * @ip: an instruction pointer address
280  *
281  * This method is used from a debugger to get the name of the
282  * method at address @ip.
283  *
284  * This prints the name of the method at address @ip in the standard
285  * output.  Unlike mono_pmip which returns a string, this routine
286  * prints the value on the standard output. 
287  */
288 void
289 mono_print_method_from_ip (void *ip)
290 {
291         MonoJitInfo *ji;
292         char *method;
293         MonoDebugSourceLocation *source;
294         MonoDomain *domain = mono_domain_get ();
295         FindTrampUserData user_data;
296         
297         ji = mono_jit_info_table_find (domain, ip);
298         if (!ji) {
299                 user_data.ip = ip;
300                 user_data.method = NULL;
301                 mono_domain_lock (domain);
302                 g_hash_table_foreach (domain->jit_trampoline_hash, find_tramp, &user_data);
303                 mono_domain_unlock (domain);
304                 if (user_data.method) {
305                         char *mname = mono_method_full_name (user_data.method, TRUE);
306                         printf ("IP %p is a JIT trampoline for %s\n", ip, mname);
307                         g_free (mname);
308                 }
309                 else
310                         g_print ("No method at %p\n", ip);
311                 return;
312         }
313         method = mono_method_full_name (ji->method, TRUE);
314         source = mono_debug_lookup_source_location (ji->method, (guint32)((guint8*)ip - (guint8*)ji->code_start), domain);
315
316         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);
317
318         if (source)
319                 g_print ("%s:%d\n", source->source_file, source->row);
320
321         mono_debug_free_source_location (source);
322         g_free (method);
323 }
324         
325 /* 
326  * mono_method_same_domain:
327  *
328  * Determine whenever two compiled methods are in the same domain, thus
329  * the address of the callee can be embedded in the caller.
330  */
331 gboolean mono_method_same_domain (MonoJitInfo *caller, MonoJitInfo *callee)
332 {
333         if (!caller || !callee)
334                 return FALSE;
335
336         /*
337          * If the call was made from domain-neutral to domain-specific 
338          * code, we can't patch the call site.
339          */
340         if (caller->domain_neutral && !callee->domain_neutral)
341                 return FALSE;
342
343         if ((caller->method->klass == mono_defaults.appdomain_class) &&
344                 (strstr (caller->method->name, "InvokeInDomain"))) {
345                  /* The InvokeInDomain methods change the current appdomain */
346                 return FALSE;
347         }
348
349         return TRUE;
350 }
351
352 /*
353  * mono_global_codeman_reserve:
354  *
355  *  Allocate code memory from the global code manager.
356  */
357 void *mono_global_codeman_reserve (int size)
358 {
359         void *ptr;
360
361         if (!global_codeman) {
362                 /* This can happen during startup */
363                 global_codeman = mono_code_manager_new ();
364                 return mono_code_manager_reserve (global_codeman, size);
365         }
366         else {
367                 mono_jit_lock ();
368                 ptr = mono_code_manager_reserve (global_codeman, size);
369                 mono_jit_unlock ();
370                 return ptr;
371         }
372 }
373
374 MonoJumpInfoToken *
375 mono_jump_info_token_new (MonoMemPool *mp, MonoImage *image, guint32 token)
376 {
377         MonoJumpInfoToken *res = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoToken));
378         res->image = image;
379         res->token = token;
380
381         return res;
382 }
383
384 #define MONO_INIT_VARINFO(vi,id) do { \
385         (vi)->range.first_use.pos.bid = 0xffff; \
386         (vi)->reg = -1; \
387         (vi)->idx = (id); \
388 } while (0)
389
390 //#define UNVERIFIED do { G_BREAKPOINT (); goto unverified; } while (0)
391 #define UNVERIFIED do { if (debug_options.break_on_unverified) G_BREAKPOINT (); else goto unverified; } while (0)
392
393 /*
394  * Basic blocks have two numeric identifiers:
395  * dfn: Depth First Number
396  * block_num: unique ID assigned at bblock creation
397  */
398 #define NEW_BBLOCK(cfg,new_bb) do {     \
399                 new_bb = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock)); \
400                 MONO_INST_LIST_INIT (&new_bb->ins_list); \
401         } while (0)
402
403 #define ADD_BBLOCK(cfg,b) do {  \
404                 cfg->cil_offset_to_bb [(b)->cil_code - cfg->cil_start] = (b);   \
405                 (b)->block_num = cfg->num_bblocks++;    \
406                 (b)->real_offset = real_offset; \
407         } while (0)
408
409 #define GET_BBLOCK(cfg,tblock,ip) do {  \
410                 (tblock) = cfg->cil_offset_to_bb [(ip) - cfg->cil_start]; \
411                 if (!(tblock)) {        \
412                         if ((ip) >= end || (ip) < header->code) UNVERIFIED; \
413                         NEW_BBLOCK (cfg, (tblock));     \
414                         (tblock)->cil_code = (ip);      \
415                         ADD_BBLOCK (cfg, (tblock));     \
416                 } \
417         } while (0)
418
419 #define CHECK_BBLOCK(target,ip,tblock) do {     \
420                 if ((target) < (ip) && \
421                                 MONO_INST_LIST_EMPTY (&(tblock)->ins_list)) { \
422                         bb_recheck = g_list_prepend (bb_recheck, (tblock)); \
423                         if (cfg->verbose_level > 2) \
424                                 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)); \
425                 } \
426         } while (0)
427
428 #define NEW_ICONST(cfg,dest,val) do {   \
429                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
430                 (dest)->opcode = OP_ICONST;     \
431                 (dest)->inst_c0 = (val);        \
432                 (dest)->type = STACK_I4;        \
433         } while (0)
434
435 #define NEW_PCONST(cfg,dest,val) do {   \
436                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
437                 (dest)->opcode = OP_PCONST;     \
438                 (dest)->inst_p0 = (val);        \
439                 (dest)->type = STACK_PTR;       \
440         } while (0)
441
442
443 #ifdef MONO_ARCH_NEED_GOT_VAR
444
445 #define NEW_PATCH_INFO(cfg,dest,el1,el2) do {   \
446                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
447                 (dest)->opcode = OP_PATCH_INFO; \
448                 (dest)->inst_left = (gpointer)(el1);    \
449                 (dest)->inst_right = (gpointer)(el2);   \
450         } while (0)
451
452 #define NEW_AOTCONST(cfg,dest,patch_type,cons) do {                     \
453                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
454                 (dest)->opcode = cfg->compile_aot ? OP_GOT_ENTRY : OP_PCONST; \
455                 if (cfg->compile_aot) {                                 \
456                         MonoInst *group, *got_var, *got_loc;            \
457                         got_loc = mono_get_got_var (cfg);               \
458                         NEW_TEMPLOAD ((cfg), got_var, got_loc->inst_c0); \
459                         NEW_PATCH_INFO ((cfg), group, cons, patch_type); \
460                         (dest)->inst_p0 = got_var;                      \
461                         (dest)->inst_p1 = group;                        \
462                 } else {                                                \
463                         (dest)->inst_p0 = (cons);                       \
464                         (dest)->inst_i1 = (gpointer)(patch_type);       \
465                 }                                                       \
466                 (dest)->type = STACK_PTR;                               \
467         } while (0)
468
469 #define NEW_AOTCONST_TOKEN(cfg,dest,patch_type,image,token,stack_type,stack_class) do { \
470                 MonoInst *group, *got_var, *got_loc;                    \
471                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
472                 (dest)->opcode = OP_GOT_ENTRY;                          \
473                 got_loc = mono_get_got_var (cfg);                       \
474                 NEW_TEMPLOAD ((cfg), got_var, got_loc->inst_c0);        \
475                 NEW_PATCH_INFO ((cfg), group, NULL, patch_type);        \
476                 group->inst_p0 = mono_jump_info_token_new ((cfg)->mempool, (image), (token)); \
477                 (dest)->inst_p0 = got_var;                              \
478                 (dest)->inst_p1 = group;                                \
479                 (dest)->type = (stack_type);                    \
480         (dest)->klass = (stack_class);          \
481         } while (0)
482
483 #else
484
485 #define NEW_AOTCONST(cfg,dest,patch_type,cons) do {    \
486                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
487                 (dest)->opcode = cfg->compile_aot ? OP_AOTCONST : OP_PCONST;    \
488                 (dest)->inst_p0 = (cons);       \
489                 (dest)->inst_i1 = (gpointer)(patch_type); \
490                 (dest)->type = STACK_PTR;       \
491     } while (0)
492
493 #define NEW_AOTCONST_TOKEN(cfg,dest,patch_type,image,token,stack_type,stack_class) do { \
494                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
495                 (dest)->opcode = OP_AOTCONST;   \
496                 (dest)->inst_p0 = mono_jump_info_token_new ((cfg)->mempool, (image), (token));  \
497                 (dest)->inst_p1 = (gpointer)(patch_type); \
498                 (dest)->type = (stack_type);    \
499         (dest)->klass = (stack_class);          \
500     } while (0)
501
502 #endif
503
504 #define NEW_CLASSCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_CLASS, (val))
505
506 #define NEW_IMAGECONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_IMAGE, (val))
507
508 #define NEW_FIELDCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_FIELD, (val))
509
510 #define NEW_METHODCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_METHODCONST, (val))
511
512 #define NEW_VTABLECONST(cfg,dest,vtable) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_VTABLE, cfg->compile_aot ? (gpointer)((vtable)->klass) : (vtable))
513
514 #define NEW_SFLDACONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_SFLDA, (val))
515
516 #define NEW_LDSTRCONST(cfg,dest,image,token) NEW_AOTCONST_TOKEN ((cfg), (dest), MONO_PATCH_INFO_LDSTR, (image), (token), STACK_OBJ, mono_defaults.string_class)
517
518 #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)
519
520 #define NEW_LDTOKENCONST(cfg,dest,image,token) NEW_AOTCONST_TOKEN ((cfg), (dest), MONO_PATCH_INFO_LDTOKEN, (image), (token), STACK_PTR, NULL)
521
522 #define NEW_DECLSECCONST(cfg,dest,image,entry) do { \
523                 if (cfg->compile_aot) { \
524                         NEW_AOTCONST_TOKEN (cfg, dest, MONO_PATCH_INFO_DECLSEC, image, (entry).index, STACK_OBJ, NULL); \
525                 } else { \
526                         NEW_PCONST (cfg, args [0], (entry).blob); \
527                 } \
528         } while (0)
529
530 #define NEW_DOMAINCONST(cfg,dest) do { \
531                 if (cfg->opt & MONO_OPT_SHARED) { \
532                         /* avoid depending on undefined C behavior in sequence points */ \
533                         MonoInst* __domain_var = mono_get_domainvar (cfg); \
534                         NEW_TEMPLOAD (cfg, dest, __domain_var->inst_c0); \
535                 } else { \
536                         NEW_PCONST (cfg, dest, (cfg)->domain); \
537                 } \
538         } while (0)
539
540 #define GET_VARINFO_INST(cfg,num) ((cfg)->varinfo [(num)]->inst)
541
542 #define NEW_ARGLOAD(cfg,dest,num) do {  \
543                 if (arg_array [(num)]->opcode == OP_ICONST) (dest) = arg_array [(num)]; else { \
544                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
545                 (dest)->ssa_op = MONO_SSA_LOAD; \
546                 (dest)->inst_i0 = arg_array [(num)];    \
547                 (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
548                 type_to_eval_stack_type ((cfg), param_types [(num)], (dest));   \
549                 (dest)->klass = (dest)->inst_i0->klass; \
550         }} while (0)
551
552 #define NEW_LOCLOAD(cfg,dest,num) do {  \
553                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
554                 (dest)->ssa_op = MONO_SSA_LOAD; \
555                 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)];       \
556                 (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
557                 type_to_eval_stack_type ((cfg), header->locals [(num)], (dest));        \
558                 (dest)->klass = (dest)->inst_i0->klass; \
559         } while (0)
560
561 #define NEW_LOCLOADA(cfg,dest,num) do { \
562                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
563                 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN;        \
564                 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)];       \
565                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
566                 (dest)->opcode = OP_LDADDR;     \
567                 (dest)->type = STACK_MP;        \
568                 (dest)->klass = (dest)->inst_i0->klass; \
569         if (!MONO_TYPE_ISSTRUCT (header->locals [(num)])) \
570            (cfg)->disable_ssa = TRUE; \
571         } while (0)
572
573 #define NEW_RETLOADA(cfg,dest) do {     \
574         if (cfg->vret_addr) { \
575                     (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));   \
576                     (dest)->ssa_op = MONO_SSA_LOAD;     \
577                     (dest)->inst_i0 = cfg->vret_addr; \
578                     (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
579             (dest)->type = STACK_MP; \
580                     (dest)->klass = (dest)->inst_i0->klass;     \
581         } else { \
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         } \
591         } while (0)
592
593 #define NEW_ARGLOADA(cfg,dest,num) do { \
594                 if (arg_array [(num)]->opcode == OP_ICONST) goto inline_failure; \
595                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
596                 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN;        \
597                 (dest)->inst_i0 = arg_array [(num)];    \
598                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
599                 (dest)->opcode = OP_LDADDR;     \
600                 (dest)->type = STACK_MP;        \
601                 (dest)->klass = (dest)->inst_i0->klass; \
602                 (cfg)->disable_ssa = TRUE; \
603         } while (0)
604
605 #define NEW_TEMPLOAD(cfg,dest,num) do { \
606                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
607                 (dest)->ssa_op = MONO_SSA_LOAD; \
608                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
609                 (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
610                 type_to_eval_stack_type ((cfg), (dest)->inst_i0->inst_vtype, (dest));   \
611                 (dest)->klass = (dest)->inst_i0->klass; \
612         } while (0)
613
614 #define NEW_TEMPLOADA(cfg,dest,num) do {        \
615                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
616                 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN;        \
617                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
618                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
619                 (dest)->opcode = OP_LDADDR;     \
620                 (dest)->type = STACK_MP;        \
621                 (dest)->klass = (dest)->inst_i0->klass; \
622         if (!MONO_TYPE_ISSTRUCT (cfg->varinfo [(num)]->inst_vtype)) \
623            (cfg)->disable_ssa = TRUE; \
624         } while (0)
625
626
627 #define NEW_INDLOAD(cfg,dest,addr,vtype) do {   \
628                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
629                 (dest)->inst_left = addr;       \
630                 (dest)->opcode = mini_type_to_ldind ((cfg), vtype);     \
631                 type_to_eval_stack_type ((cfg), vtype, (dest)); \
632                 /* FIXME: (dest)->klass = (dest)->inst_i0->klass;*/     \
633         } while (0)
634
635 #define NEW_INDSTORE(cfg,dest,addr,value,vtype) do {    \
636                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
637                 (dest)->inst_i0 = addr; \
638                 (dest)->opcode = mini_type_to_stind ((cfg), vtype);     \
639                 (dest)->inst_i1 = (value);      \
640                 /* FIXME: (dest)->klass = (dest)->inst_i0->klass;*/     \
641         } while (0)
642
643 #define NEW_TEMPSTORE(cfg,dest,num,inst) do {   \
644                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
645                 (dest)->ssa_op = MONO_SSA_STORE;        \
646                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
647                 (dest)->opcode = mini_type_to_stind ((cfg), (dest)->inst_i0->inst_vtype); \
648                 (dest)->inst_i1 = (inst);       \
649                 (dest)->klass = (dest)->inst_i0->klass; \
650         } while (0)
651
652 #define NEW_LOCSTORE(cfg,dest,num,inst) do {    \
653                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
654                 (dest)->opcode = mini_type_to_stind ((cfg), header->locals [(num)]); \
655                 (dest)->ssa_op = MONO_SSA_STORE;        \
656                 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)];       \
657                 (dest)->inst_i1 = (inst);       \
658                 (dest)->klass = (dest)->inst_i0->klass; \
659         } while (0)
660
661 #define NEW_ARGSTORE(cfg,dest,num,inst) do {    \
662                 if (arg_array [(num)]->opcode == OP_ICONST) goto inline_failure; \
663                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
664                 (dest)->opcode = mini_type_to_stind ((cfg), param_types [(num)]); \
665                 (dest)->ssa_op = MONO_SSA_STORE;        \
666                 (dest)->inst_i0 = arg_array [(num)];    \
667                 (dest)->inst_i1 = (inst);       \
668                 (dest)->klass = (dest)->inst_i0->klass; \
669         } while (0)
670
671 #define NEW_MEMCPY(cfg,dest,dst,src,memcpy_size,memcpy_align) do { \
672                 MONO_INST_NEW (cfg, dest, OP_MEMCPY); \
673         (dest)->inst_left = (dst); \
674                 (dest)->inst_right = (src); \
675                 (dest)->cil_code = ip; \
676         (dest)->backend.memcpy_args = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoMemcpyArgs)); \
677                 (dest)->backend.memcpy_args->size = (memcpy_size); \
678                 (dest)->backend.memcpy_args->align = (memcpy_align); \
679     } while (0)
680
681 #define NEW_MEMSET(cfg,dest,dst,imm,memcpy_size,memcpy_align) do { \
682                 MONO_INST_NEW (cfg, dest, OP_MEMSET); \
683         (dest)->inst_left = (dst); \
684                 (dest)->inst_imm = (imm); \
685                 (dest)->cil_code = ip; \
686         (dest)->backend.memcpy_args = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoMemcpyArgs)); \
687                 (dest)->backend.memcpy_args->size = (memcpy_size); \
688                 (dest)->backend.memcpy_args->align = (memcpy_align); \
689     } while (0)
690
691 #define NEW_DUMMY_USE(cfg,dest,load) do { \
692                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
693                 (dest)->opcode = OP_DUMMY_USE; \
694                 (dest)->inst_left = (load); \
695     } while (0)
696
697 #define NEW_DUMMY_STORE(cfg,dest,num) do { \
698                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
699                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
700                 (dest)->opcode = OP_DUMMY_STORE; \
701                 (dest)->klass = (dest)->inst_i0->klass; \
702         } while (0)
703
704 #define ADD_BINOP(op) do {      \
705                 MONO_INST_NEW (cfg, ins, (op)); \
706                 ins->cil_code = ip;     \
707                 sp -= 2;        \
708                 ins->inst_i0 = sp [0];  \
709                 ins->inst_i1 = sp [1];  \
710                 *sp++ = ins;    \
711                 type_from_op (ins);     \
712                 CHECK_TYPE (ins);       \
713         } while (0)
714
715 #define ADD_UNOP(op) do {       \
716                 MONO_INST_NEW (cfg, ins, (op)); \
717                 ins->cil_code = ip;     \
718                 sp--;   \
719                 ins->inst_i0 = sp [0];  \
720                 *sp++ = ins;    \
721                 type_from_op (ins);     \
722                 CHECK_TYPE (ins);       \
723         } while (0)
724
725 #define ADD_BINCOND(next_block) do {    \
726                 MonoInst *cmp;  \
727                 sp -= 2;                \
728                 MONO_INST_NEW(cfg, cmp, OP_COMPARE);    \
729                 cmp->inst_i0 = sp [0];  \
730                 cmp->inst_i1 = sp [1];  \
731                 cmp->cil_code = ins->cil_code;  \
732                 type_from_op (cmp);     \
733                 CHECK_TYPE (cmp);       \
734                 ins->inst_i0 = cmp;     \
735                 MONO_ADD_INS (bblock, ins);     \
736                 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);      \
737                 GET_BBLOCK (cfg, tblock, target);               \
738                 link_bblock (cfg, bblock, tblock);      \
739                 ins->inst_true_bb = tblock;     \
740                 CHECK_BBLOCK (target, ip, tblock);      \
741                 if ((next_block)) {     \
742                         link_bblock (cfg, bblock, (next_block));        \
743                         ins->inst_false_bb = (next_block);      \
744                         start_new_bblock = 1;   \
745                 } else {        \
746                         GET_BBLOCK (cfg, tblock, ip);           \
747                         link_bblock (cfg, bblock, tblock);      \
748                         ins->inst_false_bb = tblock;    \
749                         start_new_bblock = 2;   \
750                 }       \
751         } while (0)
752
753 /* FIXME: handle float, long ... */
754 #define ADD_UNCOND(istrue) do { \
755                 MonoInst *cmp;  \
756                 sp--;           \
757                 MONO_INST_NEW(cfg, cmp, OP_COMPARE);    \
758                 cmp->inst_i0 = sp [0];  \
759                 switch (cmp->inst_i0->type) { \
760                 case STACK_I8: \
761                         cmp->inst_i1 = zero_int64; break; \
762                 case STACK_R8: \
763                         cmp->inst_i1 = zero_r8; break; \
764                 case STACK_PTR: \
765                 case STACK_MP: \
766                         cmp->inst_i1 = zero_ptr; break; \
767                 case STACK_OBJ: \
768                         cmp->inst_i1 = zero_obj; break; \
769                 default: \
770                         cmp->inst_i1 = zero_int32;  \
771                 }  \
772                 cmp->cil_code = ins->cil_code;  \
773                 type_from_op (cmp);     \
774                 CHECK_TYPE (cmp);       \
775                 ins->inst_i0 = cmp;     \
776                 ins->opcode = (istrue)? CEE_BNE_UN: CEE_BEQ;    \
777                 MONO_ADD_INS (bblock, ins);     \
778                 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);      \
779                 GET_BBLOCK (cfg, tblock, target);               \
780                 link_bblock (cfg, bblock, tblock);      \
781                 ins->inst_true_bb = tblock;     \
782                 CHECK_BBLOCK (target, ip, tblock);      \
783                 GET_BBLOCK (cfg, tblock, ip);           \
784                 link_bblock (cfg, bblock, tblock);      \
785                 ins->inst_false_bb = tblock;    \
786                 start_new_bblock = 2;   \
787         } while (0)
788
789 #define NEW_LDELEMA(cfg,dest,sp,k) do { \
790                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
791                 (dest)->opcode = CEE_LDELEMA;   \
792                 (dest)->inst_left = (sp) [0];   \
793                 (dest)->inst_right = (sp) [1];  \
794                 (dest)->type = STACK_MP;        \
795                 (dest)->klass = (k);    \
796                 (cfg)->flags |= MONO_CFG_HAS_LDELEMA; \
797         } while (0)
798
799 #define NEW_GROUP(cfg,dest,el1,el2) do {        \
800                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
801                 (dest)->opcode = OP_GROUP;      \
802                 (dest)->inst_left = (el1);      \
803                 (dest)->inst_right = (el2);     \
804         } while (0)
805
806 #if 0
807 static gint
808 compare_bblock (gconstpointer a, gconstpointer b)
809 {
810         const MonoBasicBlock *b1 = a;
811         const MonoBasicBlock *b2 = b;
812
813         return b2->cil_code - b1->cil_code;
814 }
815 #endif
816
817 /* *
818  * link_bblock: Links two basic blocks
819  *
820  * links two basic blocks in the control flow graph, the 'from'
821  * argument is the starting block and the 'to' argument is the block
822  * the control flow ends to after 'from'.
823  */
824 static void
825 link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
826 {
827         MonoBasicBlock **newa;
828         int i, found;
829
830 #if 0
831         if (from->cil_code) {
832                 if (to->cil_code)
833                         g_print ("edge from IL%04x to IL_%04x\n", from->cil_code - cfg->cil_code, to->cil_code - cfg->cil_code);
834                 else
835                         g_print ("edge from IL%04x to exit\n", from->cil_code - cfg->cil_code);
836         } else {
837                 if (to->cil_code)
838                         g_print ("edge from entry to IL_%04x\n", to->cil_code - cfg->cil_code);
839                 else
840                         g_print ("edge from entry to exit\n");
841         }
842 #endif
843         found = FALSE;
844         for (i = 0; i < from->out_count; ++i) {
845                 if (to == from->out_bb [i]) {
846                         found = TRUE;
847                         break;
848                 }
849         }
850         if (!found) {
851                 newa = mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (from->out_count + 1));
852                 for (i = 0; i < from->out_count; ++i) {
853                         newa [i] = from->out_bb [i];
854                 }
855                 newa [i] = to;
856                 from->out_count++;
857                 from->out_bb = newa;
858         }
859
860         found = FALSE;
861         for (i = 0; i < to->in_count; ++i) {
862                 if (from == to->in_bb [i]) {
863                         found = TRUE;
864                         break;
865                 }
866         }
867         if (!found) {
868                 newa = mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (to->in_count + 1));
869                 for (i = 0; i < to->in_count; ++i) {
870                         newa [i] = to->in_bb [i];
871                 }
872                 newa [i] = from;
873                 to->in_count++;
874                 to->in_bb = newa;
875         }
876 }
877
878 /**
879  * mono_unlink_bblock:
880  *
881  *   Unlink two basic blocks.
882  */
883 static void
884 mono_unlink_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
885 {
886         int i, pos;
887         gboolean found;
888
889         found = FALSE;
890         for (i = 0; i < from->out_count; ++i) {
891                 if (to == from->out_bb [i]) {
892                         found = TRUE;
893                         break;
894                 }
895         }
896         if (found) {
897                 pos = 0;
898                 for (i = 0; i < from->out_count; ++i) {
899                         if (from->out_bb [i] != to)
900                                 from->out_bb [pos ++] = from->out_bb [i];
901                 }
902                 g_assert (pos == from->out_count - 1);
903                 from->out_count--;
904         }
905
906         found = FALSE;
907         for (i = 0; i < to->in_count; ++i) {
908                 if (from == to->in_bb [i]) {
909                         found = TRUE;
910                         break;
911                 }
912         }
913         if (found) {
914                 pos = 0;
915                 for (i = 0; i < to->in_count; ++i) {
916                         if (to->in_bb [i] != from)
917                                 to->in_bb [pos ++] = to->in_bb [i];
918                 }
919                 g_assert (pos == to->in_count - 1);
920                 to->in_count--;
921         }
922 }
923
924 /**
925  * mono_find_block_region:
926  *
927  *   We mark each basic block with a region ID. We use that to avoid BB
928  *   optimizations when blocks are in different regions.
929  *
930  * Returns:
931  *   A region token that encodes where this region is, and information
932  *   about the clause owner for this block.
933  *
934  *   The region encodes the try/catch/filter clause that owns this block
935  *   as well as the type.  -1 is a special value that represents a block
936  *   that is in none of try/catch/filter.
937  */
938 static int
939 mono_find_block_region (MonoCompile *cfg, int offset)
940 {
941         MonoMethod *method = cfg->method;
942         MonoMethodHeader *header = mono_method_get_header (method);
943         MonoExceptionClause *clause;
944         int i;
945
946         /* first search for handlers and filters */
947         for (i = 0; i < header->num_clauses; ++i) {
948                 clause = &header->clauses [i];
949                 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->data.filter_offset) &&
950                     (offset < (clause->handler_offset)))
951                         return ((i + 1) << 8) | MONO_REGION_FILTER | clause->flags;
952                            
953                 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
954                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
955                                 return ((i + 1) << 8) | MONO_REGION_FINALLY | clause->flags;
956                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
957                                 return ((i + 1) << 8) | MONO_REGION_FAULT | clause->flags;
958                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
959                                 return ((i + 1) << 8) | MONO_REGION_CATCH | clause->flags;
960                 }
961         }
962
963         /* search the try blocks */
964         for (i = 0; i < header->num_clauses; ++i) {
965                 clause = &header->clauses [i];
966                 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
967                         return ((i + 1) << 8) | clause->flags;
968         }
969
970         return -1;
971 }
972
973 static GList*
974 mono_find_final_block (MonoCompile *cfg, unsigned char *ip, unsigned char *target, int type)
975 {
976         MonoMethod *method = cfg->method;
977         MonoMethodHeader *header = mono_method_get_header (method);
978         MonoExceptionClause *clause;
979         MonoBasicBlock *handler;
980         int i;
981         GList *res = NULL;
982
983         for (i = 0; i < header->num_clauses; ++i) {
984                 clause = &header->clauses [i];
985                 if (MONO_OFFSET_IN_CLAUSE (clause, (ip - header->code)) && 
986                     (!MONO_OFFSET_IN_CLAUSE (clause, (target - header->code)))) {
987                         if (clause->flags == type) {
988                                 handler = cfg->cil_offset_to_bb [clause->handler_offset];
989                                 g_assert (handler);
990                                 res = g_list_append (res, handler);
991                         }
992                 }
993         }
994         return res;
995 }
996
997 MonoInst *
998 mono_find_spvar_for_region (MonoCompile *cfg, int region)
999 {
1000         return g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
1001 }
1002
1003 static void
1004 mono_create_spvar_for_region (MonoCompile *cfg, int region)
1005 {
1006         MonoInst *var;
1007
1008         var = g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
1009         if (var)
1010                 return;
1011
1012         var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1013         /* prevent it from being register allocated */
1014         var->flags |= MONO_INST_INDIRECT;
1015
1016         g_hash_table_insert (cfg->spvars, GINT_TO_POINTER (region), var);
1017 }
1018
1019 static MonoInst *
1020 mono_find_exvar_for_offset (MonoCompile *cfg, int offset)
1021 {
1022         return g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
1023 }
1024
1025 static MonoInst*
1026 mono_create_exvar_for_offset (MonoCompile *cfg, int offset)
1027 {
1028         MonoInst *var;
1029
1030         var = g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
1031         if (var)
1032                 return var;
1033
1034         var = mono_compile_create_var (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL);
1035         /* prevent it from being register allocated */
1036         var->flags |= MONO_INST_INDIRECT;
1037
1038         g_hash_table_insert (cfg->exvars, GINT_TO_POINTER (offset), var);
1039
1040         return var;
1041 }
1042
1043 static void
1044 df_visit (MonoBasicBlock *start, int *dfn, MonoBasicBlock **array)
1045 {
1046         int i;
1047
1048         array [*dfn] = start;
1049         /*g_print ("visit %d at %p (BB%ld)\n", *dfn, start->cil_code, start->block_num);*/
1050         for (i = 0; i < start->out_count; ++i) {
1051                 if (start->out_bb [i]->dfn)
1052                         continue;
1053                 (*dfn)++;
1054                 start->out_bb [i]->dfn = *dfn;
1055                 start->out_bb [i]->df_parent = start;
1056                 array [*dfn] = start->out_bb [i];
1057                 df_visit (start->out_bb [i], dfn, array);
1058         }
1059 }
1060
1061 static MonoBasicBlock*
1062 find_previous (MonoBasicBlock **bblocks, guint32 n_bblocks, MonoBasicBlock *start, const guchar *code)
1063 {
1064         MonoBasicBlock *best = start;
1065         int i;
1066
1067         for (i = 0; i < n_bblocks; ++i) {
1068                 if (bblocks [i]) {
1069                         MonoBasicBlock *bb = bblocks [i];
1070
1071                         if (bb->cil_code && bb->cil_code < code && bb->cil_code > best->cil_code)
1072                                 best = bb;
1073                 }
1074         }
1075
1076         return best;
1077 }
1078
1079 static void
1080 split_bblock (MonoCompile *cfg, MonoBasicBlock *first, MonoBasicBlock *second) {
1081         int i, j;
1082         MonoInst *inst;
1083         MonoBasicBlock *bb;
1084
1085         if (!MONO_INST_LIST_EMPTY (&second->ins_list))
1086                 return;
1087         
1088         /* 
1089          * FIXME: take into account all the details:
1090          * second may have been the target of more than one bblock
1091          */
1092         second->out_count = first->out_count;
1093         second->out_bb = first->out_bb;
1094
1095         for (i = 0; i < first->out_count; ++i) {
1096                 bb = first->out_bb [i];
1097                 for (j = 0; j < bb->in_count; ++j) {
1098                         if (bb->in_bb [j] == first)
1099                                 bb->in_bb [j] = second;
1100                 }
1101         }
1102
1103         first->out_count = 0;
1104         first->out_bb = NULL;
1105         link_bblock (cfg, first, second);
1106
1107         /*g_print ("start search at %p for %p\n", first->cil_code, second->cil_code);*/
1108         MONO_BB_FOR_EACH_INS (first, inst) {
1109                 MonoInst *inst_next;
1110
1111                 /*char *code = mono_disasm_code_one (NULL, cfg->method, inst->next->cil_code, NULL);
1112                 g_print ("found %p: %s", inst->next->cil_code, code);
1113                 g_free (code);*/
1114                 if (inst->cil_code >= second->cil_code)
1115                         continue;
1116
1117                 inst_next = mono_inst_list_next (&inst->node, &first->ins_list);
1118                 if (!inst_next)
1119                         break;
1120
1121                 if (inst_next->cil_code < second->cil_code)
1122                         continue;
1123                         
1124                 second->ins_list.next = inst->node.next;
1125                 second->ins_list.prev = first->ins_list.prev;
1126                 inst->node.next = &first->ins_list;
1127                 first->ins_list.prev = &inst->node;
1128
1129                 second->next_bb = first->next_bb;
1130                 first->next_bb = second;
1131                 return;
1132         }
1133         if (MONO_INST_LIST_EMPTY (&second->ins_list)) {
1134                 g_warning ("bblock split failed in %s::%s\n", cfg->method->klass->name, cfg->method->name);
1135                 //G_BREAKPOINT ();
1136         }
1137 }
1138
1139 static guint32
1140 reverse_branch_op (guint32 opcode)
1141 {
1142         static const int reverse_map [] = {
1143                 CEE_BNE_UN, CEE_BLT, CEE_BLE, CEE_BGT, CEE_BGE,
1144                 CEE_BEQ, CEE_BLT_UN, CEE_BLE_UN, CEE_BGT_UN, CEE_BGE_UN
1145         };
1146         static const int reverse_fmap [] = {
1147                 OP_FBNE_UN, OP_FBLT, OP_FBLE, OP_FBGT, OP_FBGE,
1148                 OP_FBEQ, OP_FBLT_UN, OP_FBLE_UN, OP_FBGT_UN, OP_FBGE_UN
1149         };
1150         static const int reverse_lmap [] = {
1151                 OP_LBNE_UN, OP_LBLT, OP_LBLE, OP_LBGT, OP_LBGE,
1152                 OP_LBEQ, OP_LBLT_UN, OP_LBLE_UN, OP_LBGT_UN, OP_LBGE_UN
1153         };
1154         static const int reverse_imap [] = {
1155                 OP_IBNE_UN, OP_IBLT, OP_IBLE, OP_IBGT, OP_IBGE,
1156                 OP_IBEQ, OP_IBLT_UN, OP_IBLE_UN, OP_IBGT_UN, OP_IBGE_UN
1157         };
1158                                 
1159         if (opcode >= CEE_BEQ && opcode <= CEE_BLT_UN) {
1160                 opcode = reverse_map [opcode - CEE_BEQ];
1161         } else if (opcode >= OP_FBEQ && opcode <= OP_FBLT_UN) {
1162                 opcode = reverse_fmap [opcode - OP_FBEQ];
1163         } else if (opcode >= OP_LBEQ && opcode <= OP_LBLT_UN) {
1164                 opcode = reverse_lmap [opcode - OP_LBEQ];
1165         } else if (opcode >= OP_IBEQ && opcode <= OP_IBLT_UN) {
1166                 opcode = reverse_imap [opcode - OP_IBEQ];
1167         } else
1168                 g_assert_not_reached ();
1169
1170         return opcode;
1171 }
1172
1173 #ifdef MONO_ARCH_SOFT_FLOAT
1174 static int
1175 condbr_to_fp_br (int opcode)
1176 {
1177         switch (opcode) {
1178         case CEE_BEQ: return OP_FBEQ;
1179         case CEE_BGE: return OP_FBGE;
1180         case CEE_BGT: return OP_FBGT;
1181         case CEE_BLE: return OP_FBLE;
1182         case CEE_BLT: return OP_FBLT;
1183         case CEE_BNE_UN: return OP_FBNE_UN;
1184         case CEE_BGE_UN: return OP_FBGE_UN;
1185         case CEE_BGT_UN: return OP_FBGT_UN;
1186         case CEE_BLE_UN: return OP_FBLE_UN;
1187         case CEE_BLT_UN: return OP_FBLT_UN;
1188         }
1189         g_assert_not_reached ();
1190         return 0;
1191 }
1192 #endif
1193
1194 /*
1195  * Returns the type used in the eval stack when @type is loaded.
1196  * FIXME: return a MonoType/MonoClass for the byref and VALUETYPE cases.
1197  */
1198 static void
1199 type_to_eval_stack_type (MonoCompile *cfg, MonoType *type, MonoInst *inst)
1200 {
1201         MonoClass *klass;
1202
1203         inst->klass = klass = mono_class_from_mono_type (type);
1204         if (type->byref) {
1205                 inst->type = STACK_MP;
1206                 return;
1207         }
1208
1209 handle_enum:
1210         switch (type->type) {
1211         case MONO_TYPE_VOID:
1212                 inst->type = STACK_INV;
1213                 return;
1214         case MONO_TYPE_I1:
1215         case MONO_TYPE_U1:
1216         case MONO_TYPE_BOOLEAN:
1217         case MONO_TYPE_I2:
1218         case MONO_TYPE_U2:
1219         case MONO_TYPE_CHAR:
1220         case MONO_TYPE_I4:
1221         case MONO_TYPE_U4:
1222                 inst->type = STACK_I4;
1223                 return;
1224         case MONO_TYPE_I:
1225         case MONO_TYPE_U:
1226         case MONO_TYPE_PTR:
1227         case MONO_TYPE_FNPTR:
1228                 inst->type = STACK_PTR;
1229                 return;
1230         case MONO_TYPE_CLASS:
1231         case MONO_TYPE_STRING:
1232         case MONO_TYPE_OBJECT:
1233         case MONO_TYPE_SZARRAY:
1234         case MONO_TYPE_ARRAY:    
1235                 inst->type = STACK_OBJ;
1236                 return;
1237         case MONO_TYPE_I8:
1238         case MONO_TYPE_U8:
1239                 inst->type = STACK_I8;
1240                 return;
1241         case MONO_TYPE_R4:
1242         case MONO_TYPE_R8:
1243                 inst->type = STACK_R8;
1244                 return;
1245         case MONO_TYPE_VALUETYPE:
1246                 if (type->data.klass->enumtype) {
1247                         type = type->data.klass->enum_basetype;
1248                         goto handle_enum;
1249                 } else {
1250                         inst->klass = klass;
1251                         inst->type = STACK_VTYPE;
1252                         return;
1253                 }
1254         case MONO_TYPE_TYPEDBYREF:
1255                 inst->klass = mono_defaults.typed_reference_class;
1256                 inst->type = STACK_VTYPE;
1257                 return;
1258         case MONO_TYPE_GENERICINST:
1259                 type = &type->data.generic_class->container_class->byval_arg;
1260                 goto handle_enum;
1261         case MONO_TYPE_VAR :
1262         case MONO_TYPE_MVAR :
1263                 /* FIXME: all the arguments must be references for now,
1264                  * later look inside cfg and see if the arg num is
1265                  * really a reference
1266                  */
1267                 g_assert (cfg->generic_sharing_context);
1268                 inst->type = STACK_OBJ;
1269                 return;
1270         default:
1271                 g_error ("unknown type 0x%02x in eval stack type", type->type);
1272         }
1273 }
1274
1275 /*
1276  * The following tables are used to quickly validate the IL code in type_from_op ().
1277  */
1278 static const char
1279 bin_num_table [STACK_MAX] [STACK_MAX] = {
1280         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1281         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
1282         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1283         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
1284         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_R8,  STACK_INV, STACK_INV, STACK_INV},
1285         {STACK_INV, STACK_MP,  STACK_INV, STACK_MP,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV},
1286         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1287         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1288 };
1289
1290 static const char 
1291 neg_table [] = {
1292         STACK_INV, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_INV, STACK_INV, STACK_INV
1293 };
1294
1295 /* reduce the size of this table */
1296 static const char
1297 bin_int_table [STACK_MAX] [STACK_MAX] = {
1298         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1299         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1300         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1301         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, 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         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1306 };
1307
1308 static const char
1309 bin_comp_table [STACK_MAX] [STACK_MAX] = {
1310 /*      Inv i  L  p  F  &  O  vt */
1311         {0},
1312         {0, 1, 0, 1, 0, 0, 0, 0}, /* i, int32 */
1313         {0, 0, 1, 0, 0, 0, 0, 0}, /* L, int64 */
1314         {0, 1, 0, 1, 0, 2, 4, 0}, /* p, ptr */
1315         {0, 0, 0, 0, 1, 0, 0, 0}, /* F, R8 */
1316         {0, 0, 0, 2, 0, 1, 0, 0}, /* &, managed pointer */
1317         {0, 0, 0, 4, 0, 0, 3, 0}, /* O, reference */
1318         {0, 0, 0, 0, 0, 0, 0, 0}, /* vt value type */
1319 };
1320
1321 /* reduce the size of this table */
1322 static const char
1323 shift_table [STACK_MAX] [STACK_MAX] = {
1324         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1325         {STACK_INV, STACK_I4,  STACK_INV, STACK_I4,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1326         {STACK_INV, STACK_I8,  STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1327         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, 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         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1332 };
1333
1334 /*
1335  * Tables to map from the non-specific opcode to the matching
1336  * type-specific opcode.
1337  */
1338 /* handles from CEE_ADD to CEE_SHR_UN (CEE_REM_UN for floats) */
1339 static const guint16
1340 binops_op_map [STACK_MAX] = {
1341         0, 0, OP_LADD-CEE_ADD, OP_PADD-CEE_ADD, OP_FADD-CEE_ADD, OP_PADD-CEE_ADD
1342 };
1343
1344 /* handles from CEE_NEG to CEE_CONV_U8 */
1345 static const guint16
1346 unops_op_map [STACK_MAX] = {
1347         0, 0, OP_LNEG-CEE_NEG, OP_PNEG-CEE_NEG, OP_FNEG-CEE_NEG, OP_PNEG-CEE_NEG
1348 };
1349
1350 /* handles from CEE_CONV_U2 to CEE_SUB_OVF_UN */
1351 static const guint16
1352 ovfops_op_map [STACK_MAX] = {
1353         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
1354 };
1355
1356 /* handles from CEE_CONV_OVF_I1_UN to CEE_CONV_OVF_U_UN */
1357 static const guint16
1358 ovf2ops_op_map [STACK_MAX] = {
1359         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
1360 };
1361
1362 /* handles from CEE_CONV_OVF_I1 to CEE_CONV_OVF_U8 */
1363 static const guint16
1364 ovf3ops_op_map [STACK_MAX] = {
1365         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
1366 };
1367
1368 /* handles from CEE_CEQ to CEE_CLT_UN */
1369 static const guint16
1370 ceqops_op_map [STACK_MAX] = {
1371         0, 0, OP_LCEQ-OP_CEQ, OP_PCEQ-OP_CEQ, OP_FCEQ-OP_CEQ, OP_LCEQ-OP_CEQ
1372 };
1373
1374 /*
1375  * Sets ins->type (the type on the eval stack) according to the
1376  * type of the opcode and the arguments to it.
1377  * Invalid IL code is marked by setting ins->type to the invalid value STACK_INV.
1378  *
1379  * FIXME: this function sets ins->type unconditionally in some cases, but
1380  * it should set it to invalid for some types (a conv.x on an object)
1381  */
1382 static void
1383 type_from_op (MonoInst *ins) {
1384         switch (ins->opcode) {
1385         /* binops */
1386         case CEE_ADD:
1387         case CEE_SUB:
1388         case CEE_MUL:
1389         case CEE_DIV:
1390         case CEE_REM:
1391                 /* FIXME: check unverifiable args for STACK_MP */
1392                 ins->type = bin_num_table [ins->inst_i0->type] [ins->inst_i1->type];
1393                 ins->opcode += binops_op_map [ins->type];
1394                 return;
1395         case CEE_DIV_UN:
1396         case CEE_REM_UN:
1397         case CEE_AND:
1398         case CEE_OR:
1399         case CEE_XOR:
1400                 ins->type = bin_int_table [ins->inst_i0->type] [ins->inst_i1->type];
1401                 ins->opcode += binops_op_map [ins->type];
1402                 return;
1403         case CEE_SHL:
1404         case CEE_SHR:
1405         case CEE_SHR_UN:
1406                 ins->type = shift_table [ins->inst_i0->type] [ins->inst_i1->type];
1407                 ins->opcode += binops_op_map [ins->type];
1408                 return;
1409         case OP_COMPARE:
1410         case OP_LCOMPARE:
1411                 /* FIXME: handle some specifics with ins->next->type */
1412                 ins->type = bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] ? STACK_I4: STACK_INV;
1413                 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))))
1414                         ins->opcode = OP_LCOMPARE;
1415                 return;
1416         case OP_CEQ:
1417                 ins->type = bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] ? STACK_I4: STACK_INV;
1418                 ins->opcode += ceqops_op_map [ins->inst_i0->type];
1419                 return;
1420                 
1421         case OP_CGT:
1422         case OP_CGT_UN:
1423         case OP_CLT:
1424         case OP_CLT_UN:
1425                 ins->type = (bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] & 1) ? STACK_I4: STACK_INV;
1426                 ins->opcode += ceqops_op_map [ins->inst_i0->type];
1427                 return;
1428         /* unops */
1429         case CEE_NEG:
1430                 ins->type = neg_table [ins->inst_i0->type];
1431                 ins->opcode += unops_op_map [ins->type];
1432                 return;
1433         case CEE_NOT:
1434                 if (ins->inst_i0->type >= STACK_I4 && ins->inst_i0->type <= STACK_PTR)
1435                         ins->type = ins->inst_i0->type;
1436                 else
1437                         ins->type = STACK_INV;
1438                 ins->opcode += unops_op_map [ins->type];
1439                 return;
1440         case CEE_CONV_I1:
1441         case CEE_CONV_I2:
1442         case CEE_CONV_I4:
1443         case CEE_CONV_U4:
1444                 ins->type = STACK_I4;
1445                 ins->opcode += unops_op_map [ins->inst_i0->type];
1446                 return;
1447         case CEE_CONV_R_UN:
1448                 ins->type = STACK_R8;
1449                 switch (ins->inst_i0->type) {
1450                 case STACK_I4:
1451                 case STACK_PTR:
1452                         break;
1453                 case STACK_I8:
1454                         ins->opcode = OP_LCONV_TO_R_UN; 
1455                         break;
1456                 }
1457                 return;
1458         case CEE_CONV_OVF_I1:
1459         case CEE_CONV_OVF_U1:
1460         case CEE_CONV_OVF_I2:
1461         case CEE_CONV_OVF_U2:
1462         case CEE_CONV_OVF_I4:
1463         case CEE_CONV_OVF_U4:
1464                 ins->type = STACK_I4;
1465                 ins->opcode += ovf3ops_op_map [ins->inst_i0->type];
1466                 return;
1467         case CEE_CONV_OVF_I_UN:
1468         case CEE_CONV_OVF_U_UN:
1469                 ins->type = STACK_PTR;
1470                 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1471                 return;
1472         case CEE_CONV_OVF_I1_UN:
1473         case CEE_CONV_OVF_I2_UN:
1474         case CEE_CONV_OVF_I4_UN:
1475         case CEE_CONV_OVF_U1_UN:
1476         case CEE_CONV_OVF_U2_UN:
1477         case CEE_CONV_OVF_U4_UN:
1478                 ins->type = STACK_I4;
1479                 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1480                 return;
1481         case CEE_CONV_U:
1482                 ins->type = STACK_PTR;
1483                 switch (ins->inst_i0->type) {
1484                 case STACK_I4:
1485                         break;
1486                 case STACK_PTR:
1487                 case STACK_MP:
1488 #if SIZEOF_VOID_P == 8
1489                         ins->opcode = OP_LCONV_TO_U;
1490 #endif
1491                         break;
1492                 case STACK_I8:
1493                         ins->opcode = OP_LCONV_TO_U;
1494                         break;
1495                 case STACK_R8:
1496                         ins->opcode = OP_FCONV_TO_U;
1497                         break;
1498                 }
1499                 return;
1500         case CEE_CONV_I8:
1501         case CEE_CONV_U8:
1502                 ins->type = STACK_I8;
1503                 ins->opcode += unops_op_map [ins->inst_i0->type];
1504                 return;
1505         case CEE_CONV_OVF_I8:
1506         case CEE_CONV_OVF_U8:
1507                 ins->type = STACK_I8;
1508                 ins->opcode += ovf3ops_op_map [ins->inst_i0->type];
1509                 return;
1510         case CEE_CONV_OVF_U8_UN:
1511         case CEE_CONV_OVF_I8_UN:
1512                 ins->type = STACK_I8;
1513                 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1514                 return;
1515         case CEE_CONV_R4:
1516         case CEE_CONV_R8:
1517                 ins->type = STACK_R8;
1518                 ins->opcode += unops_op_map [ins->inst_i0->type];
1519                 return;
1520         case OP_CKFINITE:
1521                 ins->type = STACK_R8;           
1522                 return;
1523         case CEE_CONV_U2:
1524         case CEE_CONV_U1:
1525                 ins->type = STACK_I4;
1526                 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1527                 break;
1528         case CEE_CONV_I:
1529         case CEE_CONV_OVF_I:
1530         case CEE_CONV_OVF_U:
1531                 ins->type = STACK_PTR;
1532                 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1533                 return;
1534         case CEE_ADD_OVF:
1535         case CEE_ADD_OVF_UN:
1536         case CEE_MUL_OVF:
1537         case CEE_MUL_OVF_UN:
1538         case CEE_SUB_OVF:
1539         case CEE_SUB_OVF_UN:
1540                 ins->type = bin_num_table [ins->inst_i0->type] [ins->inst_i1->type];
1541                 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1542                 if (ins->type == STACK_R8)
1543                         ins->type = STACK_INV;
1544                 return;
1545         default:
1546                 g_error ("opcode 0x%04x not handled in type from op", ins->opcode);
1547                 break;
1548         }
1549 }
1550
1551 static const char 
1552 ldind_type [] = {
1553         STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_R8, STACK_OBJ
1554 };
1555
1556 /* map ldelem.x to the matching ldind.x opcode */
1557 static const guchar
1558 ldelem_to_ldind [] = {
1559         CEE_LDIND_I1,
1560         CEE_LDIND_U1,
1561         CEE_LDIND_I2,
1562         CEE_LDIND_U2,
1563         CEE_LDIND_I4,
1564         CEE_LDIND_U4,
1565         CEE_LDIND_I8,
1566         CEE_LDIND_I,
1567         CEE_LDIND_R4,
1568         CEE_LDIND_R8,
1569         CEE_LDIND_REF
1570 };
1571
1572 /* map stelem.x to the matching stind.x opcode */
1573 static const guchar
1574 stelem_to_stind [] = {
1575         CEE_STIND_I,
1576         CEE_STIND_I1,
1577         CEE_STIND_I2,
1578         CEE_STIND_I4,
1579         CEE_STIND_I8,
1580         CEE_STIND_R4,
1581         CEE_STIND_R8,
1582         CEE_STIND_REF
1583 };
1584
1585 #if 0
1586
1587 static const char
1588 param_table [STACK_MAX] [STACK_MAX] = {
1589         {0},
1590 };
1591
1592 static int
1593 check_values_to_signature (MonoInst *args, MonoType *this, MonoMethodSignature *sig)
1594 {
1595         int i;
1596
1597         if (sig->hasthis) {
1598                 switch (args->type) {
1599                 case STACK_I4:
1600                 case STACK_I8:
1601                 case STACK_R8:
1602                 case STACK_VTYPE:
1603                 case STACK_INV:
1604                         return 0;
1605                 }
1606                 args++;
1607         }
1608         for (i = 0; i < sig->param_count; ++i) {
1609                 switch (args [i].type) {
1610                 case STACK_INV:
1611                         return 0;
1612                 case STACK_MP:
1613                         if (!sig->params [i]->byref)
1614                                 return 0;
1615                         continue;
1616                 case STACK_OBJ:
1617                         if (sig->params [i]->byref)
1618                                 return 0;
1619                         switch (sig->params [i]->type) {
1620                         case MONO_TYPE_CLASS:
1621                         case MONO_TYPE_STRING:
1622                         case MONO_TYPE_OBJECT:
1623                         case MONO_TYPE_SZARRAY:
1624                         case MONO_TYPE_ARRAY:
1625                                 break;
1626                         default:
1627                                 return 0;
1628                         }
1629                         continue;
1630                 case STACK_R8:
1631                         if (sig->params [i]->byref)
1632                                 return 0;
1633                         if (sig->params [i]->type != MONO_TYPE_R4 && sig->params [i]->type != MONO_TYPE_R8)
1634                                 return 0;
1635                         continue;
1636                 case STACK_PTR:
1637                 case STACK_I4:
1638                 case STACK_I8:
1639                 case STACK_VTYPE:
1640                         break;
1641                 }
1642                 /*if (!param_table [args [i].type] [sig->params [i]->type])
1643                         return 0;*/
1644         }
1645         return 1;
1646 }
1647 #endif
1648
1649 static guint
1650 mini_type_to_ldind (MonoCompile* cfg, MonoType *type)
1651 {
1652         if (cfg->generic_sharing_context && !type->byref) {
1653                 /* FIXME: all the arguments must be references for now,
1654                  * later look inside cfg and see if the arg num is
1655                  * really a reference
1656                  */
1657                 if (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)
1658                         return CEE_LDIND_REF;
1659         }
1660         return mono_type_to_ldind (type);
1661 }
1662
1663 static guint
1664 mini_type_to_stind (MonoCompile* cfg, MonoType *type)
1665 {
1666         if (cfg->generic_sharing_context && !type->byref) {
1667                 /* FIXME: all the arguments must be references for now,
1668                  * later look inside cfg and see if the arg num is
1669                  * really a reference
1670                  */
1671                 if (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)
1672                         return CEE_STIND_REF;
1673         }
1674         return mono_type_to_stind (type);
1675 }
1676
1677 int
1678 mono_op_imm_to_op (int opcode)
1679 {
1680         switch (opcode) {
1681         case OP_ADD_IMM:
1682                 return OP_PADD;
1683         case OP_IADD_IMM:
1684                 return OP_IADD;
1685         case OP_LADD_IMM:
1686                 return OP_LADD;
1687         case OP_ISUB_IMM:
1688                 return OP_ISUB;
1689         case OP_LSUB_IMM:
1690                 return OP_LSUB;
1691         case OP_AND_IMM:
1692 #if SIZEOF_VOID_P == 4
1693                 return OP_IAND;
1694 #else
1695                 return OP_LAND;
1696 #endif
1697         case OP_IAND_IMM:
1698                 return OP_IAND;
1699         case OP_LAND_IMM:
1700                 return OP_LAND;
1701         case OP_IOR_IMM:
1702                 return OP_IOR;
1703         case OP_LOR_IMM:
1704                 return OP_LOR;
1705         case OP_IXOR_IMM:
1706                 return OP_IXOR;
1707         case OP_LXOR_IMM:
1708                 return OP_LXOR;
1709         case OP_ISHL_IMM:
1710                 return OP_ISHL;
1711         case OP_LSHL_IMM:
1712                 return OP_LSHL;
1713         case OP_ISHR_IMM:
1714                 return OP_ISHR;
1715         case OP_LSHR_IMM:
1716                 return OP_LSHR;
1717         case OP_ISHR_UN_IMM:
1718                 return OP_ISHR_UN;
1719         case OP_LSHR_UN_IMM:
1720                 return OP_LSHR_UN;
1721         case OP_IDIV_IMM:
1722                 return OP_IDIV;
1723         case OP_IDIV_UN_IMM:
1724                 return OP_IDIV_UN;
1725         case OP_IREM_UN_IMM:
1726                 return OP_IREM_UN;
1727         case OP_IREM_IMM:
1728                 return OP_IREM;
1729         case OP_DIV_IMM:
1730 #if SIZEOF_VOID_P == 4
1731                 return OP_IDIV;
1732 #else
1733                 return OP_LDIV;
1734 #endif
1735         case OP_REM_IMM:
1736 #if SIZEOF_VOID_P == 4
1737                 return OP_IREM;
1738 #else
1739                 return OP_LREM;
1740 #endif
1741         case OP_ADDCC_IMM:
1742                 return OP_ADDCC;
1743         case OP_ADC_IMM:
1744                 return OP_ADC;
1745         case OP_SUBCC_IMM:
1746                 return OP_SUBCC;
1747         case OP_SBB_IMM:
1748                 return OP_SBB;
1749         case OP_IADC_IMM:
1750                 return OP_IADC;
1751         case OP_ISBB_IMM:
1752                 return OP_ISBB;
1753         case OP_COMPARE_IMM:
1754                 return OP_COMPARE;
1755         case OP_ICOMPARE_IMM:
1756                 return OP_ICOMPARE;
1757         default:
1758                 printf ("%s\n", mono_inst_name (opcode));
1759                 g_assert_not_reached ();
1760         }
1761 }
1762
1763 /*
1764  * mono_decompose_op_imm:
1765  *
1766  *   Replace the OP_.._IMM INS with its non IMM variant.
1767  */
1768 void
1769 mono_decompose_op_imm (MonoCompile *cfg, MonoInst *ins)
1770 {
1771         MonoInst *temp;
1772
1773         MONO_INST_NEW (cfg, temp, OP_ICONST);
1774         temp->inst_c0 = ins->inst_imm;
1775         temp->dreg = mono_regstate_next_int (cfg->rs);
1776         MONO_INST_LIST_ADD_TAIL (&(temp)->node, &(ins)->node);
1777         ins->opcode = mono_op_imm_to_op (ins->opcode);
1778         ins->sreg2 = temp->dreg;
1779 }
1780
1781 /*
1782  * When we need a pointer to the current domain many times in a method, we
1783  * call mono_domain_get() once and we store the result in a local variable.
1784  * This function returns the variable that represents the MonoDomain*.
1785  */
1786 inline static MonoInst *
1787 mono_get_domainvar (MonoCompile *cfg)
1788 {
1789         if (!cfg->domainvar)
1790                 cfg->domainvar = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1791         return cfg->domainvar;
1792 }
1793
1794 /*
1795  * The got_var contains the address of the Global Offset Table when AOT 
1796  * compiling.
1797  */
1798 inline static MonoInst *
1799 mono_get_got_var (MonoCompile *cfg)
1800 {
1801 #ifdef MONO_ARCH_NEED_GOT_VAR
1802         if (!cfg->compile_aot)
1803                 return NULL;
1804         if (!cfg->got_var) {
1805                 cfg->got_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1806         }
1807         return cfg->got_var;
1808 #else
1809         return NULL;
1810 #endif
1811 }
1812
1813 static MonoInst *
1814 mono_get_rgctx_var (MonoCompile *cfg)
1815 {
1816         g_assert (cfg->generic_sharing_context);
1817
1818         if (!cfg->rgctx_var) {
1819                 cfg->rgctx_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1820                 /* force the var to be stack allocated */
1821                 cfg->rgctx_var->flags |= MONO_INST_INDIRECT;
1822         }
1823
1824         return cfg->rgctx_var;
1825 }
1826
1827 MonoInst*
1828 mono_compile_create_var (MonoCompile *cfg, MonoType *type, int opcode)
1829 {
1830         MonoInst *inst;
1831         int num = cfg->num_varinfo;
1832
1833         if ((num + 1) >= cfg->varinfo_count) {
1834                 int orig_count = cfg->varinfo_count;
1835                 cfg->varinfo_count = (cfg->varinfo_count + 2) * 2;
1836                 cfg->varinfo = (MonoInst **)g_realloc (cfg->varinfo, sizeof (MonoInst*) * cfg->varinfo_count);
1837                 cfg->vars = (MonoMethodVar *)g_realloc (cfg->vars, sizeof (MonoMethodVar) * cfg->varinfo_count);
1838                 memset (&cfg->vars [orig_count], 0, (cfg->varinfo_count - orig_count) * sizeof (MonoMethodVar));
1839         }
1840
1841         /*g_print ("created temp %d of type 0x%x\n", num, type->type);*/
1842         mono_jit_stats.allocate_var++;
1843
1844         MONO_INST_NEW (cfg, inst, opcode);
1845         inst->inst_c0 = num;
1846         inst->inst_vtype = type;
1847         inst->klass = mono_class_from_mono_type (type);
1848         /* if set to 1 the variable is native */
1849         inst->backend.is_pinvoke = 0;
1850
1851         cfg->varinfo [num] = inst;
1852
1853         MONO_INIT_VARINFO (&cfg->vars [num], num);
1854
1855         cfg->num_varinfo++;
1856         if (cfg->verbose_level > 2)
1857                 g_print ("created temp %d of type %s\n", num, mono_type_get_name (type));
1858         return inst;
1859 }
1860
1861 /*
1862  * Transform a MonoInst into a load from the variable of index var_index.
1863  */
1864 void
1865 mono_compile_make_var_load (MonoCompile *cfg, MonoInst *dest, gssize var_index) {
1866         memset (dest, 0, sizeof (MonoInst));
1867         dest->ssa_op = MONO_SSA_LOAD;
1868         dest->inst_i0 = cfg->varinfo [var_index];
1869         dest->opcode = mini_type_to_ldind (cfg, dest->inst_i0->inst_vtype);
1870         type_to_eval_stack_type (cfg, dest->inst_i0->inst_vtype, dest);
1871         dest->klass = dest->inst_i0->klass;
1872 }
1873
1874 /*
1875  * Create a MonoInst that is a load from the variable of index var_index.
1876  */
1877 MonoInst*
1878 mono_compile_create_var_load (MonoCompile *cfg, gssize var_index) {
1879         MonoInst *dest;
1880         NEW_TEMPLOAD (cfg,dest,var_index);
1881         return dest;
1882 }
1883
1884 /*
1885  * Create a MonoInst that is a store of the given value into the variable of index var_index.
1886  */
1887 MonoInst*
1888 mono_compile_create_var_store (MonoCompile *cfg, gssize var_index, MonoInst *value) {
1889         MonoInst *dest;
1890         NEW_TEMPSTORE (cfg, dest, var_index, value);
1891         return dest;
1892 }
1893
1894 static MonoType*
1895 type_from_stack_type (MonoInst *ins) {
1896         switch (ins->type) {
1897         case STACK_I4: return &mono_defaults.int32_class->byval_arg;
1898         case STACK_I8: return &mono_defaults.int64_class->byval_arg;
1899         case STACK_PTR: return &mono_defaults.int_class->byval_arg;
1900         case STACK_R8: return &mono_defaults.double_class->byval_arg;
1901         case STACK_MP:
1902                 /* 
1903                  * this if used to be commented without any specific reason, but
1904                  * it breaks #80235 when commented
1905                  */
1906                 if (ins->klass)
1907                         return &ins->klass->this_arg;
1908                 else
1909                         return &mono_defaults.object_class->this_arg;
1910         case STACK_OBJ:
1911                 /* ins->klass may not be set for ldnull.
1912                  * Also, if we have a boxed valuetype, we want an object lass,
1913                  * not the valuetype class
1914                  */
1915                 if (ins->klass && !ins->klass->valuetype)
1916                         return &ins->klass->byval_arg;
1917                 return &mono_defaults.object_class->byval_arg;
1918         case STACK_VTYPE: return &ins->klass->byval_arg;
1919         default:
1920                 g_error ("stack type %d to montype not handled\n", ins->type);
1921         }
1922         return NULL;
1923 }
1924
1925 MonoType*
1926 mono_type_from_stack_type (MonoInst *ins) {
1927         return type_from_stack_type (ins);
1928 }
1929
1930 static MonoClass*
1931 array_access_to_klass (int opcode, MonoInst *array_obj)
1932 {
1933         switch (opcode) {
1934         case CEE_LDELEM_U1:
1935                 return mono_defaults.byte_class;
1936         case CEE_LDELEM_U2:
1937                 return mono_defaults.uint16_class;
1938         case CEE_LDELEM_I:
1939         case CEE_STELEM_I:
1940                 return mono_defaults.int_class;
1941         case CEE_LDELEM_I1:
1942         case CEE_STELEM_I1:
1943                 return mono_defaults.sbyte_class;
1944         case CEE_LDELEM_I2:
1945         case CEE_STELEM_I2:
1946                 return mono_defaults.int16_class;
1947         case CEE_LDELEM_I4:
1948         case CEE_STELEM_I4:
1949                 return mono_defaults.int32_class;
1950         case CEE_LDELEM_U4:
1951                 return mono_defaults.uint32_class;
1952         case CEE_LDELEM_I8:
1953         case CEE_STELEM_I8:
1954                 return mono_defaults.int64_class;
1955         case CEE_LDELEM_R4:
1956         case CEE_STELEM_R4:
1957                 return mono_defaults.single_class;
1958         case CEE_LDELEM_R8:
1959         case CEE_STELEM_R8:
1960                 return mono_defaults.double_class;
1961         case CEE_LDELEM_REF:
1962         case CEE_STELEM_REF: {
1963                 MonoClass *klass = array_obj->klass;
1964                 /* FIXME: add assert */
1965                 if (klass && klass->rank)
1966                         return klass->element_class;
1967                 return mono_defaults.object_class;
1968         }
1969         default:
1970                 g_assert_not_reached ();
1971         }
1972         return NULL;
1973 }
1974
1975 void
1976 mono_add_ins_to_end (MonoBasicBlock *bb, MonoInst *inst)
1977 {
1978         MonoInst *last = mono_inst_list_last (&bb->ins_list);
1979
1980         if (last && ((last->opcode >= CEE_BEQ &&
1981                         last->opcode <= CEE_BLT_UN) ||
1982                         last->opcode == OP_BR ||
1983                         last->opcode == OP_SWITCH)) {
1984                 MONO_INST_LIST_ADD_TAIL (&inst->node, &last->node);
1985         } else {
1986                 MONO_ADD_INS (bb, inst);
1987         }
1988 }
1989
1990 void
1991 mono_add_varcopy_to_end (MonoCompile *cfg, MonoBasicBlock *bb, int src, int dest)
1992 {
1993         MonoInst *inst, *load;
1994
1995         NEW_TEMPLOAD (cfg, load, src);
1996
1997         NEW_TEMPSTORE (cfg, inst, dest, load);
1998         /* FIXME: handle CEE_STIND_R4 */
1999         if (inst->opcode == CEE_STOBJ) {
2000                 NEW_TEMPLOADA (cfg, inst, dest);
2001                 handle_stobj (cfg, bb, inst, load, NULL, inst->klass, TRUE, FALSE, FALSE);
2002         } else {
2003                 inst->cil_code = NULL;
2004                 mono_add_ins_to_end (bb, inst);
2005         }
2006 }
2007
2008 /*
2009  * merge_stacks:
2010  *
2011  * Merge stack state between two basic blocks according to Ecma 335, Partition III,
2012  * section 1.8.1.1. Store the resulting stack state into stack_2.
2013  * Returns: TRUE, if verification succeeds, FALSE otherwise.
2014  * FIXME: We should store the stack state in a dedicated structure instead of in
2015  * MonoInst's.
2016  */
2017 static gboolean
2018 merge_stacks (MonoCompile *cfg, MonoStackSlot *state_1, MonoStackSlot *state_2, guint32 size)
2019 {
2020         int i;
2021
2022         if (cfg->dont_verify_stack_merge)
2023                 return TRUE;
2024
2025         /* FIXME: Implement all checks from the spec */
2026
2027         for (i = 0; i < size; ++i) {
2028                 MonoStackSlot *slot1 = &state_1 [i];
2029                 MonoStackSlot *slot2 = &state_2 [i];
2030
2031                 if (slot1->type != slot2->type)
2032                         return FALSE;
2033
2034                 switch (slot1->type) {
2035                 case STACK_PTR:
2036                         /* FIXME: Perform merge ? */
2037                         /* klass == NULL means a native int */
2038                         if (slot1->klass && slot2->klass) {
2039                                 if (slot1->klass != slot2->klass)
2040                                         return FALSE;
2041                         }
2042                         break;
2043                 case STACK_MP:
2044                         /* FIXME: Change this to an assert and fix the JIT to allways fill this */
2045                         if (slot1->klass && slot2->klass) {
2046                                 if (slot1->klass != slot2->klass)
2047                                         return FALSE;
2048                         }
2049                         break;
2050                 case STACK_OBJ: {
2051                         MonoClass *klass1 = slot1->klass;
2052                         MonoClass *klass2 = slot2->klass;
2053
2054                         if (!klass1) {
2055                                 /* slot1 is ldnull */
2056                         } else if (!klass2) {
2057                                 /* slot2 is ldnull */
2058                                 slot2->klass = slot1->klass;
2059                         }
2060                         break;
2061                 }
2062                 }
2063         }
2064
2065         return TRUE;
2066 }
2067
2068 /*
2069  * This function is called to handle items that are left on the evaluation stack
2070  * at basic block boundaries. What happens is that we save the values to local variables
2071  * and we reload them later when first entering the target basic block (with the
2072  * handle_loaded_temps () function).
2073  * It is also used to handle items on the stack in store opcodes, since it is
2074  * possible that the variable to be stored into is already on the stack, in
2075  * which case its old value should be used.
2076  * A single joint point will use the same variables (stored in the array bb->out_stack or
2077  * bb->in_stack, if the basic block is before or after the joint point).
2078  * If the stack merge fails at a join point, cfg->unverifiable is set.
2079  */
2080 static int
2081 handle_stack_args (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst **sp, int count) {
2082         int i, bindex;
2083         MonoBasicBlock *outb;
2084         MonoInst *inst, **locals;
2085         MonoStackSlot *stack_state;
2086         gboolean found;
2087
2088         if (!count)
2089                 return 0;
2090         if (cfg->verbose_level > 3)
2091                 g_print ("%d item(s) on exit from B%d\n", count, bb->block_num);
2092
2093         stack_state = mono_mempool_alloc (cfg->mempool, sizeof (MonoStackSlot) * count);
2094         for (i = 0; i < count; ++i) {
2095                 stack_state [i].type = sp [i]->type;
2096                 stack_state [i].klass = sp [i]->klass;
2097
2098                 /* Check that instructions other than ldnull have ins->klass set */
2099                 if (!cfg->dont_verify_stack_merge && (sp [i]->type == STACK_OBJ) && !((sp [i]->opcode == OP_PCONST) && sp [i]->inst_c0 == 0))
2100                         g_assert (sp [i]->klass);
2101         }
2102
2103         /* Perform verification and stack state merge */
2104         for (i = 0; i < bb->out_count; ++i) {
2105                 outb = bb->out_bb [i];
2106
2107                 /* exception handlers are linked, but they should not be considered for stack args */
2108                 if (outb->flags & BB_EXCEPTION_HANDLER)
2109                         continue;
2110                 if (outb->stack_state) {
2111                         gboolean verified;
2112
2113                         if (count != outb->in_scount) {
2114                                 cfg->unverifiable = TRUE;
2115                                 return 0;
2116                         }
2117                         verified = merge_stacks (cfg, stack_state, outb->stack_state, count);
2118                         if (!verified) {
2119                                 cfg->unverifiable = TRUE;
2120                                 return 0;
2121                         }
2122
2123                         if (cfg->verbose_level > 3) {
2124                                 int j;
2125
2126                                 for (j = 0; j < count; ++j)
2127                                         printf ("\tStack state of BB%d, slot %d=%d\n", outb->block_num, j, outb->stack_state [j].type);
2128                         }
2129                 } else {
2130                         /* Make a copy of the stack state */
2131                         outb->stack_state = mono_mempool_alloc (cfg->mempool, sizeof (MonoStackSlot) * count);
2132                         memcpy (outb->stack_state, stack_state, sizeof (MonoStackSlot) * count);
2133                 }
2134         }
2135
2136         if (!bb->out_scount) {
2137                 bb->out_scount = count;
2138                 //g_print ("bblock %d has out:", bb->block_num);
2139                 found = FALSE;
2140                 for (i = 0; i < bb->out_count; ++i) {
2141                         outb = bb->out_bb [i];
2142                         /* exception handlers are linked, but they should not be considered for stack args */
2143                         if (outb->flags & BB_EXCEPTION_HANDLER)
2144                                 continue;
2145                         //g_print (" %d", outb->block_num);
2146                         if (outb->in_stack) {
2147                                 found = TRUE;
2148                                 bb->out_stack = outb->in_stack;
2149                                 break;
2150                         }
2151                 }
2152                 //g_print ("\n");
2153                 if (!found) {
2154                         bb->out_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * count);
2155                         for (i = 0; i < count; ++i) {
2156                                 /* 
2157                                  * try to reuse temps already allocated for this purpouse, if they occupy the same
2158                                  * stack slot and if they are of the same type.
2159                                  * This won't cause conflicts since if 'local' is used to 
2160                                  * store one of the values in the in_stack of a bblock, then
2161                                  * the same variable will be used for the same outgoing stack 
2162                                  * slot as well. 
2163                                  * This doesn't work when inlining methods, since the bblocks
2164                                  * in the inlined methods do not inherit their in_stack from
2165                                  * the bblock they are inlined to. See bug #58863 for an
2166                                  * example.
2167                                  * This hack is disabled since it also prevents proper tracking of types.
2168                                  */
2169 #if 1
2170                                 bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
2171 #else
2172                                 if (cfg->inlined_method)
2173                                         bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
2174                                 else
2175                                         bb->out_stack [i] = mono_compile_get_interface_var (cfg, i, sp [i]);
2176 #endif
2177                         }
2178                 }
2179         }
2180
2181         for (i = 0; i < bb->out_count; ++i) {
2182                 outb = bb->out_bb [i];
2183                 /* exception handlers are linked, but they should not be considered for stack args */
2184                 if (outb->flags & BB_EXCEPTION_HANDLER)
2185                         continue;
2186                 if (outb->in_scount) {
2187                         if (outb->in_scount != bb->out_scount)
2188                                 G_BREAKPOINT ();
2189                         continue; /* check they are the same locals */
2190                 }
2191                 outb->in_scount = count;
2192                 outb->in_stack = bb->out_stack;
2193         }
2194
2195         locals = bb->out_stack;
2196         for (i = 0; i < count; ++i) {
2197                 /* add store ops at the end of the bb, before the branch */
2198                 NEW_TEMPSTORE (cfg, inst, locals [i]->inst_c0, sp [i]);
2199                 if (inst->opcode == CEE_STOBJ) {
2200                         NEW_TEMPLOADA (cfg, inst, locals [i]->inst_c0);
2201                         handle_stobj (cfg, bb, inst, sp [i], sp [i]->cil_code, inst->klass, TRUE, FALSE, FALSE);
2202                 } else {
2203                         inst->cil_code = sp [i]->cil_code;
2204                         mono_add_ins_to_end (bb, inst);
2205                 }
2206                 if (cfg->verbose_level > 3)
2207                         g_print ("storing %d to temp %d\n", i, (int)locals [i]->inst_c0);
2208         }
2209
2210         /*
2211          * It is possible that the out bblocks already have in_stack assigned, and
2212          * the in_stacks differ. In this case, we will store to all the different 
2213          * in_stacks.
2214          */
2215
2216         found = TRUE;
2217         bindex = 0;
2218         while (found) {
2219                 /* Find a bblock which has a different in_stack */
2220                 found = FALSE;
2221                 while (bindex < bb->out_count) {
2222                         outb = bb->out_bb [bindex];
2223                         /* exception handlers are linked, but they should not be considered for stack args */
2224                         if (outb->flags & BB_EXCEPTION_HANDLER) {
2225                                 bindex++;
2226                                 continue;
2227                         }
2228                         if (outb->in_stack != locals) {
2229                                 /* 
2230                                  * Instead of storing sp [i] to locals [i], we need to store
2231                                  * locals [i] to <new locals>[i], since the sp [i] tree can't
2232                                  * be shared between trees.
2233                                  */
2234                                 for (i = 0; i < count; ++i)
2235                                         mono_add_varcopy_to_end (cfg, bb, locals [i]->inst_c0, outb->in_stack [i]->inst_c0);
2236                                 locals = outb->in_stack;
2237                                 found = TRUE;
2238                                 break;
2239                         }
2240                         bindex ++;
2241                 }
2242         }
2243         
2244         return 0;
2245 }
2246
2247 static int
2248 ret_type_to_call_opcode (MonoType *type, int calli, int virt, MonoGenericSharingContext *gsctx)
2249 {
2250         if (type->byref)
2251                 return calli? OP_CALL_REG: virt? OP_CALLVIRT: OP_CALL;
2252
2253 handle_enum:
2254         type = mini_get_basic_type_from_generic (gsctx, type);
2255         switch (type->type) {
2256         case MONO_TYPE_VOID:
2257                 return calli? OP_VOIDCALL_REG: virt? OP_VOIDCALLVIRT: OP_VOIDCALL;
2258         case MONO_TYPE_I1:
2259         case MONO_TYPE_U1:
2260         case MONO_TYPE_BOOLEAN:
2261         case MONO_TYPE_I2:
2262         case MONO_TYPE_U2:
2263         case MONO_TYPE_CHAR:
2264         case MONO_TYPE_I4:
2265         case MONO_TYPE_U4:
2266                 return calli? OP_CALL_REG: virt? OP_CALLVIRT: OP_CALL;
2267         case MONO_TYPE_I:
2268         case MONO_TYPE_U:
2269         case MONO_TYPE_PTR:
2270         case MONO_TYPE_FNPTR:
2271                 return calli? OP_CALL_REG: virt? OP_CALLVIRT: OP_CALL;
2272         case MONO_TYPE_CLASS:
2273         case MONO_TYPE_STRING:
2274         case MONO_TYPE_OBJECT:
2275         case MONO_TYPE_SZARRAY:
2276         case MONO_TYPE_ARRAY:    
2277                 return calli? OP_CALL_REG: virt? OP_CALLVIRT: OP_CALL;
2278         case MONO_TYPE_I8:
2279         case MONO_TYPE_U8:
2280                 return calli? OP_LCALL_REG: virt? OP_LCALLVIRT: OP_LCALL;
2281         case MONO_TYPE_R4:
2282         case MONO_TYPE_R8:
2283                 return calli? OP_FCALL_REG: virt? OP_FCALLVIRT: OP_FCALL;
2284         case MONO_TYPE_VALUETYPE:
2285                 if (type->data.klass->enumtype) {
2286                         type = type->data.klass->enum_basetype;
2287                         goto handle_enum;
2288                 } else
2289                         return calli? OP_VCALL_REG: virt? OP_VCALLVIRT: OP_VCALL;
2290         case MONO_TYPE_TYPEDBYREF:
2291                 return calli? OP_VCALL_REG: virt? OP_VCALLVIRT: OP_VCALL;
2292         case MONO_TYPE_GENERICINST:
2293                 type = &type->data.generic_class->container_class->byval_arg;
2294                 goto handle_enum;
2295         default:
2296                 g_error ("unknown type 0x%02x in ret_type_to_call_opcode", type->type);
2297         }
2298         return -1;
2299 }
2300
2301 void
2302 mono_create_jump_table (MonoCompile *cfg, MonoInst *label, MonoBasicBlock **bbs, int num_blocks)
2303 {
2304         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
2305         MonoJumpInfoBBTable *table;
2306
2307         table = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfoBBTable));
2308         table->table = bbs;
2309         table->table_size = num_blocks;
2310         
2311         ji->ip.label = label;
2312         ji->type = MONO_PATCH_INFO_SWITCH;
2313         ji->data.table = table;
2314         ji->next = cfg->patch_info;
2315         cfg->patch_info = ji;
2316 }
2317
2318 static void
2319 mono_save_token_info (MonoCompile *cfg, MonoImage *image, guint32 token, gpointer key)
2320 {
2321         if (cfg->compile_aot) {
2322                 MonoJumpInfoToken *jump_info_token = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoToken));
2323                 jump_info_token->image = image;
2324                 jump_info_token->token = token;
2325                 g_hash_table_insert (cfg->token_info_hash, key, jump_info_token);
2326         }
2327 }
2328
2329 /*
2330  * When we add a tree of instructions, we need to ensure the instructions currently
2331  * on the stack are executed before (like, if we load a value from a local).
2332  * We ensure this by saving the currently loaded values to temps and rewriting the
2333  * instructions to load the values.
2334  * This is not done for opcodes that terminate a basic block (because it's handled already
2335  * by handle_stack_args ()) and for opcodes that can't change values, like POP.
2336  */
2337 static void
2338 handle_loaded_temps (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst **stack, MonoInst **sp)
2339 {
2340         MonoInst *load, *store, *temp, *ins;
2341
2342         while (stack < sp) {
2343                 ins = *stack;
2344                 /* handle also other constants */
2345                 if ((ins->opcode != OP_ICONST) &&
2346                     /* temps never get written to again, so we can safely avoid duplicating them */
2347                     !(ins->ssa_op == MONO_SSA_LOAD && ins->inst_i0->opcode == OP_LOCAL && ins->inst_i0->flags & MONO_INST_IS_TEMP)) {
2348                         temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
2349                         temp->flags |= MONO_INST_IS_TEMP;
2350                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2351                         store->cil_code = ins->cil_code;
2352                         if (store->opcode == CEE_STOBJ) {
2353                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
2354                                 handle_stobj (cfg, bblock, store, ins, ins->cil_code, temp->klass, FALSE, FALSE, FALSE);
2355                         } else
2356                                 MONO_ADD_INS (bblock, store);
2357                         NEW_TEMPLOAD (cfg, load, temp->inst_c0);
2358                         load->cil_code = ins->cil_code;
2359                         *stack = load;
2360                 }
2361                 stack++;
2362         }
2363 }
2364
2365 /*
2366  * target_type_is_incompatible:
2367  * @cfg: MonoCompile context
2368  *
2369  * Check that the item @arg on the evaluation stack can be stored
2370  * in the target type (can be a local, or field, etc).
2371  * The cfg arg can be used to check if we need verification or just
2372  * validity checks.
2373  *
2374  * Returns: non-0 value if arg can't be stored on a target.
2375  */
2376 static int
2377 target_type_is_incompatible (MonoCompile *cfg, MonoType *target, MonoInst *arg)
2378 {
2379         MonoType *simple_type;
2380         MonoClass *klass;
2381
2382         if (target->byref) {
2383                 /* FIXME: check that the pointed to types match */
2384                 if (arg->type == STACK_MP)
2385                         return arg->klass != mono_class_from_mono_type (target);
2386                 if (arg->type == STACK_PTR)
2387                         return 0;
2388                 return 1;
2389         }
2390         simple_type = mono_type_get_underlying_type (target);
2391         switch (simple_type->type) {
2392         case MONO_TYPE_VOID:
2393                 return 1;
2394         case MONO_TYPE_I1:
2395         case MONO_TYPE_U1:
2396         case MONO_TYPE_BOOLEAN:
2397         case MONO_TYPE_I2:
2398         case MONO_TYPE_U2:
2399         case MONO_TYPE_CHAR:
2400         case MONO_TYPE_I4:
2401         case MONO_TYPE_U4:
2402                 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
2403                         return 1;
2404                 return 0;
2405         case MONO_TYPE_PTR:
2406                 /* STACK_MP is needed when setting pinned locals */
2407                 if (arg->type != STACK_I4 && arg->type != STACK_PTR && arg->type != STACK_MP)
2408                         return 1;
2409                 return 0;
2410         case MONO_TYPE_I:
2411         case MONO_TYPE_U:
2412         case MONO_TYPE_FNPTR:
2413                 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
2414                         return 1;
2415                 return 0;
2416         case MONO_TYPE_OBJECT:
2417                 if (arg->type != STACK_OBJ)
2418                         return 1;
2419                 return 0;
2420         case MONO_TYPE_STRING:
2421                 if (arg->type != STACK_OBJ)
2422                         return 1;
2423                 /* ldnull has arg->klass unset */
2424                 /*if (arg->klass && arg->klass != mono_defaults.string_class) {
2425                         G_BREAKPOINT ();
2426                         return 1;
2427                 }*/
2428                 return 0;
2429         case MONO_TYPE_CLASS:
2430         case MONO_TYPE_SZARRAY:
2431         case MONO_TYPE_ARRAY:    
2432                 if (arg->type != STACK_OBJ)
2433                         return 1;
2434                 /* FIXME: check type compatibility */
2435                 return 0;
2436         case MONO_TYPE_I8:
2437         case MONO_TYPE_U8:
2438                 if (arg->type != STACK_I8)
2439                         return 1;
2440                 return 0;
2441         case MONO_TYPE_R4:
2442         case MONO_TYPE_R8:
2443                 if (arg->type != STACK_R8)
2444                         return 1;
2445                 return 0;
2446         case MONO_TYPE_VALUETYPE:
2447                 if (arg->type != STACK_VTYPE)
2448                         return 1;
2449                 klass = mono_class_from_mono_type (simple_type);
2450                 if (klass != arg->klass)
2451                         return 1;
2452                 return 0;
2453         case MONO_TYPE_TYPEDBYREF:
2454                 if (arg->type != STACK_VTYPE)
2455                         return 1;
2456                 klass = mono_class_from_mono_type (simple_type);
2457                 if (klass != arg->klass)
2458                         return 1;
2459                 return 0;
2460         case MONO_TYPE_GENERICINST:
2461                 if (mono_type_generic_inst_is_valuetype (simple_type)) {
2462                         klass = mono_class_from_mono_type (simple_type);
2463                         if (klass->enumtype)
2464                                 return target_type_is_incompatible (cfg, klass->enum_basetype, arg);
2465                         if (arg->type != STACK_VTYPE)
2466                                 return 1;
2467                         if (klass != arg->klass)
2468                                 return 1;
2469                         return 0;
2470                 } else {
2471                         if (arg->type != STACK_OBJ)
2472                                 return 1;
2473                         /* FIXME: check type compatibility */
2474                         return 0;
2475                 }
2476         case MONO_TYPE_VAR:
2477         case MONO_TYPE_MVAR:
2478                 /* FIXME: all the arguments must be references for now,
2479                  * later look inside cfg and see if the arg num is
2480                  * really a reference
2481                  */
2482                 g_assert (cfg->generic_sharing_context);
2483                 if (arg->type != STACK_OBJ)
2484                         return 1;
2485                 return 0;
2486         default:
2487                 g_error ("unknown type 0x%02x in target_type_is_incompatible", simple_type->type);
2488         }
2489         return 1;
2490 }
2491
2492 /*
2493  * Prepare arguments for passing to a function call.
2494  * Return a non-zero value if the arguments can't be passed to the given
2495  * signature.
2496  * The type checks are not yet complete and some conversions may need
2497  * casts on 32 or 64 bit architectures.
2498  *
2499  * FIXME: implement this using target_type_is_incompatible ()
2500  */
2501 static int
2502 check_call_signature (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args)
2503 {
2504         MonoType *simple_type;
2505         int i;
2506
2507         if (sig->hasthis) {
2508                 if (args [0]->type != STACK_OBJ && args [0]->type != STACK_MP && args [0]->type != STACK_PTR)
2509                         return 1;
2510                 args++;
2511         }
2512         for (i = 0; i < sig->param_count; ++i) {
2513                 if (sig->params [i]->byref) {
2514                         if (args [i]->type != STACK_MP && args [i]->type != STACK_PTR)
2515                                 return 1;
2516                         continue;
2517                 }
2518                 simple_type = sig->params [i];
2519                 simple_type = mini_get_basic_type_from_generic (cfg->generic_sharing_context, simple_type);
2520 handle_enum:
2521                 switch (simple_type->type) {
2522                 case MONO_TYPE_VOID:
2523                         return 1;
2524                         continue;
2525                 case MONO_TYPE_I1:
2526                 case MONO_TYPE_U1:
2527                 case MONO_TYPE_BOOLEAN:
2528                 case MONO_TYPE_I2:
2529                 case MONO_TYPE_U2:
2530                 case MONO_TYPE_CHAR:
2531                 case MONO_TYPE_I4:
2532                 case MONO_TYPE_U4:
2533                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR)
2534                                 return 1;
2535                         continue;
2536                 case MONO_TYPE_I:
2537                 case MONO_TYPE_U:
2538                 case MONO_TYPE_PTR:
2539                 case MONO_TYPE_FNPTR:
2540                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR && args [i]->type != STACK_MP && args [i]->type != STACK_OBJ)
2541                                 return 1;
2542                         continue;
2543                 case MONO_TYPE_CLASS:
2544                 case MONO_TYPE_STRING:
2545                 case MONO_TYPE_OBJECT:
2546                 case MONO_TYPE_SZARRAY:
2547                 case MONO_TYPE_ARRAY:    
2548                         if (args [i]->type != STACK_OBJ)
2549                                 return 1;
2550                         continue;
2551                 case MONO_TYPE_I8:
2552                 case MONO_TYPE_U8:
2553                         if (args [i]->type != STACK_I8)
2554                                 return 1;
2555                         continue;
2556                 case MONO_TYPE_R4:
2557                 case MONO_TYPE_R8:
2558                         if (args [i]->type != STACK_R8)
2559                                 return 1;
2560                         continue;
2561                 case MONO_TYPE_VALUETYPE:
2562                         if (simple_type->data.klass->enumtype) {
2563                                 simple_type = simple_type->data.klass->enum_basetype;
2564                                 goto handle_enum;
2565                         }
2566                         if (args [i]->type != STACK_VTYPE)
2567                                 return 1;
2568                         continue;
2569                 case MONO_TYPE_TYPEDBYREF:
2570                         if (args [i]->type != STACK_VTYPE)
2571                                 return 1;
2572                         continue;
2573                 case MONO_TYPE_GENERICINST:
2574                         simple_type = &simple_type->data.generic_class->container_class->byval_arg;
2575                         goto handle_enum;
2576
2577                 default:
2578                         g_error ("unknown type 0x%02x in check_call_signature",
2579                                  simple_type->type);
2580                 }
2581         }
2582         return 0;
2583 }
2584
2585 inline static int
2586 mono_spill_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoCallInst *call, MonoMethodSignature *sig, gboolean ret_object, 
2587                  const guint8 *ip, gboolean to_end)
2588 {
2589         MonoInst *temp, *store, *ins = (MonoInst*)call;
2590         MonoType *ret = sig->ret;
2591
2592         if (!MONO_TYPE_IS_VOID (ret) || ret_object) {
2593                 if (ret_object) {
2594                         call->inst.type = STACK_OBJ;
2595                         call->inst.opcode = OP_CALL;
2596                         temp = mono_compile_create_var (cfg, &mono_defaults.string_class->byval_arg, OP_LOCAL);
2597                 } else {
2598                         type_to_eval_stack_type (cfg, ret, ins);
2599                         temp = mono_compile_create_var (cfg, ret, OP_LOCAL);
2600                 }
2601                 
2602                 temp->flags |= MONO_INST_IS_TEMP;
2603
2604                 if (MONO_TYPE_ISSTRUCT (ret)) {
2605                         MonoInst *loada, *dummy_store;
2606
2607                         /* 
2608                          * Emit a dummy store to the local holding the result so the
2609                          * liveness info remains correct.
2610                          */
2611                         NEW_DUMMY_STORE (cfg, dummy_store, temp->inst_c0);
2612                         if (to_end)
2613                                 mono_add_ins_to_end (bblock, dummy_store);
2614                         else
2615                                 MONO_ADD_INS (bblock, dummy_store);
2616
2617                         /* we use this to allocate native sized structs */
2618                         temp->backend.is_pinvoke = sig->pinvoke;
2619
2620                         NEW_TEMPLOADA (cfg, loada, temp->inst_c0);
2621                         if (call->inst.opcode == OP_VCALL || call->inst.opcode == OP_VCALL_RGCTX)
2622                                 ins->inst_left = loada;
2623                         else
2624                                 ins->inst_right = loada; /* a virtual or indirect call */
2625
2626                         if (to_end)
2627                                 mono_add_ins_to_end (bblock, ins);
2628                         else
2629                                 MONO_ADD_INS (bblock, ins);
2630                 } else {
2631                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2632                         store->cil_code = ip;
2633                         
2634 #ifdef MONO_ARCH_SOFT_FLOAT
2635                         if (store->opcode == CEE_STIND_R4) {
2636                                 /*FIXME implement proper support for to_end*/
2637                                 g_assert (!to_end);
2638                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
2639                                 handle_store_float (cfg, bblock, store, ins, ip);
2640                         } else
2641 #endif
2642                         if (to_end)
2643                                 mono_add_ins_to_end (bblock, store);
2644                         else
2645                                 MONO_ADD_INS (bblock, store);
2646                 }
2647                 return temp->inst_c0;
2648         } else {
2649                 if (to_end)
2650                         mono_add_ins_to_end (bblock, ins);
2651                 else
2652                         MONO_ADD_INS (bblock, ins);
2653                 return -1;
2654         }
2655 }
2656
2657 inline static MonoCallInst *
2658 mono_emit_call_args (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, 
2659                      MonoInst **args, int calli, int virtual, const guint8 *ip, gboolean to_end)
2660 {
2661         MonoCallInst *call;
2662         MonoInst *arg, *n;
2663
2664         MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (sig->ret, calli, virtual, cfg->generic_sharing_context));
2665
2666 #ifdef MONO_ARCH_SOFT_FLOAT
2667         /* we need to convert the r4 value to an int value */
2668         {
2669                 int i;
2670                 for (i = 0; i < sig->param_count; ++i) {
2671                         if (!sig->params [i]->byref && sig->params [i]->type == MONO_TYPE_R4) {
2672                                 MonoInst *iargs [1];
2673                                 int temp;
2674                                 iargs [0] = args [i + sig->hasthis];
2675
2676                                 temp = mono_emit_jit_icall (cfg, bblock, mono_fload_r4_arg, iargs, ip);
2677                                 NEW_TEMPLOAD (cfg, arg, temp);
2678                                 args [i + sig->hasthis] = arg;
2679                         }
2680                 }
2681         }
2682 #endif
2683
2684         call->inst.cil_code = ip;
2685         call->args = args;
2686         call->signature = sig;
2687         call = mono_arch_call_opcode (cfg, bblock, call, virtual);
2688         type_to_eval_stack_type (cfg, sig->ret, &call->inst);
2689
2690         MONO_INST_LIST_FOR_EACH_ENTRY_SAFE (arg, n, &call->out_args, node) {
2691                 if (!arg->cil_code)
2692                         arg->cil_code = ip;
2693                 if (to_end)
2694                         mono_add_ins_to_end (bblock, arg);
2695                 else
2696                         MONO_ADD_INS (bblock, arg);
2697         }
2698         return call;
2699 }
2700
2701 inline static MonoCallInst*
2702 mono_emit_calli (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, 
2703                  MonoInst **args, MonoInst *addr, const guint8 *ip)
2704 {
2705         MonoCallInst *call = mono_emit_call_args (cfg, bblock, sig, args, TRUE, FALSE, ip, FALSE);
2706
2707         call->inst.inst_i0 = addr;
2708
2709         return call;
2710 }
2711
2712 inline static MonoCallInst*
2713 mono_emit_rgctx_calli (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig,
2714         MonoInst **args, MonoInst *addr, MonoInst *rgctx_arg, const guint8 *ip)
2715 {
2716         MonoCallInst *call = mono_emit_calli (cfg, bblock, sig, args, addr, ip);
2717
2718         if (rgctx_arg) {
2719                 switch (call->inst.opcode) {
2720                 case OP_CALL_REG: call->inst.opcode = OP_CALL_REG_RGCTX; break;
2721                 case OP_VOIDCALL_REG: call->inst.opcode = OP_VOIDCALL_REG_RGCTX; break;
2722                 case OP_FCALL_REG: call->inst.opcode = OP_FCALL_REG_RGCTX; break;
2723                 case OP_LCALL_REG: call->inst.opcode = OP_LCALL_REG_RGCTX; break;
2724                 case OP_VCALL_REG: {
2725                         MonoInst *group;
2726
2727                         NEW_GROUP (cfg, group, call->inst.inst_left, NULL);
2728                         call->inst.inst_left = group;
2729                         call->inst.opcode = OP_VCALL_REG_RGCTX;
2730                         break;
2731                 }
2732                 default: g_assert_not_reached ();
2733                 }
2734
2735                 if (call->inst.opcode != OP_VCALL_REG_RGCTX) {
2736                         g_assert (!call->inst.inst_right);
2737                         call->inst.inst_right = rgctx_arg;
2738                 } else {
2739                         g_assert (!call->inst.inst_left->inst_right);
2740                         call->inst.inst_left->inst_right = rgctx_arg;
2741                 }
2742         }
2743
2744         return call;
2745 }
2746
2747 inline static int
2748 mono_emit_calli_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, 
2749                                                  MonoInst **args, MonoInst *addr, const guint8 *ip)
2750 {
2751         MonoCallInst *call = mono_emit_calli (cfg, bblock, sig, args, addr, ip);
2752
2753         return mono_spill_call (cfg, bblock, call, sig, FALSE, ip, FALSE);
2754 }
2755
2756 static int
2757 mono_emit_rgctx_calli_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig,
2758         MonoInst **args, MonoInst *addr, MonoInst *rgctx_arg, const guint8 *ip)
2759 {
2760         MonoCallInst *call = mono_emit_rgctx_calli (cfg, bblock, sig, args, addr, rgctx_arg, ip);
2761
2762         return mono_spill_call (cfg, bblock, call, sig, FALSE, ip, FALSE);
2763 }
2764
2765 static MonoCallInst*
2766 mono_emit_method_call_full (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method, MonoMethodSignature *sig,
2767                        MonoInst **args, const guint8 *ip, MonoInst *this, gboolean to_end)
2768 {
2769         gboolean virtual = this != NULL;
2770         MonoCallInst *call;
2771
2772         call = mono_emit_call_args (cfg, bblock, sig, args, FALSE, virtual, ip, to_end);
2773
2774         if (this && sig->hasthis && 
2775             (method->klass->marshalbyref || method->klass == mono_defaults.object_class) && 
2776             !(method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !MONO_CHECK_THIS (this)) {
2777                 call->method = mono_marshal_get_remoting_invoke_with_check (method);
2778         } else {
2779                 call->method = method;
2780         }
2781         call->inst.flags |= MONO_INST_HAS_METHOD;
2782         call->inst.inst_left = this;
2783
2784         if (call->method->klass->flags & TYPE_ATTRIBUTE_INTERFACE)
2785                 /* Needed by the code generated in inssel.brg */
2786                 mono_get_got_var (cfg);
2787
2788         return call;
2789 }
2790
2791 static MonoCallInst*
2792 mono_emit_method_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method, MonoMethodSignature *sig,
2793                        MonoInst **args, const guint8 *ip, MonoInst *this)
2794 {
2795         return mono_emit_method_call_full (cfg, bblock, method, sig, args, ip, this, FALSE);
2796 }
2797
2798 inline static int
2799 mono_emit_method_call_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,  
2800                        MonoMethodSignature *signature, MonoInst **args, const guint8 *ip, MonoInst *this)
2801 {
2802         MonoCallInst *call = mono_emit_method_call (cfg, bblock, method, signature, args, ip, this);
2803
2804         return mono_spill_call (cfg, bblock, call, signature, method->string_ctor, ip, FALSE);
2805 }
2806
2807 inline static int
2808 mono_emit_method_call_spilled_full (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,  
2809                        MonoMethodSignature *signature, MonoInst **args, const guint8 *ip, MonoInst *this,
2810                        gboolean ret_object, gboolean to_end)
2811 {
2812         MonoCallInst *call = mono_emit_method_call_full (cfg, bblock, method, signature, args, ip, this, to_end);
2813
2814         return mono_spill_call (cfg, bblock, call, signature, ret_object, ip, to_end);
2815 }
2816
2817 inline static int
2818 mono_emit_native_call (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoMethodSignature *sig,
2819                        MonoInst **args, const guint8 *ip, gboolean ret_object, gboolean to_end)
2820 {
2821         MonoCallInst *call;
2822
2823         g_assert (sig);
2824
2825         call = mono_emit_call_args (cfg, bblock, sig, args, FALSE, FALSE, ip, to_end);
2826         call->fptr = func;
2827
2828         return mono_spill_call (cfg, bblock, call, sig, ret_object, ip, to_end);
2829 }
2830
2831 inline static int
2832 mono_emit_jit_icall (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoInst **args, const guint8 *ip)
2833 {
2834         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (func);
2835         
2836         if (!info) {
2837                 g_warning ("unregistered JIT ICall");
2838                 g_assert_not_reached ();
2839         }
2840
2841         return mono_emit_native_call (cfg, bblock, mono_icall_get_wrapper (info), info->sig, args, ip, FALSE, FALSE);
2842 }
2843
2844 static MonoCallInst*
2845 mono_emit_rgctx_method_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method, MonoMethodSignature *sig,
2846                 MonoInst **args, MonoInst *rgctx_arg, const guint8 *ip, MonoInst *this)
2847 {
2848         MonoCallInst *call = mono_emit_method_call_full (cfg, bblock, method, sig, args, ip, this, FALSE);
2849
2850         if (rgctx_arg) {
2851                 switch (call->inst.opcode) {
2852                 case OP_CALL: call->inst.opcode = OP_CALL_RGCTX; break;
2853                 case OP_VOIDCALL: call->inst.opcode = OP_VOIDCALL_RGCTX; break;
2854                 case OP_FCALL: call->inst.opcode = OP_FCALL_RGCTX; break;
2855                 case OP_LCALL: call->inst.opcode = OP_LCALL_RGCTX; break;
2856                 case OP_VCALL: call->inst.opcode = OP_VCALL_RGCTX; break;
2857                 default: g_assert_not_reached ();
2858                 }
2859
2860                 if (call->inst.opcode != OP_VCALL_RGCTX) {
2861                         g_assert (!call->inst.inst_left);
2862                         call->inst.inst_left = rgctx_arg;
2863                 } else {
2864                         g_assert (!call->inst.inst_right);
2865                         call->inst.inst_right = rgctx_arg;
2866                 }
2867         }
2868
2869         return call;
2870 }
2871
2872 inline static int
2873 mono_emit_rgctx_method_call_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,  
2874                 MonoMethodSignature *signature, MonoInst **args, MonoInst *rgctx_arg, const guint8 *ip,
2875                 MonoInst *this)
2876 {
2877         MonoCallInst *call = mono_emit_rgctx_method_call (cfg, bblock, method, signature, args, rgctx_arg, ip, this);
2878
2879         return mono_spill_call (cfg, bblock, call, signature, method->string_ctor, ip, FALSE);
2880 }
2881
2882 static void
2883 mono_emulate_opcode (MonoCompile *cfg, MonoInst *tree, MonoInst **iargs, MonoJitICallInfo *info)
2884 {
2885         MonoInst *ins, *temp = NULL, *store, *load;
2886         MonoInstList *head, *list;
2887         int nargs;
2888         MonoCallInst *call;
2889
2890         //g_print ("emulating: ");
2891         //mono_print_tree_nl (tree);
2892         MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (info->sig->ret, FALSE, FALSE, cfg->generic_sharing_context));
2893         ins = (MonoInst*)call;
2894         MONO_INST_LIST_INIT (&ins->node);
2895         
2896         call->inst.cil_code = tree->cil_code;
2897         call->args = iargs;
2898         call->signature = info->sig;
2899
2900         call = mono_arch_call_opcode (cfg, cfg->cbb, call, FALSE);
2901
2902         if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
2903                 temp = mono_compile_create_var (cfg, info->sig->ret, OP_LOCAL);
2904                 temp->flags |= MONO_INST_IS_TEMP;
2905                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2906                 MONO_INST_LIST_INIT (&store->node);
2907                 /* FIXME: handle CEE_STIND_R4 */
2908                 store->cil_code = tree->cil_code;
2909         } else {
2910                 store = ins;
2911         }
2912
2913         nargs = info->sig->param_count + info->sig->hasthis;
2914
2915         if (nargs) {
2916                 MONO_INST_LIST_ADD_TAIL (&store->node,
2917                                         &call->out_args);
2918                 list = &call->out_args;
2919         } else {
2920                 list = &store->node;
2921         }
2922
2923         if (cfg->prev_ins) {
2924                 /* 
2925                  * This assumes that that in a tree, emulate_opcode is called for a
2926                  * node before it is called for its children. dec_foreach needs to
2927                  * take this into account.
2928                  */
2929                 head = &cfg->prev_ins->node;
2930         } else {
2931                 head = &cfg->cbb->ins_list;
2932         }
2933
2934         MONO_INST_LIST_SPLICE_INIT (list, head);
2935
2936         call->fptr = mono_icall_get_wrapper (info);
2937
2938         if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
2939                 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
2940                 *tree = *load;
2941         }
2942 }
2943
2944 /*
2945  * This entry point could be used later for arbitrary method
2946  * redirection.
2947  */
2948 inline static int
2949 mini_redirect_call (int *temp, MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,  
2950                        MonoMethodSignature *signature, MonoInst **args, const guint8 *ip, MonoInst *this)
2951 {
2952
2953         if (method->klass == mono_defaults.string_class) {
2954                 /* managed string allocation support */
2955                 if (strcmp (method->name, "InternalAllocateStr") == 0) {
2956                         MonoInst *iargs [2];
2957                         MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
2958                         MonoMethod *managed_alloc = mono_gc_get_managed_allocator (vtable, FALSE);
2959                         if (!managed_alloc)
2960                                 return FALSE;
2961                         NEW_VTABLECONST (cfg, iargs [0], vtable);
2962                         iargs [1] = args [0];
2963                         *temp = mono_emit_method_call_spilled (cfg, bblock, managed_alloc, mono_method_signature (managed_alloc), iargs, ip, this);
2964                         return TRUE;
2965                 }
2966         }
2967         return FALSE;
2968 }
2969
2970 static MonoMethodSignature *
2971 mono_get_array_new_va_signature (int arity)
2972 {
2973         static GHashTable *sighash = NULL;
2974         MonoMethodSignature *res;
2975         int i;
2976
2977         mono_jit_lock ();
2978         if (!sighash) {
2979                 sighash = g_hash_table_new (NULL, NULL);
2980         }
2981         else if ((res = g_hash_table_lookup (sighash, GINT_TO_POINTER (arity)))) {
2982                 mono_jit_unlock ();
2983                 return res;
2984         }
2985
2986         res = mono_metadata_signature_alloc (mono_defaults.corlib, arity + 1);
2987
2988         res->pinvoke = 1;
2989 #ifdef MONO_ARCH_VARARG_ICALLS
2990         /* Only set this only some archs since not all backends can handle varargs+pinvoke */
2991         res->call_convention = MONO_CALL_VARARG;
2992 #endif
2993
2994 #ifdef PLATFORM_WIN32
2995         res->call_convention = MONO_CALL_C;
2996 #endif
2997
2998         res->params [0] = &mono_defaults.int_class->byval_arg;  
2999         for (i = 0; i < arity; i++)
3000                 res->params [i + 1] = &mono_defaults.int_class->byval_arg;
3001
3002         res->ret = &mono_defaults.int_class->byval_arg;
3003
3004         g_hash_table_insert (sighash, GINT_TO_POINTER (arity), res);
3005         mono_jit_unlock ();
3006
3007         return res;
3008 }
3009
3010 #ifdef MONO_ARCH_SOFT_FLOAT
3011 static void
3012 handle_store_float (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ptr, MonoInst *val, const unsigned char *ip)
3013 {
3014         MonoInst *iargs [2];
3015         iargs [0] = val;
3016         iargs [1] = ptr;
3017
3018         mono_emit_jit_icall (cfg, bblock, mono_fstore_r4, iargs, ip);
3019 }
3020
3021 static int
3022 handle_load_float (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ptr, const unsigned char *ip)
3023 {
3024         MonoInst *iargs [1];
3025         iargs [0] = ptr;
3026
3027         return mono_emit_jit_icall (cfg, bblock, mono_fload_r4, iargs, ip);
3028 }
3029
3030 #define LDLOC_SOFT_FLOAT(cfg,ins,idx,ip) do {\
3031                 if (header->locals [(idx)]->type == MONO_TYPE_R4 && !header->locals [(idx)]->byref) {   \
3032                         int temp;       \
3033                         NEW_LOCLOADA (cfg, (ins), (idx));       \
3034                         temp = handle_load_float (cfg, bblock, (ins), (ip));    \
3035                         NEW_TEMPLOAD (cfg, (ins), temp);        \
3036                 }       \
3037         } while (0)
3038 #define STLOC_SOFT_FLOAT(cfg,ins,idx,ip) do {\
3039                 if (header->locals [(idx)]->type == MONO_TYPE_R4 && !header->locals [(idx)]->byref) {   \
3040                         int temp;       \
3041                         NEW_LOCLOADA (cfg, (ins), (idx));       \
3042                         handle_store_float (cfg, bblock, (ins), *sp, (ip));     \
3043                         MONO_INST_NEW (cfg, (ins), OP_NOP);     \
3044                 }       \
3045         } while (0)
3046 #define LDARG_SOFT_FLOAT(cfg,ins,idx,ip) do {\
3047                 if (param_types [(idx)]->type == MONO_TYPE_R4 && !param_types [(idx)]->byref) { \
3048                         int temp;       \
3049                         NEW_ARGLOADA (cfg, (ins), (idx));       \
3050                         temp = handle_load_float (cfg, bblock, (ins), (ip));    \
3051                         NEW_TEMPLOAD (cfg, (ins), temp);        \
3052                 }       \
3053         } while (0)
3054 #define STARG_SOFT_FLOAT(cfg,ins,idx,ip) do {\
3055                 if (param_types [(idx)]->type == MONO_TYPE_R4 && !param_types [(idx)]->byref) { \
3056                         int temp;       \
3057                         NEW_ARGLOADA (cfg, (ins), (idx));       \
3058                         handle_store_float (cfg, bblock, (ins), *sp, (ip));     \
3059                         MONO_INST_NEW (cfg, (ins), OP_NOP);     \
3060                 }       \
3061         } while (0)
3062 #else
3063 #define LDLOC_SOFT_FLOAT(cfg,ins,idx,ip)
3064 #define STLOC_SOFT_FLOAT(cfg,ins,idx,ip)
3065 #define LDARG_SOFT_FLOAT(cfg,ins,idx,ip)
3066 #define STARG_SOFT_FLOAT(cfg,ins,idx,ip)
3067 #endif
3068
3069 static MonoMethod*
3070 get_memcpy_method (void)
3071 {
3072         static MonoMethod *memcpy_method = NULL;
3073         if (!memcpy_method) {
3074                 memcpy_method = mono_class_get_method_from_name (mono_defaults.string_class, "memcpy", 3);
3075                 if (!memcpy_method)
3076                         g_error ("Old corlib found. Install a new one");
3077         }
3078         return memcpy_method;
3079 }
3080
3081 static void
3082 handle_stobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, MonoInst *src, const unsigned char *ip, MonoClass *klass, gboolean to_end, gboolean native, gboolean write_barrier) {
3083         MonoInst *iargs [3];
3084         int n;
3085         guint32 align = 0;
3086         MonoMethod *memcpy_method;
3087
3088         g_assert (klass);
3089         /*
3090          * This check breaks with spilled vars... need to handle it during verification anyway.
3091          * g_assert (klass && klass == src->klass && klass == dest->klass);
3092          */
3093
3094         if (native)
3095                 n = mono_class_native_size (klass, &align);
3096         else
3097                 n = mono_class_value_size (klass, &align);
3098
3099 #if HAVE_WRITE_BARRIERS
3100         /* if native is true there should be no references in the struct */
3101         if (write_barrier && klass->has_references && !native) {
3102                 iargs [0] = dest;
3103                 iargs [1] = src;
3104                 NEW_PCONST (cfg, iargs [2], klass);
3105
3106                 mono_emit_jit_icall (cfg, bblock, mono_value_copy, iargs, ip);
3107                 return;
3108         }
3109 #endif
3110
3111         /* FIXME: add write barrier handling */
3112         if ((cfg->opt & MONO_OPT_INTRINS) && !to_end && n <= sizeof (gpointer) * 5) {
3113                 MonoInst *inst;
3114                 if (dest->opcode == OP_LDADDR) {
3115                         /* Keep liveness info correct */
3116                         NEW_DUMMY_STORE (cfg, inst, dest->inst_i0->inst_c0);
3117                         MONO_ADD_INS (bblock, inst);
3118                 }
3119                 NEW_MEMCPY (cfg, inst, dest, src, n, align);
3120                 MONO_ADD_INS (bblock, inst);
3121                 return;
3122         }
3123         iargs [0] = dest;
3124         iargs [1] = src;
3125         NEW_ICONST (cfg, iargs [2], n);
3126
3127         memcpy_method = get_memcpy_method ();
3128         mono_emit_method_call_spilled_full (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL, FALSE, to_end);
3129 }
3130
3131 static MonoMethod*
3132 get_memset_method (void)
3133 {
3134         static MonoMethod *memset_method = NULL;
3135         if (!memset_method) {
3136                 memset_method = mono_class_get_method_from_name (mono_defaults.string_class, "memset", 3);
3137                 if (!memset_method)
3138                         g_error ("Old corlib found. Install a new one");
3139         }
3140         return memset_method;
3141 }
3142
3143 static void
3144 handle_initobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, const guchar *ip, MonoClass *klass, MonoInst **stack_start, MonoInst **sp)
3145 {
3146         MonoInst *iargs [3];
3147         MonoInst *ins, *zero_int32;
3148         int n;
3149         guint32 align;
3150         MonoMethod *memset_method;
3151
3152         NEW_ICONST (cfg, zero_int32, 0);
3153
3154         mono_class_init (klass);
3155         n = mono_class_value_size (klass, &align);
3156         MONO_INST_NEW (cfg, ins, 0);
3157         ins->cil_code = ip;
3158         ins->inst_left = dest;
3159         ins->inst_right = zero_int32;
3160         if (n == 1) {
3161                 ins->opcode = CEE_STIND_I1;
3162                 MONO_ADD_INS (bblock, ins);
3163         } else if ((n == 2) && (align >= 2)) {
3164                 ins->opcode = CEE_STIND_I2;
3165                 MONO_ADD_INS (bblock, ins);
3166         } else if ((n == 2) && (align >= 4)) {
3167                 ins->opcode = CEE_STIND_I4;
3168                 MONO_ADD_INS (bblock, ins);
3169         } else if (n <= sizeof (gpointer) * 5) {
3170                 NEW_MEMSET (cfg, ins, dest, 0, n, align);
3171                 MONO_ADD_INS (bblock, ins);
3172         } else {
3173                 memset_method = get_memset_method ();
3174                 handle_loaded_temps (cfg, bblock, stack_start, sp);
3175                 iargs [0] = dest;
3176                 NEW_ICONST (cfg, iargs [1], 0);
3177                 NEW_ICONST (cfg, iargs [2], n);
3178                 mono_emit_method_call_spilled (cfg, bblock, memset_method, memset_method->signature, iargs, ip, NULL);
3179         }
3180 }
3181
3182 static int
3183 handle_alloc (MonoCompile *cfg, MonoBasicBlock *bblock, MonoClass *klass, gboolean for_box, const guchar *ip)
3184 {
3185         MonoInst *iargs [2];
3186         void *alloc_ftn;
3187
3188         if (cfg->opt & MONO_OPT_SHARED) {
3189                 NEW_DOMAINCONST (cfg, iargs [0]);
3190                 NEW_CLASSCONST (cfg, iargs [1], klass);
3191
3192                 alloc_ftn = mono_object_new;
3193         } else if (cfg->compile_aot && bblock->out_of_line && klass->type_token && klass->image == mono_defaults.corlib) {
3194                 /* This happens often in argument checking code, eg. throw new FooException... */
3195                 /* Avoid relocations by calling a helper function specialized to mscorlib */
3196                 NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (klass->type_token));
3197                 return mono_emit_jit_icall (cfg, bblock, mono_helper_newobj_mscorlib, iargs, ip);
3198         } else {
3199                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
3200                 MonoMethod *managed_alloc = mono_gc_get_managed_allocator (vtable, for_box);
3201                 gboolean pass_lw;
3202
3203                 if (managed_alloc) {
3204                         NEW_VTABLECONST (cfg, iargs [0], vtable);
3205                         return mono_emit_method_call_spilled (cfg, bblock, managed_alloc, mono_method_signature (managed_alloc), iargs, ip, NULL);
3206                 }
3207                 alloc_ftn = mono_class_get_allocation_ftn (vtable, for_box, &pass_lw);
3208                 if (pass_lw) {
3209                         guint32 lw = vtable->klass->instance_size;
3210                         lw = ((lw + (sizeof (gpointer) - 1)) & ~(sizeof (gpointer) - 1)) / sizeof (gpointer);
3211                         NEW_ICONST (cfg, iargs [0], lw);
3212                         NEW_VTABLECONST (cfg, iargs [1], vtable);
3213                 }
3214                 else
3215                         NEW_VTABLECONST (cfg, iargs [0], vtable);
3216         }
3217
3218         return mono_emit_jit_icall (cfg, bblock, alloc_ftn, iargs, ip);
3219 }
3220
3221 static int
3222 handle_alloc_from_inst (MonoCompile *cfg, MonoBasicBlock *bblock, MonoClass *klass, MonoInst *vtable_inst,
3223                 gboolean for_box, const guchar *ip)
3224 {
3225         MonoInst *iargs [2];
3226         MonoMethod *managed_alloc = NULL;
3227         /*
3228           FIXME: we cannot get managed_alloc here because we can't get
3229           the class's vtable (because it's not a closed class)
3230
3231         MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
3232         MonoMethod *managed_alloc = mono_gc_get_managed_allocator (vtable, for_box);
3233         */
3234
3235         g_assert (!(cfg->opt & MONO_OPT_SHARED));
3236         g_assert (!cfg->compile_aot);
3237
3238         if (managed_alloc) {
3239                 iargs [0] = vtable_inst;
3240                 return mono_emit_method_call_spilled (cfg, bblock, managed_alloc, mono_method_signature (managed_alloc), iargs, ip, NULL);
3241         }
3242
3243         iargs [0] = vtable_inst;
3244
3245         return mono_emit_jit_icall (cfg, bblock, mono_object_new_specific, iargs, ip);
3246 }
3247
3248 /**
3249  * Handles unbox of a Nullable<T>, returning a temp variable
3250  * where the result is stored
3251  */
3252 static int
3253 handle_unbox_nullable (MonoCompile* cfg, MonoBasicBlock* bblock, MonoInst* val, const guchar *ip, MonoClass* klass)
3254 {
3255        MonoMethod* method = mono_class_get_method_from_name (klass, "Unbox", 1);
3256        return mono_emit_method_call_spilled (cfg, bblock, method, mono_method_signature (method), &val, ip, NULL);
3257         
3258 }
3259
3260
3261
3262 static MonoInst *
3263 handle_box (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *val, const guchar *ip, MonoClass *klass)
3264 {
3265         MonoInst *dest, *vtoffset, *add, *vstore;
3266         int temp;
3267
3268        if (mono_class_is_nullable (klass)) {
3269                MonoMethod* method = mono_class_get_method_from_name (klass, "Box", 1);
3270                temp = mono_emit_method_call_spilled (cfg, bblock, method, mono_method_signature (method), &val, ip, NULL);
3271                NEW_TEMPLOAD (cfg, dest, temp);
3272                return dest;
3273        }
3274
3275
3276         temp = handle_alloc (cfg, bblock, klass, TRUE, ip);
3277         NEW_TEMPLOAD (cfg, dest, temp);
3278         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
3279         MONO_INST_NEW (cfg, add, OP_PADD);
3280         add->inst_left = dest;
3281         add->inst_right = vtoffset;
3282         add->cil_code = ip;
3283         add->klass = klass;
3284         MONO_INST_NEW (cfg, vstore, CEE_STIND_I);
3285         vstore->opcode = mini_type_to_stind (cfg, &klass->byval_arg);
3286         vstore->cil_code = ip;
3287         vstore->inst_left = add;
3288         vstore->inst_right = val;
3289
3290 #ifdef MONO_ARCH_SOFT_FLOAT
3291         if (vstore->opcode == CEE_STIND_R4) {
3292                 handle_store_float (cfg, bblock, add, val, ip);
3293         } else
3294 #endif
3295         if (vstore->opcode == CEE_STOBJ) {
3296                 handle_stobj (cfg, bblock, add, val, ip, klass, FALSE, FALSE, TRUE);
3297         } else
3298                 MONO_ADD_INS (bblock, vstore);
3299
3300         NEW_TEMPLOAD (cfg, dest, temp);
3301         return dest;
3302 }
3303
3304 static MonoInst*
3305 handle_delegate_ctor (MonoCompile *cfg, MonoBasicBlock *bblock, MonoClass *klass, MonoInst *target, MonoMethod *method, unsigned char *ip)
3306 {
3307         gpointer *trampoline;
3308         MonoInst *obj, *ins, *store, *offset_ins, *method_ins, *tramp_ins;
3309         int temp;
3310
3311         temp = handle_alloc (cfg, bblock, klass, FALSE, ip);
3312
3313         /* Inline the contents of mono_delegate_ctor */
3314
3315         /* Set target field */
3316         /* Optimize away setting of NULL target */
3317         if (!(target->opcode == OP_PCONST && target->inst_p0 == 0)) {
3318                 NEW_TEMPLOAD (cfg, obj, temp);
3319                 NEW_ICONST (cfg, offset_ins, G_STRUCT_OFFSET (MonoDelegate, target));
3320                 MONO_INST_NEW (cfg, ins, OP_PADD);
3321                 ins->cil_code = ip;
3322                 ins->inst_left = obj;
3323                 ins->inst_right = offset_ins;
3324
3325                 MONO_INST_NEW (cfg, store, CEE_STIND_REF);
3326                 store->cil_code = ip;
3327                 store->inst_left = ins;
3328                 store->inst_right = target;
3329                 mono_bblock_add_inst (bblock, store);
3330         }
3331
3332         /* Set method field */
3333         NEW_TEMPLOAD (cfg, obj, temp);
3334         NEW_ICONST (cfg, offset_ins, G_STRUCT_OFFSET (MonoDelegate, method));
3335         MONO_INST_NEW (cfg, ins, OP_PADD);
3336         ins->cil_code = ip;
3337         ins->inst_left = obj;
3338         ins->inst_right = offset_ins;
3339
3340         NEW_METHODCONST (cfg, method_ins, method);
3341
3342         MONO_INST_NEW (cfg, store, CEE_STIND_I);
3343         store->cil_code = ip;
3344         store->inst_left = ins;
3345         store->inst_right = method_ins;
3346         mono_bblock_add_inst (bblock, store);
3347
3348         /* Set invoke_impl field */
3349         NEW_TEMPLOAD (cfg, obj, temp);
3350         NEW_ICONST (cfg, offset_ins, G_STRUCT_OFFSET (MonoDelegate, invoke_impl));
3351         MONO_INST_NEW (cfg, ins, OP_PADD);
3352         ins->cil_code = ip;
3353         ins->inst_left = obj;
3354         ins->inst_right = offset_ins;
3355
3356         trampoline = mono_create_delegate_trampoline (klass);
3357         NEW_AOTCONST (cfg, tramp_ins, MONO_PATCH_INFO_ABS, trampoline);
3358
3359         MONO_INST_NEW (cfg, store, CEE_STIND_I);
3360         store->cil_code = ip;
3361         store->inst_left = ins;
3362         store->inst_right = tramp_ins;
3363         mono_bblock_add_inst (bblock, store);
3364
3365         /* All the checks which are in mono_delegate_ctor () are done by the delegate trampoline */
3366
3367         NEW_TEMPLOAD (cfg, obj, temp);
3368
3369         return obj;
3370 }
3371
3372 static int
3373 handle_array_new (MonoCompile *cfg, MonoBasicBlock *bblock, int rank, MonoInst **sp, unsigned char *ip)
3374 {
3375         MonoMethodSignature *esig;
3376         char icall_name [256];
3377         char *name;
3378         MonoJitICallInfo *info;
3379
3380         /* Need to register the icall so it gets an icall wrapper */
3381         sprintf (icall_name, "ves_array_new_va_%d", rank);
3382
3383         mono_jit_lock ();
3384         info = mono_find_jit_icall_by_name (icall_name);
3385         if (info == NULL) {
3386                 esig = mono_get_array_new_va_signature (rank);
3387                 name = g_strdup (icall_name);
3388                 info = mono_register_jit_icall (mono_array_new_va, name, esig, FALSE);
3389
3390                 g_hash_table_insert (jit_icall_name_hash, name, name);
3391         }
3392         mono_jit_unlock ();
3393
3394         cfg->flags |= MONO_CFG_HAS_VARARGS;
3395
3396         /* FIXME: This uses info->sig, but it should use the signature of the wrapper */
3397         return mono_emit_native_call (cfg, bblock, mono_icall_get_wrapper (info), info->sig, sp, ip, TRUE, FALSE);
3398 }
3399
3400 static void
3401 mono_emit_load_got_addr (MonoCompile *cfg)
3402 {
3403         MonoInst *load, *store, *dummy_use;
3404         MonoInst *get_got;
3405
3406         if (!cfg->got_var || cfg->got_var_allocated)
3407                 return;
3408
3409         MONO_INST_NEW (cfg, get_got, OP_LOAD_GOTADDR);
3410         NEW_TEMPSTORE (cfg, store, cfg->got_var->inst_c0, get_got);
3411
3412         /* Add it to the start of the first bblock */
3413         MONO_INST_LIST_ADD (&store->node, &cfg->bb_entry->ins_list);
3414
3415         cfg->got_var_allocated = TRUE;
3416
3417         /* 
3418          * Add a dummy use to keep the got_var alive, since real uses might
3419          * only be generated in the decompose or instruction selection phases.
3420          * Add it to end_bblock, so the variable's lifetime covers the whole
3421          * method.
3422          */
3423         NEW_TEMPLOAD (cfg, load, cfg->got_var->inst_c0);
3424         NEW_DUMMY_USE (cfg, dummy_use, load);
3425         MONO_ADD_INS (cfg->bb_exit, dummy_use);
3426 }
3427
3428 #define CODE_IS_STLOC(ip) (((ip) [0] >= CEE_STLOC_0 && (ip) [0] <= CEE_STLOC_3) || ((ip) [0] == CEE_STLOC_S))
3429
3430 static gboolean
3431 mini_class_is_system_array (MonoClass *klass)
3432 {
3433         if (klass->parent == mono_defaults.array_class)
3434                 return TRUE;
3435         else
3436                 return FALSE;
3437 }
3438
3439 static gboolean
3440 mono_method_check_inlining (MonoCompile *cfg, MonoMethod *method)
3441 {
3442         MonoMethodHeader *header = mono_method_get_header (method);
3443         MonoMethodSignature *signature = mono_method_signature (method);
3444         MonoVTable *vtable;
3445         int i;
3446
3447         if (cfg->generic_sharing_context)
3448                 return FALSE;
3449
3450         if (method->inline_failure)
3451                 return FALSE;
3452
3453 #ifdef MONO_ARCH_HAVE_LMF_OPS
3454         if (((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
3455                  (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) &&
3456             !MONO_TYPE_ISSTRUCT (signature->ret) && !mini_class_is_system_array (method->klass))
3457                 return TRUE;
3458 #endif
3459
3460         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3461             (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
3462             (method->iflags & METHOD_IMPL_ATTRIBUTE_NOINLINING) ||
3463             (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) ||
3464             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3465             (method->klass->marshalbyref) ||
3466             !header || header->num_clauses ||
3467             /* fixme: why cant we inline valuetype returns? */
3468             MONO_TYPE_ISSTRUCT (signature->ret))
3469                 return FALSE;
3470
3471 #ifdef MONO_ARCH_SOFT_FLOAT
3472         /* this complicates things, fix later */
3473         if (signature->ret->type == MONO_TYPE_R4)
3474                 return FALSE;
3475 #endif
3476         /* its not worth to inline methods with valuetype arguments?? */
3477         for (i = 0; i < signature->param_count; i++) {
3478                 if (MONO_TYPE_ISSTRUCT (signature->params [i])) {
3479                         return FALSE;
3480                 }
3481 #ifdef MONO_ARCH_SOFT_FLOAT
3482                 /* this complicates things, fix later */
3483                 if (!signature->params [i]->byref && signature->params [i]->type == MONO_TYPE_R4)
3484                         return FALSE;
3485 #endif
3486         }
3487
3488         /*
3489          * if we can initialize the class of the method right away, we do,
3490          * otherwise we don't allow inlining if the class needs initialization,
3491          * since it would mean inserting a call to mono_runtime_class_init()
3492          * inside the inlined code
3493          */
3494         if (!(cfg->opt & MONO_OPT_SHARED)) {
3495                 vtable = mono_class_vtable (cfg->domain, method->klass);
3496                 if (method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) {
3497                         if (cfg->run_cctors && method->klass->has_cctor) {
3498                                 /* This makes so that inline cannot trigger */
3499                                 /* .cctors: too many apps depend on them */
3500                                 /* running with a specific order... */
3501                                 if (! vtable->initialized)
3502                                         return FALSE;
3503                                 mono_runtime_class_init (vtable);
3504                         }
3505                 }
3506                 else if (!vtable->initialized && mono_class_needs_cctor_run (method->klass, NULL))
3507                         return FALSE;
3508         } else {
3509                 /* 
3510                  * If we're compiling for shared code
3511                  * the cctor will need to be run at aot method load time, for example,
3512                  * or at the end of the compilation of the inlining method.
3513                  */
3514                 if (mono_class_needs_cctor_run (method->klass, NULL) && !((method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3515                         return FALSE;
3516         }
3517         //if (!MONO_TYPE_IS_VOID (signature->ret)) return FALSE;
3518
3519         /*
3520          * CAS - do not inline methods with declarative security
3521          * Note: this has to be before any possible return TRUE;
3522          */
3523         if (mono_method_has_declsec (method))
3524                 return FALSE;
3525
3526         /* also consider num_locals? */
3527         if (getenv ("MONO_INLINELIMIT")) {
3528                 if (header->code_size < atoi (getenv ("MONO_INLINELIMIT"))) {
3529                         return TRUE;
3530                 }
3531         } else if (header->code_size < INLINE_LENGTH_LIMIT)
3532                 return TRUE;
3533
3534         return FALSE;
3535 }
3536
3537 static gboolean
3538 mini_field_access_needs_cctor_run (MonoCompile *cfg, MonoMethod *method, MonoVTable *vtable)
3539 {
3540         if (vtable->initialized && !cfg->compile_aot)
3541                 return FALSE;
3542
3543         if (vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)
3544                 return FALSE;
3545
3546         if (!mono_class_needs_cctor_run (vtable->klass, method))
3547                 return FALSE;
3548
3549         if (! (method->flags & METHOD_ATTRIBUTE_STATIC) && (vtable->klass == method->klass))
3550                 /* The initialization is already done before the method is called */
3551                 return FALSE;
3552
3553         return TRUE;
3554 }
3555
3556 static MonoInst*
3557 mini_get_ldelema_ins (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *cmethod, MonoInst **sp, unsigned char *ip, gboolean is_set)
3558 {
3559         int temp, rank;
3560         MonoInst *addr;
3561         MonoMethod *addr_method;
3562         int element_size;
3563
3564         rank = mono_method_signature (cmethod)->param_count - (is_set? 1: 0);
3565
3566         if (rank == 1) {
3567                 MONO_INST_NEW (cfg, addr, CEE_LDELEMA);
3568                 addr->inst_left = sp [0];
3569                 addr->inst_right = sp [1];
3570                 addr->cil_code = ip;
3571                 addr->type = STACK_MP;
3572                 addr->klass = cmethod->klass->element_class;
3573                 return addr;
3574         }
3575
3576         if (rank == 2 && (cfg->opt & MONO_OPT_INTRINS)) {
3577 #if defined(MONO_ARCH_EMULATE_MUL_DIV) && !defined(MONO_ARCH_NO_EMULATE_MUL)
3578                 /* OP_LDELEMA2D depends on OP_LMUL */
3579 #else
3580                 MonoInst *indexes;
3581                 NEW_GROUP (cfg, indexes, sp [1], sp [2]);
3582                 MONO_INST_NEW (cfg, addr, OP_LDELEMA2D);
3583                 addr->inst_left = sp [0];
3584                 addr->inst_right = indexes;
3585                 addr->cil_code = ip;
3586                 addr->type = STACK_MP;
3587                 addr->klass = cmethod->klass->element_class;
3588                 return addr;
3589 #endif
3590         }
3591
3592         element_size = mono_class_array_element_size (cmethod->klass->element_class);
3593         addr_method = mono_marshal_get_array_address (rank, element_size);
3594         temp = mono_emit_method_call_spilled (cfg, bblock, addr_method, addr_method->signature, sp, ip, NULL);
3595         NEW_TEMPLOAD (cfg, addr, temp);
3596         return addr;
3597
3598 }
3599
3600 static MonoJitICallInfo **emul_opcode_map = NULL;
3601
3602 MonoJitICallInfo *
3603 mono_find_jit_opcode_emulation (int opcode)
3604 {
3605         g_assert (opcode >= 0 && opcode <= OP_LAST);
3606         if  (emul_opcode_map)
3607                 return emul_opcode_map [opcode];
3608         else
3609                 return NULL;
3610 }
3611
3612 static int
3613 is_unsigned_regsize_type (MonoType *type)
3614 {
3615         switch (type->type) {
3616         case MONO_TYPE_U1:
3617         case MONO_TYPE_U2:
3618         case MONO_TYPE_U4:
3619 #if SIZEOF_VOID_P == 8
3620         /*case MONO_TYPE_U8: this requires different opcodes in inssel.brg */
3621 #endif
3622                 return TRUE;
3623         default:
3624                 return FALSE;
3625         }
3626 }
3627
3628 static MonoInst*
3629 mini_get_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
3630 {
3631         MonoInst *ins = NULL;
3632         
3633         static MonoClass *runtime_helpers_class = NULL;
3634         if (! runtime_helpers_class)
3635                 runtime_helpers_class = mono_class_from_name (mono_defaults.corlib,
3636                         "System.Runtime.CompilerServices", "RuntimeHelpers");
3637
3638         if (cmethod->klass == mono_defaults.string_class) {
3639                 if (strcmp (cmethod->name, "get_Chars") == 0) {
3640                         MONO_INST_NEW (cfg, ins, OP_GETCHR);
3641                         ins->inst_i0 = args [0];
3642                         ins->inst_i1 = args [1];
3643                         return ins;
3644                 } else if (strcmp (cmethod->name, "get_Length") == 0) {
3645                         MONO_INST_NEW (cfg, ins, OP_STRLEN);
3646                         ins->inst_i0 = args [0];
3647                         return ins;
3648                 } else if (strcmp (cmethod->name, "InternalSetChar") == 0) {
3649                         MonoInst *get_addr;
3650                         MONO_INST_NEW (cfg, get_addr, OP_STR_CHAR_ADDR);
3651                         get_addr->inst_i0 = args [0];
3652                         get_addr->inst_i1 = args [1];
3653                         MONO_INST_NEW (cfg, ins, CEE_STIND_I2);
3654                         ins->inst_i0 = get_addr;
3655                         ins->inst_i1 = args [2];
3656                         return ins;
3657                 } else 
3658                         return NULL;
3659         } else if (cmethod->klass == mono_defaults.object_class) {
3660                 if (strcmp (cmethod->name, "GetType") == 0) {
3661                         MONO_INST_NEW (cfg, ins, OP_GETTYPE);
3662                         ins->inst_i0 = args [0];
3663                         return ins;
3664                 /* The OP_GETHASHCODE rule depends on OP_MUL */
3665 #if !defined(MONO_ARCH_EMULATE_MUL_DIV) && !defined(HAVE_MOVING_COLLECTOR)
3666                 } else if (strcmp (cmethod->name, "InternalGetHashCode") == 0) {
3667                         MONO_INST_NEW (cfg, ins, OP_GETHASHCODE);
3668                         ins->inst_i0 = args [0];
3669                         return ins;
3670 #endif
3671                 } else if (strcmp (cmethod->name, ".ctor") == 0) {
3672                         MONO_INST_NEW (cfg, ins, OP_NOP);
3673                         return ins;
3674                 } else
3675                         return NULL;
3676         } else if (cmethod->klass == mono_defaults.array_class) {
3677                 if (cmethod->name [0] != 'g')
3678                         return NULL;
3679
3680                 if (strcmp (cmethod->name, "get_Rank") == 0) {
3681                         MONO_INST_NEW (cfg, ins, OP_ARRAY_RANK);
3682                         ins->inst_i0 = args [0];
3683                         return ins;
3684                 } else if (strcmp (cmethod->name, "get_Length") == 0) {
3685                         MONO_INST_NEW (cfg, ins, CEE_LDLEN);
3686                         ins->inst_i0 = args [0];
3687                         return ins;
3688                 } else
3689                         return NULL;
3690         } else if (cmethod->klass == runtime_helpers_class) {
3691                 if (strcmp (cmethod->name, "get_OffsetToStringData") == 0) {
3692                         NEW_ICONST (cfg, ins, G_STRUCT_OFFSET (MonoString, chars));
3693                         return ins;
3694                 } else
3695                         return NULL;
3696         } else if (cmethod->klass == mono_defaults.thread_class) {
3697                 if (strcmp (cmethod->name, "get_CurrentThread") == 0 && (ins = mono_arch_get_thread_intrinsic (cfg)))
3698                         return ins;
3699                 if (strcmp (cmethod->name, "MemoryBarrier") == 0) {
3700                         MONO_INST_NEW (cfg, ins, OP_MEMORY_BARRIER);
3701                         return ins;
3702                 }
3703         } else if (mini_class_is_system_array (cmethod->klass) &&
3704                         strcmp (cmethod->name, "GetGenericValueImpl") == 0) {
3705                 MonoInst *sp [2];
3706                 MonoInst *ldelem, *store, *load;
3707                 MonoClass *eklass = mono_class_from_mono_type (fsig->params [1]);
3708                 int n;
3709                 n = mini_type_to_stind (cfg, &eklass->byval_arg);
3710                 if (n == CEE_STOBJ)
3711                         return NULL;
3712                 sp [0] = args [0];
3713                 sp [1] = args [1];
3714                 NEW_LDELEMA (cfg, ldelem, sp, eklass);
3715                 ldelem->flags |= MONO_INST_NORANGECHECK;
3716                 MONO_INST_NEW (cfg, store, n);
3717                 MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, &eklass->byval_arg));
3718                 type_to_eval_stack_type (cfg, &eklass->byval_arg, load);
3719                 load->inst_left = ldelem;
3720                 store->inst_left = args [2];
3721                 store->inst_right = load;
3722                 return store;
3723         } else if (cmethod->klass == mono_defaults.math_class) {
3724                 if (strcmp (cmethod->name, "Min") == 0) {
3725                         if (is_unsigned_regsize_type (fsig->params [0])) {
3726                                 MONO_INST_NEW (cfg, ins, OP_MIN);
3727                                 ins->inst_i0 = args [0];
3728                                 ins->inst_i1 = args [1];
3729                                 return ins;
3730                         }
3731                 } else if (strcmp (cmethod->name, "Max") == 0) {
3732                         if (is_unsigned_regsize_type (fsig->params [0])) {
3733                                 MONO_INST_NEW (cfg, ins, OP_MAX);
3734                                 ins->inst_i0 = args [0];
3735                                 ins->inst_i1 = args [1];
3736                                 return ins;
3737                         }
3738                 }
3739         } else if (cmethod->klass->image == mono_defaults.corlib &&
3740                            (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
3741                            (strcmp (cmethod->klass->name, "Interlocked") == 0)) {
3742                 ins = NULL;
3743
3744 #if SIZEOF_VOID_P == 8
3745                 if (strcmp (cmethod->name, "Read") == 0 && (fsig->params [0]->type == MONO_TYPE_I8)) {
3746                         /* 64 bit reads are already atomic */
3747                         MONO_INST_NEW (cfg, ins, CEE_LDIND_I8);
3748                         ins->inst_i0 = args [0];
3749                 }
3750 #endif
3751
3752 #ifdef MONO_ARCH_HAVE_ATOMIC_ADD
3753                 if (strcmp (cmethod->name, "Increment") == 0) {
3754                         MonoInst *ins_iconst;
3755                         guint32 opcode;
3756
3757                         if (fsig->params [0]->type == MONO_TYPE_I4)
3758                                 opcode = OP_ATOMIC_ADD_NEW_I4;
3759                         else if (fsig->params [0]->type == MONO_TYPE_I8)
3760                                 opcode = OP_ATOMIC_ADD_NEW_I8;
3761                         else
3762                                 g_assert_not_reached ();
3763
3764 #if SIZEOF_VOID_P == 4
3765                         if (opcode == OP_ATOMIC_ADD_NEW_I8)
3766                                 return NULL;
3767 #endif
3768
3769                         MONO_INST_NEW (cfg, ins, opcode);
3770                         MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
3771                         ins_iconst->inst_c0 = 1;
3772
3773                         ins->inst_i0 = args [0];
3774                         ins->inst_i1 = ins_iconst;
3775                 } else if (strcmp (cmethod->name, "Decrement") == 0) {
3776                         MonoInst *ins_iconst;
3777                         guint32 opcode;
3778
3779                         if (fsig->params [0]->type == MONO_TYPE_I4)
3780                                 opcode = OP_ATOMIC_ADD_NEW_I4;
3781                         else if (fsig->params [0]->type == MONO_TYPE_I8)
3782                                 opcode = OP_ATOMIC_ADD_NEW_I8;
3783                         else
3784                                 g_assert_not_reached ();
3785
3786 #if SIZEOF_VOID_P == 4
3787                         if (opcode == OP_ATOMIC_ADD_NEW_I8)
3788                                 return NULL;
3789 #endif
3790
3791                         MONO_INST_NEW (cfg, ins, opcode);
3792                         MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
3793                         ins_iconst->inst_c0 = -1;
3794
3795                         ins->inst_i0 = args [0];
3796                         ins->inst_i1 = ins_iconst;
3797                 } else if (strcmp (cmethod->name, "Add") == 0) {
3798                         guint32 opcode;
3799
3800                         if (fsig->params [0]->type == MONO_TYPE_I4)
3801                                 opcode = OP_ATOMIC_ADD_NEW_I4;
3802                         else if (fsig->params [0]->type == MONO_TYPE_I8)
3803                                 opcode = OP_ATOMIC_ADD_NEW_I8;
3804                         else
3805                                 g_assert_not_reached ();
3806
3807 #if SIZEOF_VOID_P == 4
3808                         if (opcode == OP_ATOMIC_ADD_NEW_I8)
3809                                 return NULL;
3810 #endif
3811                         
3812                         MONO_INST_NEW (cfg, ins, opcode);
3813
3814                         ins->inst_i0 = args [0];
3815                         ins->inst_i1 = args [1];
3816                 }
3817 #endif /* MONO_ARCH_HAVE_ATOMIC_ADD */
3818
3819 #ifdef MONO_ARCH_HAVE_ATOMIC_EXCHANGE
3820                 if (strcmp (cmethod->name, "Exchange") == 0) {
3821                         guint32 opcode;
3822
3823                         if (fsig->params [0]->type == MONO_TYPE_I4)
3824                                 opcode = OP_ATOMIC_EXCHANGE_I4;
3825 #if SIZEOF_VOID_P == 8
3826                         else if ((fsig->params [0]->type == MONO_TYPE_I8) ||
3827                                          (fsig->params [0]->type == MONO_TYPE_I) ||
3828                                          (fsig->params [0]->type == MONO_TYPE_OBJECT))
3829                                 opcode = OP_ATOMIC_EXCHANGE_I8;
3830 #else
3831                         else if ((fsig->params [0]->type == MONO_TYPE_I) ||
3832                                          (fsig->params [0]->type == MONO_TYPE_OBJECT))
3833                                 opcode = OP_ATOMIC_EXCHANGE_I4;
3834 #endif
3835                         else
3836                                 return NULL;
3837
3838 #if SIZEOF_VOID_P == 4
3839                         if (opcode == OP_ATOMIC_EXCHANGE_I8)
3840                                 return NULL;
3841 #endif
3842
3843                         MONO_INST_NEW (cfg, ins, opcode);
3844
3845                         ins->inst_i0 = args [0];
3846                         ins->inst_i1 = args [1];
3847                 }
3848 #endif /* MONO_ARCH_HAVE_ATOMIC_EXCHANGE */
3849
3850                 if (ins)
3851                         return ins;
3852         } else if (cmethod->klass->image == mono_defaults.corlib) {
3853                 if (cmethod->name [0] == 'B' && strcmp (cmethod->name, "Break") == 0
3854                                 && strcmp (cmethod->klass->name, "Debugger") == 0) {
3855                         MONO_INST_NEW (cfg, ins, OP_BREAK);
3856                         return ins;
3857                 }
3858                 if (cmethod->name [0] == 'g' && strcmp (cmethod->name, "get_IsRunningOnWindows") == 0
3859                                 && strcmp (cmethod->klass->name, "Environment") == 0) {
3860 #ifdef PLATFORM_WIN32
3861                         NEW_ICONST (cfg, ins, 1);
3862 #else
3863                         NEW_ICONST (cfg, ins, 0);
3864 #endif
3865                         return ins;
3866                 }
3867         }
3868
3869         return mono_arch_get_inst_for_method (cfg, cmethod, fsig, args);
3870 }
3871
3872 static void
3873 mono_save_args (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, MonoInst **sp, MonoInst **args)
3874 {
3875         MonoInst *store, *temp;
3876         int i;
3877
3878         g_assert (!MONO_TYPE_ISSTRUCT (sig->ret));
3879
3880         if (!sig->hasthis && sig->param_count == 0) 
3881                 return;
3882
3883         if (sig->hasthis) {
3884                 if (sp [0]->opcode == OP_ICONST) {
3885                         *args++ = sp [0];
3886                 } else {
3887                         temp = mono_compile_create_var (cfg, type_from_stack_type (*sp), OP_LOCAL);
3888                         *args++ = temp;
3889                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
3890                         /* FIXME: handle CEE_STIND_R4 */
3891                         store->cil_code = sp [0]->cil_code;
3892                         MONO_ADD_INS (bblock, store);
3893                 }
3894                 sp++;
3895         }
3896
3897         for (i = 0; i < sig->param_count; ++i) {
3898                 if (sp [0]->opcode == OP_ICONST) {
3899                         *args++ = sp [0];
3900                 } else {
3901                         temp = mono_compile_create_var (cfg, sig->params [i], OP_LOCAL);
3902                         *args++ = temp;
3903                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
3904                         store->cil_code = sp [0]->cil_code;
3905                         /* FIXME: handle CEE_STIND_R4 */
3906                         if (store->opcode == CEE_STOBJ) {
3907                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
3908                                 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, temp->klass, FALSE, FALSE, FALSE);
3909 #ifdef MONO_ARCH_SOFT_FLOAT
3910                         } else if (store->opcode == CEE_STIND_R4) {
3911                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
3912                                 handle_store_float (cfg, bblock, store, *sp, sp [0]->cil_code);
3913 #endif
3914                         } else {
3915                                 MONO_ADD_INS (bblock, store);
3916                         } 
3917                 }
3918                 sp++;
3919         }
3920 }
3921 #define MONO_INLINE_CALLED_LIMITED_METHODS 0
3922 #define MONO_INLINE_CALLER_LIMITED_METHODS 0
3923
3924 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
3925 static char*
3926 mono_inline_called_method_name_limit = NULL;
3927 static gboolean check_inline_called_method_name_limit (MonoMethod *called_method) {
3928         char *called_method_name = mono_method_full_name (called_method, TRUE);
3929         int strncmp_result;
3930         
3931         if (mono_inline_called_method_name_limit == NULL) {
3932                 char *limit_string = getenv ("MONO_INLINE_CALLED_METHOD_NAME_LIMIT");
3933                 if (limit_string != NULL) {
3934                         mono_inline_called_method_name_limit = limit_string;
3935                 } else {
3936                         mono_inline_called_method_name_limit = (char *) "";
3937                 }
3938         }
3939         
3940         strncmp_result = strncmp (called_method_name, mono_inline_called_method_name_limit, strlen (mono_inline_called_method_name_limit));
3941         g_free (called_method_name);
3942         
3943         //return (strncmp_result <= 0);
3944         return (strncmp_result == 0);
3945 }
3946 #endif
3947
3948 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
3949 static char*
3950 mono_inline_caller_method_name_limit = NULL;
3951 static gboolean check_inline_caller_method_name_limit (MonoMethod *caller_method) {
3952         char *caller_method_name = mono_method_full_name (caller_method, TRUE);
3953         int strncmp_result;
3954         
3955         if (mono_inline_caller_method_name_limit == NULL) {
3956                 char *limit_string = getenv ("MONO_INLINE_CALLER_METHOD_NAME_LIMIT");
3957                 if (limit_string != NULL) {
3958                         mono_inline_caller_method_name_limit = limit_string;
3959                 } else {
3960                         mono_inline_caller_method_name_limit = (char *) "";
3961                 }
3962         }
3963         
3964         strncmp_result = strncmp (caller_method_name, mono_inline_caller_method_name_limit, strlen (mono_inline_caller_method_name_limit));
3965         g_free (caller_method_name);
3966         
3967         //return (strncmp_result <= 0);
3968         return (strncmp_result == 0);
3969 }
3970 #endif
3971
3972 static int
3973 inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoBasicBlock *bblock, MonoInst **sp,
3974                 guchar *ip, guint real_offset, GList *dont_inline, MonoBasicBlock **last_b, gboolean inline_allways)
3975 {
3976         MonoInst *ins, *rvar = NULL;
3977         MonoMethodHeader *cheader;
3978         MonoBasicBlock *ebblock, *sbblock;
3979         int i, costs, new_locals_offset;
3980         MonoMethod *prev_inlined_method;
3981         MonoBasicBlock **prev_cil_offset_to_bb;
3982         unsigned char* prev_cil_start;
3983         guint32 prev_cil_offset_to_bb_len;
3984
3985         g_assert (cfg->exception_type == MONO_EXCEPTION_NONE);
3986
3987 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
3988         if ((! inline_allways) && ! check_inline_called_method_name_limit (cmethod))
3989                 return 0;
3990 #endif
3991 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
3992         if ((! inline_allways) && ! check_inline_caller_method_name_limit (cfg->method))
3993                 return 0;
3994 #endif
3995
3996         if (bblock->out_of_line && !inline_allways)
3997                 return 0;
3998
3999         if (cfg->verbose_level > 2)
4000                 g_print ("INLINE START %p %s -> %s\n", cmethod,  mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
4001
4002         if (!cmethod->inline_info) {
4003                 mono_jit_stats.inlineable_methods++;
4004                 cmethod->inline_info = 1;
4005         }
4006         /* allocate space to store the return value */
4007         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
4008                 rvar =  mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
4009         }
4010
4011         /* allocate local variables */
4012         cheader = mono_method_get_header (cmethod);
4013         new_locals_offset = cfg->num_varinfo;
4014         for (i = 0; i < cheader->num_locals; ++i)
4015                 mono_compile_create_var (cfg, cheader->locals [i], OP_LOCAL);
4016
4017         /* allocate starte and end blocks */
4018         NEW_BBLOCK (cfg, sbblock);
4019         sbblock->block_num = cfg->num_bblocks++;
4020         sbblock->real_offset = real_offset;
4021
4022         NEW_BBLOCK (cfg, ebblock);
4023         ebblock->block_num = cfg->num_bblocks++;
4024         ebblock->real_offset = real_offset;
4025
4026         prev_inlined_method = cfg->inlined_method;
4027         cfg->inlined_method = cmethod;
4028         prev_cil_offset_to_bb = cfg->cil_offset_to_bb;
4029         prev_cil_offset_to_bb_len = cfg->cil_offset_to_bb_len;
4030         prev_cil_start = cfg->cil_start;
4031
4032         costs = mono_method_to_ir (cfg, cmethod, sbblock, ebblock, new_locals_offset, rvar, dont_inline, sp, real_offset, *ip == CEE_CALLVIRT);
4033
4034         cfg->inlined_method = prev_inlined_method;
4035         cfg->cil_offset_to_bb = prev_cil_offset_to_bb;
4036         cfg->cil_offset_to_bb_len = prev_cil_offset_to_bb_len;
4037         cfg->cil_start = prev_cil_start;
4038
4039         if ((costs >= 0 && costs < 60) || inline_allways) {
4040                 if (cfg->verbose_level > 2)
4041                         g_print ("INLINE END %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
4042                 
4043                 mono_jit_stats.inlined_methods++;
4044
4045                 /* always add some code to avoid block split failures */
4046                 MONO_INST_NEW (cfg, ins, OP_NOP);
4047                 MONO_ADD_INS (bblock, ins);
4048                 ins->cil_code = ip;
4049
4050                 bblock->next_bb = sbblock;
4051                 link_bblock (cfg, bblock, sbblock);
4052
4053                 if (rvar) {
4054                         NEW_TEMPLOAD (cfg, ins, rvar->inst_c0);
4055 #ifdef MONO_ARCH_SOFT_FLOAT
4056                         if (ins->opcode == CEE_LDIND_R4) {
4057                                 int temp;
4058                                 NEW_TEMPLOADA (cfg, ins, rvar->inst_c0);
4059                                 temp = handle_load_float (cfg, bblock, ins, ip);
4060                                 NEW_TEMPLOAD (cfg, ins, temp);
4061                         }
4062 #endif
4063                         *sp++ = ins;
4064                 }
4065                 *last_b = ebblock;
4066                 return costs + 1;
4067         } else {
4068                 if (cfg->verbose_level > 2)
4069                         g_print ("INLINE ABORTED %s\n", mono_method_full_name (cmethod, TRUE));
4070                 cfg->exception_type = MONO_EXCEPTION_NONE;
4071                 mono_loader_clear_error ();
4072                 cmethod->inline_failure = TRUE;
4073         }
4074         return 0;
4075 }
4076
4077 /*
4078  * Some of these comments may well be out-of-date.
4079  * Design decisions: we do a single pass over the IL code (and we do bblock 
4080  * splitting/merging in the few cases when it's required: a back jump to an IL
4081  * address that was not already seen as bblock starting point).
4082  * Code is validated as we go (full verification is still better left to metadata/verify.c).
4083  * Complex operations are decomposed in simpler ones right away. We need to let the 
4084  * arch-specific code peek and poke inside this process somehow (except when the 
4085  * optimizations can take advantage of the full semantic info of coarse opcodes).
4086  * All the opcodes of the form opcode.s are 'normalized' to opcode.
4087  * MonoInst->opcode initially is the IL opcode or some simplification of that 
4088  * (OP_LOAD, OP_STORE). The arch-specific code may rearrange it to an arch-specific 
4089  * opcode with value bigger than OP_LAST.
4090  * At this point the IR can be handed over to an interpreter, a dumb code generator
4091  * or to the optimizing code generator that will translate it to SSA form.
4092  *
4093  * Profiling directed optimizations.
4094  * We may compile by default with few or no optimizations and instrument the code
4095  * or the user may indicate what methods to optimize the most either in a config file
4096  * or through repeated runs where the compiler applies offline the optimizations to 
4097  * each method and then decides if it was worth it.
4098  *
4099  */
4100
4101 #define CHECK_TYPE(ins) if (!(ins)->type) UNVERIFIED
4102 #define CHECK_STACK(num) if ((sp - stack_start) < (num)) UNVERIFIED
4103 #define CHECK_STACK_OVF(num) if (((sp - stack_start) + (num)) > header->max_stack) UNVERIFIED
4104 #define CHECK_ARG(num) if ((unsigned)(num) >= (unsigned)num_args) UNVERIFIED
4105 #define CHECK_LOCAL(num) if ((unsigned)(num) >= (unsigned)header->num_locals) UNVERIFIED
4106 #define CHECK_OPSIZE(size) if (ip + size > end) UNVERIFIED
4107 #define CHECK_UNVERIFIABLE(cfg) if (cfg->unverifiable) UNVERIFIED
4108 #define CHECK_TYPELOAD(klass) if (!(klass) || (klass)->exception_type) {cfg->exception_ptr = klass; goto load_error;}
4109
4110 /* offset from br.s -> br like opcodes */
4111 #define BIG_BRANCH_OFFSET 13
4112
4113 static inline gboolean
4114 ip_in_bb (MonoCompile *cfg, MonoBasicBlock *bb, const guint8* ip)
4115 {
4116         MonoBasicBlock *b = cfg->cil_offset_to_bb [ip - cfg->cil_start];
4117         
4118         return b == NULL || b == bb;
4119 }
4120
4121 static int
4122 get_basic_blocks (MonoCompile *cfg, MonoMethodHeader* header, guint real_offset, unsigned char *start, unsigned char *end, unsigned char **pos)
4123 {
4124         unsigned char *ip = start;
4125         unsigned char *target;
4126         int i;
4127         guint cli_addr;
4128         MonoBasicBlock *bblock;
4129         const MonoOpcode *opcode;
4130
4131         while (ip < end) {
4132                 cli_addr = ip - start;
4133                 i = mono_opcode_value ((const guint8 **)&ip, end);
4134                 if (i < 0)
4135                         UNVERIFIED;
4136                 opcode = &mono_opcodes [i];
4137                 switch (opcode->argument) {
4138                 case MonoInlineNone:
4139                         ip++; 
4140                         break;
4141                 case MonoInlineString:
4142                 case MonoInlineType:
4143                 case MonoInlineField:
4144                 case MonoInlineMethod:
4145                 case MonoInlineTok:
4146                 case MonoInlineSig:
4147                 case MonoShortInlineR:
4148                 case MonoInlineI:
4149                         ip += 5;
4150                         break;
4151                 case MonoInlineVar:
4152                         ip += 3;
4153                         break;
4154                 case MonoShortInlineVar:
4155                 case MonoShortInlineI:
4156                         ip += 2;
4157                         break;
4158                 case MonoShortInlineBrTarget:
4159                         target = start + cli_addr + 2 + (signed char)ip [1];
4160                         GET_BBLOCK (cfg, bblock, target);
4161                         ip += 2;
4162                         if (ip < end)
4163                                 GET_BBLOCK (cfg, bblock, ip);
4164                         break;
4165                 case MonoInlineBrTarget:
4166                         target = start + cli_addr + 5 + (gint32)read32 (ip + 1);
4167                         GET_BBLOCK (cfg, bblock, target);
4168                         ip += 5;
4169                         if (ip < end)
4170                                 GET_BBLOCK (cfg, bblock, ip);
4171                         break;
4172                 case MonoInlineSwitch: {
4173                         guint32 n = read32 (ip + 1);
4174                         guint32 j;
4175                         ip += 5;
4176                         cli_addr += 5 + 4 * n;
4177                         target = start + cli_addr;
4178                         GET_BBLOCK (cfg, bblock, target);
4179                         
4180                         for (j = 0; j < n; ++j) {
4181                                 target = start + cli_addr + (gint32)read32 (ip);
4182                                 GET_BBLOCK (cfg, bblock, target);
4183                                 ip += 4;
4184                         }
4185                         break;
4186                 }
4187                 case MonoInlineR:
4188                 case MonoInlineI8:
4189                         ip += 9;
4190                         break;
4191                 default:
4192                         g_assert_not_reached ();
4193                 }
4194
4195                 if (i == CEE_THROW) {
4196                         unsigned char *bb_start = ip - 1;
4197                         
4198                         /* Find the start of the bblock containing the throw */
4199                         bblock = NULL;
4200                         while ((bb_start >= start) && !bblock) {
4201                                 bblock = cfg->cil_offset_to_bb [(bb_start) - start];
4202                                 bb_start --;
4203                         }
4204                         if (bblock)
4205                                 bblock->out_of_line = 1;
4206                 }
4207         }
4208         return 0;
4209 unverified:
4210         *pos = ip;
4211         return 1;
4212 }
4213
4214 static MonoInst*
4215 emit_tree (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ins, const guint8* ip_next)
4216 {
4217         MonoInst *store, *temp, *load;
4218         
4219         if (ip_in_bb (cfg, bblock, ip_next) &&
4220                 (CODE_IS_STLOC (ip_next) || *ip_next == CEE_RET))
4221                         return ins;
4222         
4223         temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
4224         temp->flags |= MONO_INST_IS_TEMP;
4225         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
4226         /* FIXME: handle CEE_STIND_R4 */
4227         store->cil_code = ins->cil_code;
4228         MONO_ADD_INS (bblock, store);
4229         NEW_TEMPLOAD (cfg, load, temp->inst_c0);
4230         load->cil_code = ins->cil_code;
4231         return load;
4232 }
4233
4234 static inline MonoMethod *
4235 mini_get_method (MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context)
4236 {
4237         MonoMethod *method;
4238
4239         if (m->wrapper_type != MONO_WRAPPER_NONE)
4240                 return mono_method_get_wrapper_data (m, token);
4241
4242         method = mono_get_method_full (m->klass->image, token, klass, context);
4243
4244         return method;
4245 }
4246
4247 static inline MonoClass*
4248 mini_get_class (MonoMethod *method, guint32 token, MonoGenericContext *context)
4249 {
4250         MonoClass *klass;
4251
4252         if (method->wrapper_type != MONO_WRAPPER_NONE)
4253                 klass = mono_method_get_wrapper_data (method, token);
4254         else
4255                 klass = mono_class_get_full (method->klass->image, token, context);
4256         if (klass)
4257                 mono_class_init (klass);
4258         return klass;
4259 }
4260
4261 /*
4262  * Returns TRUE if the JIT should abort inlining because "callee"
4263  * is influenced by security attributes.
4264  */
4265 static
4266 gboolean check_linkdemand (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee, MonoBasicBlock *bblock, unsigned char *ip)
4267 {
4268         guint32 result;
4269         
4270         if ((cfg->method != caller) && mono_method_has_declsec (callee)) {
4271                 return TRUE;
4272         }
4273         
4274         result = mono_declsec_linkdemand (cfg->domain, caller, callee);
4275         if (result == MONO_JIT_SECURITY_OK)
4276                 return FALSE;
4277
4278         if (result == MONO_JIT_LINKDEMAND_ECMA) {
4279                 /* Generate code to throw a SecurityException before the actual call/link */
4280                 MonoSecurityManager *secman = mono_security_manager_get_methods ();
4281                 MonoInst *args [2];
4282
4283                 NEW_ICONST (cfg, args [0], 4);
4284                 NEW_METHODCONST (cfg, args [1], caller);
4285                 mono_emit_method_call_spilled (cfg, bblock, secman->linkdemandsecurityexception, mono_method_signature (secman->linkdemandsecurityexception), args, ip, NULL);
4286         } else if (cfg->exception_type == MONO_EXCEPTION_NONE) {
4287                  /* don't hide previous results */
4288                 cfg->exception_type = MONO_EXCEPTION_SECURITY_LINKDEMAND;
4289                 cfg->exception_data = result;
4290                 return TRUE;
4291         }
4292         
4293         return FALSE;
4294 }
4295
4296 static MonoMethod*
4297 method_access_exception (void)
4298 {
4299         static MonoMethod *method = NULL;
4300
4301         if (!method) {
4302                 MonoSecurityManager *secman = mono_security_manager_get_methods ();
4303                 method = mono_class_get_method_from_name (secman->securitymanager,
4304                                                           "MethodAccessException", 2);
4305         }
4306         g_assert (method);
4307         return method;
4308 }
4309
4310 static void
4311 emit_throw_method_access_exception (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee,
4312                                     MonoBasicBlock *bblock, unsigned char *ip)
4313 {
4314         MonoMethod *thrower = method_access_exception ();
4315         MonoInst *args [2];
4316
4317         NEW_METHODCONST (cfg, args [0], caller);
4318         NEW_METHODCONST (cfg, args [1], callee);
4319         mono_emit_method_call_spilled (cfg, bblock, thrower,
4320                 mono_method_signature (thrower), args, ip, NULL);
4321 }
4322
4323 static MonoMethod*
4324 verification_exception (void)
4325 {
4326         static MonoMethod *method = NULL;
4327
4328         if (!method) {
4329                 MonoSecurityManager *secman = mono_security_manager_get_methods ();
4330                 method = mono_class_get_method_from_name (secman->securitymanager,
4331                                                           "VerificationException", 0);
4332         }
4333         g_assert (method);
4334         return method;
4335 }
4336
4337 static void
4338 emit_throw_verification_exception (MonoCompile *cfg, MonoBasicBlock *bblock, unsigned char *ip)
4339 {
4340         MonoMethod *thrower = verification_exception ();
4341
4342         mono_emit_method_call_spilled (cfg, bblock, thrower,
4343                 mono_method_signature (thrower),
4344                 NULL, ip, NULL);
4345 }
4346
4347 static void
4348 ensure_method_is_allowed_to_call_method (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee,
4349                                          MonoBasicBlock *bblock, unsigned char *ip)
4350 {
4351         MonoSecurityCoreCLRLevel caller_level = mono_security_core_clr_method_level (caller, TRUE);
4352         MonoSecurityCoreCLRLevel callee_level = mono_security_core_clr_method_level (callee, TRUE);
4353         gboolean is_safe = TRUE;
4354
4355         if (!(caller_level >= callee_level ||
4356                         caller_level == MONO_SECURITY_CORE_CLR_SAFE_CRITICAL ||
4357                         callee_level == MONO_SECURITY_CORE_CLR_SAFE_CRITICAL)) {
4358                 is_safe = FALSE;
4359         }
4360
4361         if (!is_safe)
4362                 emit_throw_method_access_exception (cfg, caller, callee, bblock, ip);
4363 }
4364
4365 static gboolean
4366 method_is_safe (MonoMethod *method)
4367 {
4368         /*
4369         if (strcmp (method->name, "unsafeMethod") == 0)
4370                 return FALSE;
4371         */
4372         return TRUE;
4373 }
4374
4375 /*
4376  * Check that the IL instructions at ip are the array initialization
4377  * sequence and return the pointer to the data and the size.
4378  */
4379 static const char*
4380 initialize_array_data (MonoMethod *method, gboolean aot, unsigned char *ip, MonoInst *newarr, int *out_size)
4381 {
4382         /*
4383          * newarr[System.Int32]
4384          * dup
4385          * ldtoken field valuetype ...
4386          * call void class [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class [mscorlib]System.Array, valuetype [mscorlib]System.RuntimeFieldHandle)
4387          */
4388         if (ip [0] == CEE_DUP && ip [1] == CEE_LDTOKEN && ip [5] == 0x4 && ip [6] == CEE_CALL) {
4389                 MonoClass *klass = newarr->inst_newa_class;
4390                 guint32 field_token = read32 (ip + 2);
4391                 guint32 field_index = field_token & 0xffffff;
4392                 guint32 token = read32 (ip + 7);
4393                 guint32 rva;
4394                 const char *data_ptr;
4395                 int size = 0;
4396                 MonoMethod *cmethod;
4397                 MonoClass *dummy_class;
4398                 MonoClassField *field = mono_field_from_token (method->klass->image, field_token, &dummy_class, NULL);
4399                 int dummy_align;
4400
4401                 if (!field)
4402                         return NULL;
4403
4404                 if (newarr->inst_newa_len->opcode != OP_ICONST)
4405                         return NULL;
4406                 cmethod = mini_get_method (method, token, NULL, NULL);
4407                 if (!cmethod)
4408                         return NULL;
4409                 if (strcmp (cmethod->name, "InitializeArray") || strcmp (cmethod->klass->name, "RuntimeHelpers") || cmethod->klass->image != mono_defaults.corlib)
4410                         return NULL;
4411                 switch (mono_type_get_underlying_type (&klass->byval_arg)->type) {
4412                 case MONO_TYPE_BOOLEAN:
4413                 case MONO_TYPE_I1:
4414                 case MONO_TYPE_U1:
4415                         size = 1; break;
4416                 /* we need to swap on big endian, so punt. Should we handle R4 and R8 as well? */
4417 #if G_BYTE_ORDER == G_LITTLE_ENDIAN
4418                 case MONO_TYPE_CHAR:
4419                 case MONO_TYPE_I2:
4420                 case MONO_TYPE_U2:
4421                         size = 2; break;
4422                 case MONO_TYPE_I4:
4423                 case MONO_TYPE_U4:
4424                 case MONO_TYPE_R4:
4425                         size = 4; break;
4426                 case MONO_TYPE_R8:
4427 #ifdef ARM_FPU_FPA
4428                         return NULL; /* stupid ARM FP swapped format */
4429 #endif
4430                 case MONO_TYPE_I8:
4431                 case MONO_TYPE_U8:
4432                         size = 8; break;
4433 #endif
4434                 default:
4435                         return NULL;
4436                 }
4437                 size *= newarr->inst_newa_len->inst_c0;
4438                 if (size > mono_type_size (field->type, &dummy_align))
4439                     return NULL;
4440                 *out_size = size;
4441                 /*g_print ("optimized in %s: size: %d, numelems: %d\n", method->name, size, newarr->inst_newa_len->inst_c0);*/
4442                 field_index = read32 (ip + 2) & 0xffffff;
4443                 mono_metadata_field_info (method->klass->image, field_index - 1, NULL, &rva, NULL);
4444                 data_ptr = mono_image_rva_map (method->klass->image, rva);
4445                 /*g_print ("field: 0x%08x, rva: %d, rva_ptr: %p\n", read32 (ip + 2), rva, data_ptr);*/
4446                 /* for aot code we do the lookup on load */
4447                 if (aot && data_ptr)
4448                         return GUINT_TO_POINTER (rva);
4449                 return data_ptr;
4450         }
4451         return NULL;
4452 }
4453
4454 static void
4455 set_exception_type_from_invalid_il (MonoCompile *cfg, MonoMethod *method, unsigned char *ip)
4456 {
4457         char *method_fname = mono_method_full_name (method, TRUE);
4458         char *method_code = mono_disasm_code_one (NULL, method, ip, NULL);
4459         cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
4460         cfg->exception_message = g_strdup_printf ("Invalid IL code in %s: %s\n", method_fname, method_code);
4461         g_free (method_fname);
4462         g_free (method_code);
4463 }
4464
4465 /*
4466  * Generates this->vtable->runtime_generic_context
4467  */
4468 static MonoInst*
4469 get_runtime_generic_context_from_this (MonoCompile *cfg, MonoInst *this, unsigned char *ip)
4470 {
4471         MonoInst *vtable, *rgc_ptr_addr, *rgc_ptr_offset, *rgc_ptr;
4472
4473         MONO_INST_NEW (cfg, vtable, CEE_LDIND_I);
4474         vtable->cil_code = ip;
4475         vtable->inst_left = this;
4476         vtable->type = STACK_PTR;
4477
4478         NEW_ICONST (cfg, rgc_ptr_offset, G_STRUCT_OFFSET (MonoVTable, runtime_generic_context));
4479
4480         MONO_INST_NEW (cfg, rgc_ptr_addr, OP_PADD);
4481         rgc_ptr_addr->cil_code = ip;
4482         rgc_ptr_addr->inst_left = vtable;
4483         rgc_ptr_addr->inst_right = rgc_ptr_offset;
4484         rgc_ptr_addr->type = STACK_PTR;
4485
4486         MONO_INST_NEW (cfg, rgc_ptr, CEE_LDIND_I);
4487         rgc_ptr->cil_code = ip;
4488         rgc_ptr->inst_left = rgc_ptr_addr;
4489         rgc_ptr->type = STACK_PTR;
4490
4491         return rgc_ptr;
4492 }
4493
4494 static MonoInst*
4495 get_runtime_generic_context (MonoCompile *cfg, MonoMethod *method, MonoInst *this, unsigned char *ip)
4496 {
4497         g_assert (!method->klass->valuetype);
4498
4499         if (method->flags & METHOD_ATTRIBUTE_STATIC) {
4500                 MonoInst *rgctx_loc, *rgctx_var;
4501
4502                 rgctx_loc = mono_get_rgctx_var (cfg);
4503                 NEW_TEMPLOAD (cfg, rgctx_var, rgctx_loc->inst_c0);
4504
4505                 return rgctx_var;
4506         } else {
4507                 return get_runtime_generic_context_from_this (cfg, this, ip);
4508         }
4509 }
4510
4511 static gpointer
4512 create_rgctx_lazy_fetch_trampoline (guint32 offset)
4513 {
4514         gpointer tramp, ptr;
4515
4516         mono_jit_lock ();
4517         if (rgctx_lazy_fetch_trampoline_hash)
4518                 tramp = g_hash_table_lookup (rgctx_lazy_fetch_trampoline_hash, GUINT_TO_POINTER (offset));
4519         else
4520                 tramp = NULL;
4521         mono_jit_unlock ();
4522         if (tramp)
4523                 return tramp;
4524
4525         tramp = mono_arch_create_rgctx_lazy_fetch_trampoline (offset);
4526         ptr = mono_create_ftnptr (mono_get_root_domain (), tramp);
4527
4528         mono_jit_lock ();
4529         if (!rgctx_lazy_fetch_trampoline_hash)
4530                 rgctx_lazy_fetch_trampoline_hash = g_hash_table_new (NULL, NULL);
4531         g_hash_table_insert (rgctx_lazy_fetch_trampoline_hash, GUINT_TO_POINTER (offset), ptr);
4532         mono_jit_unlock ();
4533
4534         return ptr;
4535 }       
4536
4537 static MonoInst*
4538 lazy_fetch_rgctx_direct_field (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *rgc_ptr, int offset, unsigned char *ip)
4539 {
4540         MonoMethodSignature *sig = helper_sig_rgctx_lazy_fetch_trampoline;
4541         guint8 *tramp = create_rgctx_lazy_fetch_trampoline (MONO_RGCTX_ENCODE_DIRECT_OFFSET (offset));
4542         int temp;
4543         MonoInst *field;
4544
4545         temp = mono_emit_native_call (cfg, bblock, tramp, sig, &rgc_ptr, ip, FALSE, FALSE); 
4546
4547         NEW_TEMPLOAD (cfg, field, temp);
4548
4549         return field;
4550 }
4551
4552 static MonoInst*
4553 lazy_fetch_rgctx_indirect_field (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *rgc_ptr, int offset, unsigned char *ip)
4554 {
4555         MonoMethodSignature *sig = helper_sig_rgctx_lazy_fetch_trampoline;
4556         guint8 *tramp = create_rgctx_lazy_fetch_trampoline (MONO_RGCTX_ENCODE_INDIRECT_OFFSET (offset));
4557         int temp;
4558         MonoInst *field;
4559
4560         temp = mono_emit_native_call (cfg, bblock, tramp, sig, &rgc_ptr, ip, FALSE, FALSE); 
4561
4562         NEW_TEMPLOAD (cfg, field, temp);
4563
4564         return field;
4565 }
4566
4567 /*
4568  * Generates ((MonoRuntimeGenericSuperInfo*)rgc)[-depth].XXX where XXX
4569  * is specified by rgctx_type.
4570  */
4571 static MonoInst*
4572 get_runtime_generic_context_super_ptr (MonoCompile *cfg, MonoBasicBlock *bblock,
4573         MonoInst *rgc_ptr, int depth, int rgctx_type, unsigned char *ip)
4574 {
4575         int field_offset_const, offset;
4576
4577         g_assert (depth >= 1);
4578
4579         switch (rgctx_type) {
4580         case MONO_RGCTX_INFO_STATIC_DATA :
4581                 field_offset_const = G_STRUCT_OFFSET (MonoRuntimeGenericSuperInfo, static_data);
4582                 break;
4583         case MONO_RGCTX_INFO_KLASS :
4584                 field_offset_const = G_STRUCT_OFFSET (MonoRuntimeGenericSuperInfo, klass);
4585                 break;
4586         case MONO_RGCTX_INFO_VTABLE:
4587                 field_offset_const = G_STRUCT_OFFSET (MonoRuntimeGenericSuperInfo, vtable);
4588                 break;
4589         default :
4590                 g_assert_not_reached ();
4591         }
4592
4593         offset = -depth * sizeof (MonoRuntimeGenericSuperInfo) + field_offset_const;
4594
4595         return lazy_fetch_rgctx_direct_field (cfg, bblock, rgc_ptr, offset, ip);
4596 }
4597
4598 static int
4599 get_rgctx_arg_info_field_offset (int rgctx_type)
4600 {
4601         switch (rgctx_type) {
4602         case MONO_RGCTX_INFO_STATIC_DATA :
4603                 return G_STRUCT_OFFSET (MonoRuntimeGenericArgInfo, static_data);
4604         case MONO_RGCTX_INFO_KLASS:
4605                 return G_STRUCT_OFFSET (MonoRuntimeGenericArgInfo, klass);
4606         case MONO_RGCTX_INFO_VTABLE :
4607                 return G_STRUCT_OFFSET (MonoRuntimeGenericArgInfo, vtable);
4608         default:
4609                 g_assert_not_reached ();
4610         }
4611 }
4612
4613 /*
4614  * Generates rgc->arg_infos [arg_num].XXX where XXX is specified by
4615  * rgctx_type;
4616  */
4617 static MonoInst*
4618 get_runtime_generic_context_arg_ptr (MonoCompile *cfg, MonoBasicBlock *bblock,
4619         MonoInst *rgc_ptr, int arg_num, int rgctx_type, unsigned char *ip)
4620 {
4621         int arg_info_offset, arg_info_field_offset, offset;
4622
4623         g_assert (arg_num >= 0);
4624         //g_assert (!lazy);
4625
4626         arg_info_offset = G_STRUCT_OFFSET (MonoRuntimeGenericContext, arg_infos) +
4627                 arg_num * sizeof (MonoRuntimeGenericArgInfo);
4628
4629         arg_info_field_offset = get_rgctx_arg_info_field_offset (rgctx_type);
4630
4631         offset = arg_info_offset + arg_info_field_offset;
4632
4633         return lazy_fetch_rgctx_direct_field (cfg, bblock, rgc_ptr, offset, ip);
4634 }
4635
4636 /*
4637  * Generates rgc->other_infos [index].XXX if index is non-negative, or
4638  * rgc->extra_other_infos [-index + 1] if index is negative.  XXX is
4639  * specified by rgctx_type;
4640  */
4641 static MonoInst*
4642 get_runtime_generic_context_other_table_ptr (MonoCompile *cfg, MonoBasicBlock *bblock,
4643         MonoInst *rgc_ptr, int index, unsigned char *ip)
4644 {
4645         if (index < MONO_RGCTX_MAX_OTHER_INFOS) {
4646                 int other_type_offset;
4647
4648                 other_type_offset = G_STRUCT_OFFSET (MonoRuntimeGenericContext, other_infos) +
4649                         index * sizeof (gpointer);
4650
4651                 return lazy_fetch_rgctx_direct_field (cfg, bblock, rgc_ptr, other_type_offset, ip);
4652         } else {
4653                 int slot_offset;
4654
4655                 slot_offset = (index - MONO_RGCTX_MAX_OTHER_INFOS) * sizeof (gpointer);
4656
4657                 return lazy_fetch_rgctx_indirect_field (cfg, bblock, rgc_ptr, slot_offset, ip);
4658         }
4659 }
4660
4661 static MonoInst*
4662 get_runtime_generic_context_other_ptr (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *bblock,
4663         MonoInst *rgc_ptr, guint32 token, int token_source, int rgctx_type, unsigned char *ip, int index)
4664 {
4665         MonoInst *args [6];
4666         int temp;
4667         MonoInst *result;
4668
4669         g_assert (method->wrapper_type == MONO_WRAPPER_NONE);
4670
4671         NEW_CLASSCONST (cfg, args [0], method->klass);
4672         args [1] = rgc_ptr;
4673         NEW_ICONST (cfg, args [2], token);
4674         NEW_ICONST (cfg, args [3], token_source);
4675         NEW_ICONST (cfg, args [4], rgctx_type);
4676         NEW_ICONST (cfg, args [5], index);
4677
4678         temp = mono_emit_jit_icall (cfg, bblock, mono_helper_get_rgctx_other_ptr, args, ip);
4679         NEW_TEMPLOAD (cfg, result, temp);
4680
4681         return result;
4682 }
4683
4684 static MonoInst*
4685 get_runtime_generic_context_ptr (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *bblock,
4686         MonoClass *klass, guint32 type_token, int token_source, MonoGenericContext *generic_context, MonoInst *rgctx,
4687         int rgctx_type, unsigned char *ip)
4688 {
4689         int arg_num = -1;
4690         int relation = mono_class_generic_class_relation (klass, rgctx_type, method->klass, generic_context, &arg_num);
4691
4692         switch (relation) {
4693         case MINI_GENERIC_CLASS_RELATION_SELF: {
4694                 int depth = klass->idepth;
4695                 return get_runtime_generic_context_super_ptr (cfg, bblock, rgctx, depth, rgctx_type, ip);
4696         }
4697         case MINI_GENERIC_CLASS_RELATION_ARGUMENT:
4698                 return get_runtime_generic_context_arg_ptr (cfg, bblock, rgctx, arg_num, rgctx_type, ip);
4699         case MINI_GENERIC_CLASS_RELATION_OTHER_TABLE:
4700                 return get_runtime_generic_context_other_table_ptr (cfg, bblock, rgctx, arg_num, ip);
4701         case MINI_GENERIC_CLASS_RELATION_OTHER:
4702                 return get_runtime_generic_context_other_ptr (cfg, method, bblock, rgctx,
4703                         type_token, token_source, rgctx_type, ip, arg_num);
4704         default:
4705                 g_assert_not_reached ();
4706                 return NULL;
4707         }
4708 }
4709
4710 static MonoInst*
4711 get_runtime_generic_context_method (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *bblock,
4712         MonoMethod *cmethod, MonoGenericContext *generic_context, MonoInst *rgctx, int rgctx_type, unsigned char *ip)
4713 {
4714         int arg_num = mono_class_lookup_or_register_other_info (method->klass, cmethod, rgctx_type, generic_context);
4715
4716         return get_runtime_generic_context_other_table_ptr (cfg, bblock, rgctx, arg_num, ip);
4717 }
4718
4719 static gboolean
4720 generic_class_is_reference_type (MonoCompile *cfg, MonoClass *klass)
4721 {
4722         MonoType *type = mini_get_basic_type_from_generic (cfg->generic_sharing_context, &klass->byval_arg);
4723
4724         return MONO_TYPE_IS_REFERENCE (type);
4725 }
4726
4727 static MiniVerifierMode verifier_mode = MINI_VERIFIER_MODE_OFF;
4728
4729 void
4730 mini_verifier_set_mode (MiniVerifierMode mode)
4731 {
4732        verifier_mode = mode;
4733 }
4734
4735 /*
4736  * Return TRUE if method don't need to be verifiable.
4737  * TODO check appdomain security flags 
4738  */
4739 static gboolean
4740 check_method_full_trust (MonoMethod *method)
4741 {
4742         return method->klass->image->assembly->in_gac || method->klass->image == mono_defaults.corlib || verifier_mode < MINI_VERIFIER_MODE_VERIFIABLE;
4743 }
4744
4745 /*
4746  * Return TRUE if method should be verifier
4747  * FIXME we should be able to check gac'ed code for validity
4748  */
4749 static gboolean
4750 check_for_method_verify (MonoMethod *method) {
4751         return (verifier_mode > MINI_VERIFIER_MODE_OFF) && !method->klass->image->assembly->in_gac && method->klass->image != mono_defaults.corlib && method->wrapper_type == MONO_WRAPPER_NONE;
4752 }
4753
4754 /*
4755  * mini_method_verify:
4756  * 
4757  * Verify the method using the new verfier.
4758  * 
4759  * Returns true if the method is invalid. 
4760  */
4761 static gboolean
4762 mini_method_verify (MonoCompile *cfg, MonoMethod *method)
4763 {
4764         GSList *tmp, *res;
4765         gboolean is_fulltrust = check_method_full_trust (method);
4766         MonoLoaderError *error;
4767
4768         if (!check_for_method_verify (method))
4769                 return FALSE;
4770
4771         res = mono_method_verify (method, 
4772                 (verifier_mode != MINI_VERIFIER_MODE_STRICT ? MONO_VERIFY_NON_STRICT: 0)
4773                 | (!is_fulltrust ? MONO_VERIFY_FAIL_FAST : 0)
4774                 | (cfg->skip_visibility ? MONO_VERIFY_SKIP_VISIBILITY : 0));
4775
4776         if ((error = mono_loader_get_last_error ())) {
4777                 cfg->exception_type = error->exception_type;
4778                 if (res)
4779                         mono_free_verify_list (res);
4780                 return TRUE;
4781         }
4782
4783         if (res) { 
4784                 for (tmp = res; tmp; tmp = tmp->next) {
4785                         MonoVerifyInfoExtended *info = (MonoVerifyInfoExtended *)tmp->data;
4786                         if (info->info.status == MONO_VERIFY_ERROR) {
4787                                 cfg->exception_type = info->exception_type;
4788                                 cfg->exception_message = g_strdup (info->info.message);
4789                                 mono_free_verify_list (res);
4790                                 return TRUE;
4791                         }
4792                         if (info->info.status == MONO_VERIFY_NOT_VERIFIABLE && !is_fulltrust) {
4793                                 cfg->exception_type = info->exception_type;
4794                                 cfg->exception_message = g_strdup (info->info.message);
4795                                 mono_free_verify_list (res);
4796                                 return TRUE;
4797                         }
4798                 }
4799                 mono_free_verify_list (res);
4800         }
4801         return FALSE;
4802 }
4803
4804 /*
4805  * mono_method_to_ir: translates IL into basic blocks containing trees
4806  */
4807 static int
4808 mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
4809                    int locals_offset, MonoInst *return_var, GList *dont_inline, MonoInst **inline_args, 
4810                    guint inline_offset, gboolean is_virtual_call)
4811 {
4812         MonoInst *zero_int32, *zero_int64, *zero_ptr, *zero_obj, *zero_r8;
4813         MonoInst *ins, **sp, **stack_start;
4814         MonoBasicBlock *bblock, *tblock = NULL, *init_localsbb = NULL;
4815         MonoMethod *cmethod;
4816         MonoInst **arg_array;
4817         MonoMethodHeader *header;
4818         MonoImage *image;
4819         guint32 token, ins_flag;
4820         MonoClass *klass;
4821         MonoClass *constrained_call = NULL;
4822         unsigned char *ip, *end, *target, *err_pos;
4823         static double r8_0 = 0.0;
4824         MonoMethodSignature *sig;
4825         MonoGenericContext *generic_context = NULL;
4826         MonoGenericContainer *generic_container = NULL;
4827         MonoType **param_types;
4828         GList *bb_recheck = NULL, *tmp;
4829         int i, n, start_new_bblock, ialign;
4830         int num_calls = 0, inline_costs = 0;
4831         int breakpoint_id = 0;
4832         guint32 align;
4833         guint real_offset, num_args;
4834         MonoBoolean security, pinvoke;
4835         MonoSecurityManager* secman = NULL;
4836         MonoDeclSecurityActions actions;
4837         GSList *class_inits = NULL;
4838         gboolean dont_verify, dont_verify_stloc;
4839
4840         /* serialization and xdomain stuff may need access to private fields and methods */
4841         dont_verify = method->klass->image->assembly->corlib_internal? TRUE: FALSE;
4842         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE;
4843         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH;
4844         dont_verify |= method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE; /* bug #77896 */
4845         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP;
4846         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP_INVOKE;
4847
4848         /* turn off visibility checks for smcs */
4849         dont_verify |= mono_security_get_mode () == MONO_SECURITY_MODE_SMCS_HACK;
4850
4851         /* still some type unsafety issues in marshal wrappers... (unknown is PtrToStructure) */
4852         dont_verify_stloc = method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE;
4853         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_UNKNOWN;
4854         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED;
4855
4856         /* Not turned on yet */
4857         cfg->dont_verify_stack_merge = TRUE;
4858
4859         image = method->klass->image;
4860         header = mono_method_get_header (method);
4861         generic_container = method->generic_container;
4862         sig = mono_method_signature (method);
4863         num_args = sig->hasthis + sig->param_count;
4864         ip = (unsigned char*)header->code;
4865         cfg->cil_start = ip;
4866         end = ip + header->code_size;
4867         mono_jit_stats.cil_code_size += header->code_size;
4868
4869         if (!dont_verify && mini_method_verify (cfg, method))
4870                 goto exception_exit;
4871
4872         if (sig->is_inflated)
4873                 generic_context = mono_method_get_context (method);
4874         else if (generic_container)
4875                 generic_context = &generic_container->context;
4876
4877         if (!cfg->generic_sharing_context)
4878                 g_assert (!sig->has_type_parameters);
4879
4880         if (cfg->method == method)
4881                 real_offset = 0;
4882         else
4883                 real_offset = inline_offset;
4884
4885         cfg->cil_offset_to_bb = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoBasicBlock*) * header->code_size);
4886         cfg->cil_offset_to_bb_len = header->code_size;
4887
4888         if (cfg->verbose_level > 2)
4889                 g_print ("method to IR %s\n", mono_method_full_name (method, TRUE));
4890
4891         dont_inline = g_list_prepend (dont_inline, method);
4892         if (cfg->method == method) {
4893
4894                 if (cfg->prof_options & MONO_PROFILE_INS_COVERAGE)
4895                         cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, header->code_size);
4896
4897                 /* ENTRY BLOCK */
4898                 NEW_BBLOCK (cfg, start_bblock);
4899                 cfg->bb_entry = start_bblock;
4900                 start_bblock->cil_code = NULL;
4901                 start_bblock->cil_length = 0;
4902                 start_bblock->block_num = cfg->num_bblocks++;
4903
4904                 /* EXIT BLOCK */
4905                 NEW_BBLOCK (cfg, end_bblock);
4906                 cfg->bb_exit = end_bblock;
4907                 end_bblock->cil_code = NULL;
4908                 end_bblock->cil_length = 0;
4909                 end_bblock->block_num = cfg->num_bblocks++;
4910                 g_assert (cfg->num_bblocks == 2);
4911
4912                 arg_array = alloca (sizeof (MonoInst *) * num_args);
4913                 for (i = num_args - 1; i >= 0; i--)
4914                         arg_array [i] = cfg->varinfo [i];
4915
4916                 if (header->num_clauses) {
4917                         cfg->spvars = g_hash_table_new (NULL, NULL);
4918                         cfg->exvars = g_hash_table_new (NULL, NULL);
4919                 }
4920                 /* handle exception clauses */
4921                 for (i = 0; i < header->num_clauses; ++i) {
4922                         MonoBasicBlock *try_bb;
4923                         MonoExceptionClause *clause = &header->clauses [i];
4924
4925                         if ((method->flags & METHOD_ATTRIBUTE_STATIC) &&
4926                                         clause->flags != MONO_EXCEPTION_CLAUSE_FILTER &&
4927                                         clause->data.catch_class &&
4928                                         cfg->generic_sharing_context &&
4929                                         mono_class_check_context_used (clause->data.catch_class)) {
4930                                 mono_get_rgctx_var (cfg);
4931                         }
4932
4933                         GET_BBLOCK (cfg, try_bb, ip + clause->try_offset);
4934                         try_bb->real_offset = clause->try_offset;
4935                         GET_BBLOCK (cfg, tblock, ip + clause->handler_offset);
4936                         tblock->real_offset = clause->handler_offset;
4937                         tblock->flags |= BB_EXCEPTION_HANDLER;
4938
4939                         link_bblock (cfg, try_bb, tblock);
4940
4941                         if (*(ip + clause->handler_offset) == CEE_POP)
4942                                 tblock->flags |= BB_EXCEPTION_DEAD_OBJ;
4943
4944                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY ||
4945                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER ||
4946                             clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) {
4947                                 MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
4948                                 MONO_ADD_INS (tblock, ins);
4949
4950                                 /* todo: is a fault block unsafe to optimize? */
4951                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
4952                                         tblock->flags |= BB_EXCEPTION_UNSAFE;
4953                         }
4954
4955
4956                         /*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);
4957                           while (p < end) {
4958                           g_print ("%s", mono_disasm_code_one (NULL, method, p, &p));
4959                           }*/
4960                         /* catch and filter blocks get the exception object on the stack */
4961                         if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE ||
4962                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
4963                                 MonoInst *load, *dummy_use;
4964
4965                                 /* mostly like handle_stack_args (), but just sets the input args */
4966                                 /* g_print ("handling clause at IL_%04x\n", clause->handler_offset); */
4967                                 tblock->in_scount = 1;
4968                                 tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
4969                                 tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
4970                                 tblock->stack_state = mono_mempool_alloc (cfg->mempool, sizeof (MonoStackSlot));
4971                                 tblock->stack_state [0].type = STACK_OBJ;
4972                                 /* FIXME? */
4973                                 tblock->stack_state [0].klass = mono_defaults.object_class;
4974
4975                                 /* 
4976                                  * Add a dummy use for the exvar so its liveness info will be
4977                                  * correct.
4978                                  */
4979                                 NEW_TEMPLOAD (cfg, load, tblock->in_stack [0]->inst_c0);
4980                                 NEW_DUMMY_USE (cfg, dummy_use, load);
4981                                 MONO_ADD_INS (tblock, dummy_use);
4982                                 
4983                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
4984                                         GET_BBLOCK (cfg, tblock, ip + clause->data.filter_offset);
4985                                         tblock->real_offset = clause->data.filter_offset;
4986                                         tblock->in_scount = 1;
4987                                         tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
4988                                         tblock->stack_state = mono_mempool_alloc (cfg->mempool, sizeof (MonoStackSlot));
4989                                         tblock->stack_state [0].type = STACK_OBJ;
4990                                         /* FIXME? */
4991                                         tblock->stack_state [0].klass = mono_defaults.object_class;
4992
4993                                         /* The filter block shares the exvar with the handler block */
4994                                         tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
4995                                         MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
4996                                         MONO_ADD_INS (tblock, ins);
4997                                 }
4998                         }
4999                 }
5000         } else {
5001                 arg_array = alloca (sizeof (MonoInst *) * num_args);
5002                 mono_save_args (cfg, start_bblock, sig, inline_args, arg_array);
5003         }
5004
5005         /* FIRST CODE BLOCK */
5006         NEW_BBLOCK (cfg, bblock);
5007         bblock->cil_code = ip;
5008
5009         ADD_BBLOCK (cfg, bblock);
5010
5011         if (cfg->method == method) {
5012                 breakpoint_id = mono_debugger_method_has_breakpoint (method);
5013                 if (breakpoint_id && (mono_debug_format != MONO_DEBUG_FORMAT_DEBUGGER)) {
5014                         MONO_INST_NEW (cfg, ins, OP_BREAK);
5015                         MONO_ADD_INS (bblock, ins);
5016                 }
5017         }
5018
5019         if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS)
5020                 secman = mono_security_manager_get_methods ();
5021
5022         security = (secman && mono_method_has_declsec (method));
5023         /* at this point having security doesn't mean we have any code to generate */
5024         if (security && (cfg->method == method)) {
5025                 /* Only Demand, NonCasDemand and DemandChoice requires code generation.
5026                  * And we do not want to enter the next section (with allocation) if we
5027                  * have nothing to generate */
5028                 security = mono_declsec_get_demands (method, &actions);
5029         }
5030
5031         /* we must Demand SecurityPermission.Unmanaged before P/Invoking */
5032         pinvoke = (secman && (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE));
5033         if (pinvoke) {
5034                 MonoMethod *wrapped = mono_marshal_method_from_wrapper (method);
5035                 if (wrapped && (wrapped->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5036                         MonoCustomAttrInfo* custom = mono_custom_attrs_from_method (wrapped);
5037
5038                         /* unless the method or it's class has the [SuppressUnmanagedCodeSecurity] attribute */
5039                         if (custom && mono_custom_attrs_has_attr (custom, secman->suppressunmanagedcodesecurity)) {
5040                                 pinvoke = FALSE;
5041                         }
5042                         if (custom)
5043                                 mono_custom_attrs_free (custom);
5044
5045                         if (pinvoke) {
5046                                 custom = mono_custom_attrs_from_class (wrapped->klass);
5047                                 if (custom && mono_custom_attrs_has_attr (custom, secman->suppressunmanagedcodesecurity)) {
5048                                         pinvoke = FALSE;
5049                                 }
5050                                 if (custom)
5051                                         mono_custom_attrs_free (custom);
5052                         }
5053                 } else {
5054                         /* not a P/Invoke after all */
5055                         pinvoke = FALSE;
5056                 }
5057         }
5058         
5059         if ((header->init_locals || (cfg->method == method && (cfg->opt & MONO_OPT_SHARED))) || cfg->compile_aot || security || pinvoke) {
5060                 /* we use a separate basic block for the initialization code */
5061                 NEW_BBLOCK (cfg, init_localsbb);
5062                 cfg->bb_init = init_localsbb;
5063                 init_localsbb->real_offset = real_offset;
5064                 start_bblock->next_bb = init_localsbb;
5065                 init_localsbb->next_bb = bblock;
5066                 link_bblock (cfg, start_bblock, init_localsbb);
5067                 link_bblock (cfg, init_localsbb, bblock);
5068                 init_localsbb->block_num = cfg->num_bblocks++;
5069         } else {
5070                 start_bblock->next_bb = bblock;
5071                 link_bblock (cfg, start_bblock, bblock);
5072         }
5073
5074         /* at this point we know, if security is TRUE, that some code needs to be generated */
5075         if (security && (cfg->method == method)) {
5076                 MonoInst *args [2];
5077
5078                 mono_jit_stats.cas_demand_generation++;
5079
5080                 if (actions.demand.blob) {
5081                         /* Add code for SecurityAction.Demand */
5082                         NEW_DECLSECCONST (cfg, args[0], image, actions.demand);
5083                         NEW_ICONST (cfg, args [1], actions.demand.size);
5084                         /* Calls static void SecurityManager.InternalDemand (byte* permissions, int size); */
5085                         mono_emit_method_call_spilled (cfg, init_localsbb, secman->demand, mono_method_signature (secman->demand), args, ip, NULL);
5086                 }
5087                 if (actions.noncasdemand.blob) {
5088                         /* CLR 1.x uses a .noncasdemand (but 2.x doesn't) */
5089                         /* For Mono we re-route non-CAS Demand to Demand (as the managed code must deal with it anyway) */
5090                         NEW_DECLSECCONST (cfg, args[0], image, actions.noncasdemand);
5091                         NEW_ICONST (cfg, args [1], actions.noncasdemand.size);
5092                         /* Calls static void SecurityManager.InternalDemand (byte* permissions, int size); */
5093                         mono_emit_method_call_spilled (cfg, init_localsbb, secman->demand, mono_method_signature (secman->demand), args, ip, NULL);
5094                 }
5095                 if (actions.demandchoice.blob) {
5096                         /* New in 2.0, Demand must succeed for one of the permissions (i.e. not all) */
5097                         NEW_DECLSECCONST (cfg, args[0], image, actions.demandchoice);
5098                         NEW_ICONST (cfg, args [1], actions.demandchoice.size);
5099                         /* Calls static void SecurityManager.InternalDemandChoice (byte* permissions, int size); */
5100                         mono_emit_method_call_spilled (cfg, init_localsbb, secman->demandchoice, mono_method_signature (secman->demandchoice), args, ip, NULL);
5101                 }
5102         }
5103
5104         /* we must Demand SecurityPermission.Unmanaged before p/invoking */
5105         if (pinvoke) {
5106                 mono_emit_method_call_spilled (cfg, init_localsbb, secman->demandunmanaged, mono_method_signature (secman->demandunmanaged), NULL, ip, NULL);
5107         }
5108
5109         if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
5110                 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
5111                         MonoMethod *wrapped = mono_marshal_method_from_wrapper (method);
5112                         if (wrapped && (wrapped->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5113                                 if (!(method->klass && method->klass->image &&
5114                                                 mono_security_core_clr_is_platform_image (method->klass->image))) {
5115                                         emit_throw_method_access_exception (cfg, method, wrapped, bblock, ip);
5116                                 }
5117                         }
5118                 }
5119                 if (!method_is_safe (method))
5120                         emit_throw_verification_exception (cfg, bblock, ip);
5121         }
5122
5123         if (header->code_size == 0)
5124                 UNVERIFIED;
5125
5126         if (get_basic_blocks (cfg, header, real_offset, ip, end, &err_pos)) {
5127                 ip = err_pos;
5128                 UNVERIFIED;
5129         }
5130
5131         if (cfg->method == method)
5132                 mono_debug_init_method (cfg, bblock, breakpoint_id);
5133
5134         param_types = mono_mempool_alloc (cfg->mempool, sizeof (MonoType*) * num_args);
5135         if (sig->hasthis)
5136                 param_types [0] = method->klass->valuetype?&method->klass->this_arg:&method->klass->byval_arg;
5137         for (n = 0; n < sig->param_count; ++n)
5138                 param_types [n + sig->hasthis] = sig->params [n];
5139         for (n = 0; n < header->num_locals; ++n) {
5140                 if (header->locals [n]->type == MONO_TYPE_VOID && !header->locals [n]->byref)
5141                         UNVERIFIED;
5142         }
5143         class_inits = NULL;
5144
5145         /* do this somewhere outside - not here */
5146         NEW_ICONST (cfg, zero_int32, 0);
5147         NEW_ICONST (cfg, zero_int64, 0);
5148         zero_int64->type = STACK_I8;
5149         NEW_PCONST (cfg, zero_ptr, 0);
5150         NEW_PCONST (cfg, zero_obj, 0);
5151         zero_obj->type = STACK_OBJ;
5152
5153         MONO_INST_NEW (cfg, zero_r8, OP_R8CONST);
5154         zero_r8->type = STACK_R8;
5155         zero_r8->inst_p0 = &r8_0;
5156
5157         /* add a check for this != NULL to inlined methods */
5158         if (is_virtual_call) {
5159                 MONO_INST_NEW (cfg, ins, OP_CHECK_THIS);
5160                 NEW_ARGLOAD (cfg, ins->inst_left, 0);
5161                 ins->cil_code = ip;
5162                 MONO_ADD_INS (bblock, ins);
5163         }
5164
5165         /* we use a spare stack slot in SWITCH and NEWOBJ and others */
5166         stack_start = sp = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (header->max_stack + 1));
5167
5168         ins_flag = 0;
5169         start_new_bblock = 0;
5170         while (ip < end) {
5171
5172                 if (cfg->method == method)
5173                         real_offset = ip - header->code;
5174                 else
5175                         real_offset = inline_offset;
5176
5177                 if (start_new_bblock) {
5178                         bblock->cil_length = ip - bblock->cil_code;
5179                         if (start_new_bblock == 2) {
5180                                 g_assert (ip == tblock->cil_code);
5181                         } else {
5182                                 GET_BBLOCK (cfg, tblock, ip);
5183                         }
5184                         bblock->next_bb = tblock;
5185                         bblock = tblock;
5186                         start_new_bblock = 0;
5187                         for (i = 0; i < bblock->in_scount; ++i) {
5188                                 if (cfg->verbose_level > 3)
5189                                         g_print ("loading %d from temp %d\n", i, (int)bblock->in_stack [i]->inst_c0);                                           
5190                                 NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
5191                                 *sp++ = ins;
5192                         }
5193                         g_slist_free (class_inits);
5194                         class_inits = NULL;
5195                 } else {
5196                         if ((tblock = cfg->cil_offset_to_bb [ip - cfg->cil_start]) && (tblock != bblock)) {
5197                                 link_bblock (cfg, bblock, tblock);
5198                                 if (sp != stack_start) {
5199                                         handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5200                                         sp = stack_start;
5201                                         CHECK_UNVERIFIABLE (cfg);
5202                                 }
5203                                 bblock->next_bb = tblock;
5204                                 bblock = tblock;
5205                                 for (i = 0; i < bblock->in_scount; ++i) {
5206                                         if (cfg->verbose_level > 3)
5207                                                 g_print ("loading %d from temp %d\n", i, (int)bblock->in_stack [i]->inst_c0);                                           
5208                                         NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
5209                                         *sp++ = ins;
5210                                 }
5211                                 g_slist_free (class_inits);
5212                                 class_inits = NULL;
5213                         }
5214                 }
5215
5216                 bblock->real_offset = real_offset;
5217
5218                 if ((cfg->method == method) && cfg->coverage_info) {
5219                         MonoInst *store, *one;
5220                         guint32 cil_offset = ip - header->code;
5221                         cfg->coverage_info->data [cil_offset].cil_code = ip;
5222
5223                         /* TODO: Use an increment here */
5224                         NEW_ICONST (cfg, one, 1);
5225                         one->cil_code = ip;
5226
5227                         NEW_PCONST (cfg, ins, &(cfg->coverage_info->data [cil_offset].count));
5228                         ins->cil_code = ip;
5229
5230                         MONO_INST_NEW (cfg, store, CEE_STIND_I);
5231                         store->cil_code = ip;
5232                         store->inst_left = ins;
5233                         store->inst_right = one;
5234
5235                         MONO_ADD_INS (bblock, store);
5236                 }
5237
5238                 if (cfg->verbose_level > 3)
5239                         g_print ("converting (in B%d: stack: %d) %s", bblock->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
5240
5241                 switch (*ip) {
5242                 case CEE_NOP:
5243                         MONO_INST_NEW (cfg, ins, OP_NOP);
5244                         ins->cil_code = ip++;
5245                         MONO_ADD_INS (bblock, ins);
5246                         break;
5247                 case CEE_BREAK:
5248                         MONO_INST_NEW (cfg, ins, OP_BREAK);
5249                         ins->cil_code = ip++;
5250                         MONO_ADD_INS (bblock, ins);
5251                         break;
5252                 case CEE_LDARG_0:
5253                 case CEE_LDARG_1:
5254                 case CEE_LDARG_2:
5255                 case CEE_LDARG_3:
5256                         CHECK_STACK_OVF (1);
5257                         n = (*ip)-CEE_LDARG_0;
5258                         CHECK_ARG (n);
5259                         NEW_ARGLOAD (cfg, ins, n);
5260                         LDARG_SOFT_FLOAT (cfg, ins, n, ip);
5261                         ins->cil_code = ip++;
5262                         *sp++ = ins;
5263                         break;
5264                 case CEE_LDLOC_0:
5265                 case CEE_LDLOC_1:
5266                 case CEE_LDLOC_2:
5267                 case CEE_LDLOC_3:
5268                         CHECK_STACK_OVF (1);
5269                         n = (*ip)-CEE_LDLOC_0;
5270                         CHECK_LOCAL (n);
5271                         NEW_LOCLOAD (cfg, ins, n);
5272                         LDLOC_SOFT_FLOAT (cfg, ins, n, ip);
5273                         ins->cil_code = ip++;
5274                         *sp++ = ins;
5275                         break;
5276                 case CEE_STLOC_0:
5277                 case CEE_STLOC_1:
5278                 case CEE_STLOC_2:
5279                 case CEE_STLOC_3:
5280                         CHECK_STACK (1);
5281                         n = (*ip)-CEE_STLOC_0;
5282                         CHECK_LOCAL (n);
5283                         --sp;
5284                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5285                         NEW_LOCSTORE (cfg, ins, n, *sp);
5286                         ins->cil_code = ip;
5287                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
5288                                 UNVERIFIED;
5289                         STLOC_SOFT_FLOAT (cfg, ins, n, ip);
5290                         if (ins->opcode == CEE_STOBJ) {
5291                                 NEW_LOCLOADA (cfg, ins, n);
5292                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
5293                         } else
5294                                 MONO_ADD_INS (bblock, ins);
5295                         ++ip;
5296                         inline_costs += 1;
5297                         break;
5298                 case CEE_LDARG_S:
5299                         CHECK_OPSIZE (2);
5300                         CHECK_STACK_OVF (1);
5301                         CHECK_ARG (ip [1]);
5302                         NEW_ARGLOAD (cfg, ins, ip [1]);
5303                         LDARG_SOFT_FLOAT (cfg, ins, ip [1], ip);
5304                         ins->cil_code = ip;
5305                         *sp++ = ins;
5306                         ip += 2;
5307                         break;
5308                 case CEE_LDARGA_S:
5309                         CHECK_OPSIZE (2);
5310                         CHECK_STACK_OVF (1);
5311                         CHECK_ARG (ip [1]);
5312                         NEW_ARGLOADA (cfg, ins, ip [1]);
5313                         ins->cil_code = ip;
5314                         *sp++ = ins;
5315                         ip += 2;
5316                         break;
5317                 case CEE_STARG_S:
5318                         CHECK_OPSIZE (2);
5319                         CHECK_STACK (1);
5320                         --sp;
5321                         CHECK_ARG (ip [1]);
5322                         NEW_ARGSTORE (cfg, ins, ip [1], *sp);
5323                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5324                         ins->cil_code = ip;
5325                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [ip [1]], *sp))
5326                                 UNVERIFIED;
5327                         STARG_SOFT_FLOAT (cfg, ins, ip [1], ip);
5328                         if (ins->opcode == CEE_STOBJ) {
5329                                 NEW_ARGLOADA (cfg, ins, ip [1]);
5330                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
5331                         } else
5332                                 MONO_ADD_INS (bblock, ins);
5333                         ip += 2;
5334                         break;
5335                 case CEE_LDLOC_S:
5336                         CHECK_OPSIZE (2);
5337                         CHECK_STACK_OVF (1);
5338                         CHECK_LOCAL (ip [1]);
5339                         NEW_LOCLOAD (cfg, ins, ip [1]);
5340                         LDLOC_SOFT_FLOAT (cfg, ins, ip [1], ip);
5341                         ins->cil_code = ip;
5342                         *sp++ = ins;
5343                         ip += 2;
5344                         break;
5345                 case CEE_LDLOCA_S:
5346                         CHECK_OPSIZE (2);
5347                         CHECK_STACK_OVF (1);
5348                         CHECK_LOCAL (ip [1]);
5349                         NEW_LOCLOADA (cfg, ins, ip [1]);
5350                         ins->cil_code = ip;
5351                         *sp++ = ins;
5352                         ip += 2;
5353                         break;
5354                 case CEE_STLOC_S:
5355                         CHECK_OPSIZE (2);
5356                         CHECK_STACK (1);
5357                         --sp;
5358                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5359                         CHECK_LOCAL (ip [1]);
5360                         NEW_LOCSTORE (cfg, ins, ip [1], *sp);
5361                         ins->cil_code = ip;
5362                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [ip [1]], *sp))
5363                                 UNVERIFIED;
5364                         STLOC_SOFT_FLOAT (cfg, ins, ip [1], ip);
5365                         if (ins->opcode == CEE_STOBJ) {
5366                                 NEW_LOCLOADA (cfg, ins, ip [1]);
5367                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
5368                         } else
5369                                 MONO_ADD_INS (bblock, ins);
5370                         ip += 2;
5371                         inline_costs += 1;
5372                         break;
5373                 case CEE_LDNULL:
5374                         CHECK_STACK_OVF (1);
5375                         NEW_PCONST (cfg, ins, NULL);
5376                         ins->cil_code = ip;
5377                         ins->type = STACK_OBJ;
5378                         ++ip;
5379                         *sp++ = ins;
5380                         break;
5381                 case CEE_LDC_I4_M1:
5382                         CHECK_STACK_OVF (1);
5383                         NEW_ICONST (cfg, ins, -1);
5384                         ins->cil_code = ip;
5385                         ++ip;
5386                         *sp++ = ins;
5387                         break;
5388                 case CEE_LDC_I4_0:
5389                 case CEE_LDC_I4_1:
5390                 case CEE_LDC_I4_2:
5391                 case CEE_LDC_I4_3:
5392                 case CEE_LDC_I4_4:
5393                 case CEE_LDC_I4_5:
5394                 case CEE_LDC_I4_6:
5395                 case CEE_LDC_I4_7:
5396                 case CEE_LDC_I4_8:
5397                         CHECK_STACK_OVF (1);
5398                         NEW_ICONST (cfg, ins, (*ip) - CEE_LDC_I4_0);
5399                         ins->cil_code = ip;
5400                         ++ip;
5401                         *sp++ = ins;
5402                         break;
5403                 case CEE_LDC_I4_S:
5404                         CHECK_OPSIZE (2);
5405                         CHECK_STACK_OVF (1);
5406                         ++ip;
5407                         NEW_ICONST (cfg, ins, *((signed char*)ip));
5408                         ins->cil_code = ip;
5409                         ++ip;
5410                         *sp++ = ins;
5411                         break;
5412                 case CEE_LDC_I4:
5413                         CHECK_OPSIZE (5);
5414                         CHECK_STACK_OVF (1);
5415                         NEW_ICONST (cfg, ins, (gint32)read32 (ip + 1));
5416                         ins->cil_code = ip;
5417                         ip += 5;
5418                         *sp++ = ins;
5419                         break;
5420                 case CEE_LDC_I8:
5421                         CHECK_OPSIZE (9);
5422                         CHECK_STACK_OVF (1);
5423                         MONO_INST_NEW (cfg, ins, OP_I8CONST);
5424                         ins->cil_code = ip;
5425                         ins->type = STACK_I8;
5426                         ++ip;
5427                         ins->inst_l = (gint64)read64 (ip);
5428                         ip += 8;
5429                         *sp++ = ins;
5430                         break;
5431                 case CEE_LDC_R4: {
5432                         float *f;
5433                         /* we should really allocate this only late in the compilation process */
5434                         mono_domain_lock (cfg->domain);
5435                         f = mono_mempool_alloc (cfg->domain->mp, sizeof (float));
5436                         mono_domain_unlock (cfg->domain);
5437                         CHECK_OPSIZE (5);
5438                         CHECK_STACK_OVF (1);
5439                         MONO_INST_NEW (cfg, ins, OP_R4CONST);
5440                         ins->type = STACK_R8;
5441                         ++ip;
5442                         readr4 (ip, f);
5443                         ins->inst_p0 = f;
5444
5445                         ip += 4;
5446                         *sp++ = ins;                    
5447                         break;
5448                 }
5449                 case CEE_LDC_R8: {
5450                         double *d;
5451                         mono_domain_lock (cfg->domain);
5452                         d = mono_mempool_alloc (cfg->domain->mp, sizeof (double));
5453                         mono_domain_unlock (cfg->domain);
5454                         CHECK_OPSIZE (9);
5455                         CHECK_STACK_OVF (1);
5456                         MONO_INST_NEW (cfg, ins, OP_R8CONST);
5457                         ins->type = STACK_R8;
5458                         ++ip;
5459                         readr8 (ip, d);
5460                         ins->inst_p0 = d;
5461
5462                         ip += 8;
5463                         *sp++ = ins;                    
5464                         break;
5465                 }
5466                 case CEE_DUP: {
5467                         MonoInst *temp, *store;
5468                         CHECK_STACK (1);
5469                         CHECK_STACK_OVF (1);
5470                         sp--;
5471                         ins = *sp;
5472                 
5473                         /* 
5474                          * small optimization: if the loaded value was from a local already,
5475                          * just load it twice.
5476                          */
5477                         if (ins->ssa_op == MONO_SSA_LOAD && 
5478                             (ins->inst_i0->opcode == OP_LOCAL || ins->inst_i0->opcode == OP_ARG)) {
5479                                 sp++;
5480                                 MONO_INST_NEW (cfg, temp, 0);
5481                                 *temp = *ins;
5482                                 temp->cil_code = ip;
5483                                 *sp++ = temp;
5484                         } else {
5485                                 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
5486                                 temp->flags |= MONO_INST_IS_TEMP;
5487                                 temp->cil_code = ip;
5488                                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
5489                                 store->cil_code = ip;
5490                                 /* FIXME: handle CEE_STIND_R4 */
5491                                 if (store->opcode == CEE_STOBJ) {
5492                                         NEW_TEMPLOADA (cfg, store, temp->inst_c0);
5493                                         handle_stobj (cfg, bblock, store, sp [0], sp [0]->cil_code, store->klass, TRUE, FALSE, FALSE);
5494                                 } else {
5495                                         MONO_ADD_INS (bblock, store);
5496                                 }
5497                                 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
5498                                 *sp++ = ins;
5499                                 ins->cil_code = ip;
5500                                 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
5501                                 *sp++ = ins;
5502                                 ins->cil_code = ip;
5503                         }
5504                         ++ip;
5505                         inline_costs += 2;
5506                         break;
5507                 }
5508                 case CEE_POP:
5509                         CHECK_STACK (1);
5510                         MONO_INST_NEW (cfg, ins, CEE_POP);
5511                         MONO_ADD_INS (bblock, ins);
5512                         ins->cil_code = ip++;
5513                         --sp;
5514                         ins->inst_i0 = *sp;
5515                         break;
5516                 case CEE_JMP:
5517                         CHECK_OPSIZE (5);
5518                         if (stack_start != sp)
5519                                 UNVERIFIED;
5520                         MONO_INST_NEW (cfg, ins, OP_JMP);
5521                         token = read32 (ip + 1);
5522                         /* FIXME: check the signature matches */
5523                         cmethod = mini_get_method (method, token, NULL, generic_context);
5524
5525                         if (!cmethod)
5526                                 goto load_error;
5527
5528                         if (cfg->generic_sharing_context && mono_method_check_context_used (cmethod))
5529                                 GENERIC_SHARING_FAILURE (CEE_JMP);
5530
5531                         if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
5532                                 if (check_linkdemand (cfg, method, cmethod, bblock, ip))
5533                                         INLINE_FAILURE;
5534                                 CHECK_CFG_EXCEPTION;
5535                         }
5536
5537                         ins->inst_p0 = cmethod;
5538                         MONO_ADD_INS (bblock, ins);
5539                         ip += 5;
5540                         start_new_bblock = 1;
5541                         break;
5542                 case CEE_CALLI:
5543                 case CEE_CALL:
5544                 case CEE_CALLVIRT: {
5545                         MonoInst *addr = NULL;
5546                         MonoMethodSignature *fsig = NULL;
5547                         int temp, array_rank = 0;
5548                         int virtual = *ip == CEE_CALLVIRT;
5549                         MonoInst *rgctx_arg = NULL;
5550                         gboolean no_spill;
5551                         int context_used = 0;
5552                         gboolean pass_rgctx = FALSE;
5553
5554                         CHECK_OPSIZE (5);
5555                         token = read32 (ip + 1);
5556
5557                         if (*ip == CEE_CALLI) {
5558                                 cmethod = NULL;
5559                                 CHECK_STACK (1);
5560                                 --sp;
5561                                 addr = *sp;
5562                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
5563                                         fsig = (MonoMethodSignature *)mono_method_get_wrapper_data (method, token);
5564                                 else
5565                                         fsig = mono_metadata_parse_signature (image, token);
5566
5567                                 n = fsig->param_count + fsig->hasthis;
5568                         } else {
5569                                 MonoMethod *cil_method;
5570                                 
5571                                 if (method->wrapper_type != MONO_WRAPPER_NONE) {
5572                                         cmethod =  (MonoMethod *)mono_method_get_wrapper_data (method, token);
5573                                         cil_method = cmethod;
5574                                 } else if (constrained_call) {
5575                                         cmethod = mono_get_method_constrained (image, token, constrained_call, generic_context, &cil_method);
5576                                         cil_method = cmethod;
5577                                 } else {
5578                                         cmethod = mini_get_method (method, token, NULL, generic_context);
5579                                         cil_method = cmethod;
5580                                 }
5581
5582                                 if (!cmethod)
5583                                         goto load_error;
5584                                 if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_method (method, cil_method))
5585                                         METHOD_ACCESS_FAILURE;
5586
5587                                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
5588                                         ensure_method_is_allowed_to_call_method (cfg, method, cil_method, bblock, ip);
5589
5590                                 if (!virtual && (cmethod->flags & METHOD_ATTRIBUTE_ABSTRACT))
5591                                         /* MS.NET seems to silently convert this to a callvirt */
5592                                         virtual = 1;
5593
5594                                 if (!cmethod->klass->inited){
5595                                         if (!mono_class_init (cmethod->klass))
5596                                                 goto load_error;
5597                                 }
5598
5599                                 if (mono_method_signature (cmethod)->pinvoke) {
5600                                         MonoMethod *wrapper = mono_marshal_get_native_wrapper (cmethod, check_for_pending_exc);
5601                                         fsig = mono_method_signature (wrapper);
5602                                 } else if (constrained_call) {
5603                                         fsig = mono_method_signature (cmethod);
5604                                 } else {
5605                                         fsig = mono_method_get_signature_full (cmethod, image, token, generic_context);
5606                                 }
5607
5608                                 mono_save_token_info (cfg, image, token, cmethod);
5609
5610                                 n = fsig->param_count + fsig->hasthis;
5611
5612                                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
5613                                         if (check_linkdemand (cfg, method, cmethod, bblock, ip))
5614                                                 INLINE_FAILURE;
5615                                         CHECK_CFG_EXCEPTION;
5616                                 }
5617
5618                                 if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL &&
5619                                     mini_class_is_system_array (cmethod->klass)) {
5620                                         array_rank = cmethod->klass->rank;
5621                                 }
5622
5623                                 if (cmethod->string_ctor)
5624                                         g_assert_not_reached ();
5625
5626                         }
5627
5628                         if (!cfg->generic_sharing_context && cmethod && cmethod->klass->generic_container)
5629                                 UNVERIFIED;
5630
5631                         CHECK_STACK (n);
5632
5633                         //g_assert (!virtual || fsig->hasthis);
5634
5635                         sp -= n;
5636
5637                         if (constrained_call) {
5638                                 /*
5639                                  * We have the `constrained.' prefix opcode.
5640                                  */
5641                                 if (constrained_call->valuetype && !cmethod->klass->valuetype) {
5642                                         MonoInst *load;
5643                                         /*
5644                                          * The type parameter is instantiated as a valuetype,
5645                                          * but that type doesn't override the method we're
5646                                          * calling, so we need to box `this'.
5647                                          * sp [0] is a pointer to the data: we need the value
5648                                          * in handle_box (), so load it here.
5649                                          */
5650                                         MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, &constrained_call->byval_arg));
5651                                         type_to_eval_stack_type (cfg, &constrained_call->byval_arg, load);
5652                                         load->cil_code = ip;
5653                                         load->inst_left = sp [0];
5654                                         sp [0] = handle_box (cfg, bblock, load, ip, constrained_call);
5655                                 } else if (!constrained_call->valuetype) {
5656                                         MonoInst *ins;
5657
5658                                         /*
5659                                          * The type parameter is instantiated as a reference
5660                                          * type.  We have a managed pointer on the stack, so
5661                                          * we need to dereference it here.
5662                                          */
5663
5664                                         MONO_INST_NEW (cfg, ins, CEE_LDIND_REF);
5665                                         ins->cil_code = ip;
5666                                         ins->inst_i0 = sp [0];
5667                                         ins->type = STACK_OBJ;
5668                                         ins->klass = mono_class_from_mono_type (&constrained_call->byval_arg);
5669                                         sp [0] = ins;
5670                                 } else if (cmethod->klass->valuetype)
5671                                         virtual = 0;
5672                                 constrained_call = NULL;
5673                         }
5674
5675                         if (*ip != CEE_CALLI && check_call_signature (cfg, fsig, sp))
5676                                 UNVERIFIED;
5677
5678                         if (cmethod && (cmethod->flags & METHOD_ATTRIBUTE_STATIC) &&
5679                                         (cmethod->klass->generic_class || cmethod->klass->generic_container)) {
5680                                 gboolean sharing_enabled = mono_class_generic_sharing_enabled (cmethod->klass);
5681                                 MonoGenericContext *context = mini_class_get_context (cmethod->klass);
5682                                 gboolean context_sharable = mono_generic_context_is_sharable (context, TRUE);
5683
5684                                 /*
5685                                  * Pass rgctx iff target method might
5686                                  * be shared, which means that sharing
5687                                  * is enabled for its class and its
5688                                  * context is sharable (and it's not a
5689                                  * generic method).
5690                                  */
5691                                 if (sharing_enabled && context_sharable &&
5692                                                 !mini_method_get_context (cmethod)->method_inst)
5693                                         pass_rgctx = TRUE;
5694                         }
5695
5696                         if (cfg->generic_sharing_context && cmethod) {
5697                                 MonoGenericContext *cmethod_context = mono_method_get_context (cmethod);
5698
5699                                 context_used = mono_method_check_context_used (cmethod);
5700
5701                                 if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD)
5702                                         GENERIC_SHARING_FAILURE (*ip);
5703
5704                                 if (context_used &&
5705                                                 ((cmethod->klass->flags & TYPE_ATTRIBUTE_INTERFACE) ||
5706                                                 (cmethod_context && cmethod_context->method_inst && cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL))) {
5707                                         GENERIC_SHARING_FAILURE (*ip);
5708                                 }
5709                         }
5710
5711                         if (pass_rgctx) {
5712                                 if (context_used) {
5713                                         MonoInst *this = NULL, *rgctx, *vtable, *field_offset, *field_addr;
5714
5715                                         GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD (*ip);
5716
5717                                         if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
5718                                                 NEW_ARGLOAD (cfg, this, 0);
5719                                         rgctx = get_runtime_generic_context (cfg, method, this, ip);
5720                                         vtable = get_runtime_generic_context_ptr (cfg, method, bblock, cmethod->klass,
5721                                                 token, MINI_TOKEN_SOURCE_METHOD, generic_context,
5722                                                 rgctx, MONO_RGCTX_INFO_VTABLE, ip);
5723
5724                                         NEW_ICONST (cfg, field_offset, G_STRUCT_OFFSET (MonoVTable, runtime_generic_context));
5725
5726                                         MONO_INST_NEW (cfg, field_addr, OP_PADD);
5727                                         field_addr->cil_code = ip;
5728                                         field_addr->inst_left = vtable;
5729                                         field_addr->inst_right = field_offset;
5730                                         field_addr->type = STACK_PTR;
5731
5732                                         MONO_INST_NEW (cfg, rgctx_arg, CEE_LDIND_I);
5733                                         rgctx_arg->cil_code = ip;
5734                                         rgctx_arg->inst_left = field_addr;
5735                                         rgctx_arg->type = STACK_PTR;
5736                                 } else {
5737                                         MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
5738
5739                                         NEW_PCONST (cfg, rgctx_arg, vtable->runtime_generic_context);
5740                                 }
5741                         }
5742
5743                         if (cmethod && virtual && 
5744                             (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) && 
5745                             !((cmethod->flags & METHOD_ATTRIBUTE_FINAL) && 
5746                               cmethod->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK) &&
5747                             mono_method_signature (cmethod)->generic_param_count) {
5748                                 MonoInst *this_temp, *this_arg_temp, *store;
5749                                 MonoInst *iargs [4];
5750
5751                                 g_assert (mono_method_signature (cmethod)->is_inflated);
5752                                 /* Prevent inlining of methods that contain indirect calls */
5753                                 INLINE_FAILURE;
5754
5755                                 this_temp = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
5756                                 this_temp->cil_code = ip;
5757                                 NEW_TEMPSTORE (cfg, store, this_temp->inst_c0, sp [0]);
5758
5759                                 store->cil_code = ip;
5760                                 MONO_ADD_INS (bblock, store);
5761
5762                                 /* FIXME: This should be a managed pointer */
5763                                 this_arg_temp = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
5764                                 this_arg_temp->cil_code = ip;
5765
5766                                 /* Because of the PCONST below */
5767                                 cfg->disable_aot = TRUE;
5768                                 NEW_TEMPLOAD (cfg, iargs [0], this_temp->inst_c0);
5769                                 NEW_METHODCONST (cfg, iargs [1], cmethod);
5770                                 NEW_PCONST (cfg, iargs [2], mono_method_get_context (cmethod));
5771                                 NEW_TEMPLOADA (cfg, iargs [3], this_arg_temp->inst_c0);
5772                                 temp = mono_emit_jit_icall (cfg, bblock, mono_helper_compile_generic_method, iargs, ip);
5773
5774                                 NEW_TEMPLOAD (cfg, addr, temp);
5775                                 NEW_TEMPLOAD (cfg, sp [0], this_arg_temp->inst_c0);
5776
5777                                 if ((temp = mono_emit_calli_spilled (cfg, bblock, fsig, sp, addr, ip)) != -1) {
5778                                         NEW_TEMPLOAD (cfg, *sp, temp);
5779                                         sp++;
5780                                 }
5781
5782                                 ip += 5;
5783                                 ins_flag = 0;
5784                                 break;
5785                         }
5786
5787                         /* FIXME: runtime generic context pointer for jumps? */
5788                         if ((ins_flag & MONO_INST_TAILCALL) && cmethod && (*ip == CEE_CALL) &&
5789                                  (mono_metadata_signature_equal (mono_method_signature (method), mono_method_signature (cmethod)))) {
5790                                 int i;
5791
5792                                 GENERIC_SHARING_FAILURE (*ip);
5793
5794                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
5795                                 INLINE_FAILURE;
5796                                 /* FIXME: This assumes the two methods has the same number and type of arguments */
5797                                 /*
5798                                  * We implement tail calls by storing the actual arguments into the 
5799                                  * argument variables, then emitting a OP_JMP. Since the actual arguments
5800                                  * can refer to the arg variables, we have to spill them.
5801                                  */
5802                                 handle_loaded_temps (cfg, bblock, sp, sp + n);
5803                                 for (i = 0; i < n; ++i) {
5804                                         /* Prevent argument from being register allocated */
5805                                         arg_array [i]->flags |= MONO_INST_VOLATILE;
5806
5807                                         /* Check if argument is the same */
5808                                         /* 
5809                                          * FIXME: This loses liveness info, so it can only be done if the
5810                                          * argument is not register allocated.
5811                                          */
5812                                         NEW_ARGLOAD (cfg, ins, i);
5813                                         if ((ins->opcode == sp [i]->opcode) && (ins->inst_i0 == sp [i]->inst_i0))
5814                                                 continue;
5815
5816                                         NEW_ARGSTORE (cfg, ins, i, sp [i]);
5817                                         ins->cil_code = ip;
5818                                         /* FIXME: handle CEE_STIND_R4 */
5819                                         if (ins->opcode == CEE_STOBJ) {
5820                                                 NEW_ARGLOADA (cfg, ins, i);
5821                                                 handle_stobj (cfg, bblock, ins, sp [i], sp [i]->cil_code, ins->klass, FALSE, FALSE, FALSE);
5822                                         }
5823                                         else
5824                                                 MONO_ADD_INS (bblock, ins);
5825                                 }
5826                                 MONO_INST_NEW (cfg, ins, OP_JMP);
5827                                 ins->cil_code = ip;
5828                                 ins->inst_p0 = cmethod;
5829                                 ins->inst_p1 = arg_array [0];
5830                                 MONO_ADD_INS (bblock, ins);
5831                                 link_bblock (cfg, bblock, end_bblock);                  
5832                                 start_new_bblock = 1;
5833                                 /* skip CEE_RET as well */
5834                                 ip += 6;
5835                                 ins_flag = 0;
5836                                 break;
5837                         }
5838                         if (cmethod && (cfg->opt & MONO_OPT_INTRINS) && (ins = mini_get_inst_for_method (cfg, cmethod, fsig, sp))) {
5839                                 ins->cil_code = ip;
5840
5841                                 if (MONO_TYPE_IS_VOID (fsig->ret)) {
5842                                         MONO_ADD_INS (bblock, ins);
5843                                 } else {
5844                                         type_to_eval_stack_type (cfg, fsig->ret, ins);
5845                                         *sp = ins;
5846                                         sp++;
5847                                 }
5848
5849                                 ip += 5;
5850                                 ins_flag = 0;
5851                                 break;
5852                         }
5853
5854                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5855
5856                         if ((cfg->opt & MONO_OPT_INLINE) && cmethod &&
5857                             (!virtual || !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) || (cmethod->flags & METHOD_ATTRIBUTE_FINAL)) && 
5858                             mono_method_check_inlining (cfg, cmethod) &&
5859                                  !g_list_find (dont_inline, cmethod)) {
5860                                 int costs;
5861                                 MonoBasicBlock *ebblock;
5862                                 gboolean allways = FALSE;
5863
5864                                 if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
5865                                         (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5866                                         /* Prevent inlining of methods that call wrappers */
5867                                         INLINE_FAILURE;
5868                                         cmethod = mono_marshal_get_native_wrapper (cmethod, check_for_pending_exc);
5869                                         allways = TRUE;
5870                                 }
5871
5872                                 if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock, allways))) {
5873                                         ip += 5;
5874                                         real_offset += 5;
5875
5876                                         GET_BBLOCK (cfg, bblock, ip);
5877                                         ebblock->next_bb = bblock;
5878                                         link_bblock (cfg, ebblock, bblock);
5879
5880                                         if (!MONO_TYPE_IS_VOID (fsig->ret))
5881                                                 sp++;
5882
5883                                         /* indicates start of a new block, and triggers a load of all 
5884                                            stack arguments at bb boundarie */
5885                                         bblock = ebblock;
5886
5887                                         inline_costs += costs;
5888                                         ins_flag = 0;
5889                                         break;
5890                                 }
5891                         }
5892                         
5893                         inline_costs += 10 * num_calls++;
5894
5895                         /* tail recursion elimination */
5896                         if ((cfg->opt & MONO_OPT_TAILC) && *ip == CEE_CALL && cmethod == method && ip [5] == CEE_RET &&
5897                                         !rgctx_arg) {
5898                                 gboolean has_vtargs = FALSE;
5899                                 int i;
5900                                 
5901                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
5902                                 INLINE_FAILURE;
5903                                 /* keep it simple */
5904                                 for (i =  fsig->param_count - 1; i >= 0; i--) {
5905                                         if (MONO_TYPE_ISSTRUCT (mono_method_signature (cmethod)->params [i])) 
5906                                                 has_vtargs = TRUE;
5907                                 }
5908
5909                                 if (!has_vtargs) {
5910                                         for (i = 0; i < n; ++i) {
5911                                                 /* FIXME: handle CEE_STIND_R4 */
5912                                                 NEW_ARGSTORE (cfg, ins, i, sp [i]);
5913                                                 ins->cil_code = ip;
5914                                                 MONO_ADD_INS (bblock, ins);
5915                                         }
5916                                         MONO_INST_NEW (cfg, ins, OP_BR);
5917                                         ins->cil_code = ip;
5918                                         MONO_ADD_INS (bblock, ins);
5919                                         tblock = start_bblock->out_bb [0];
5920                                         link_bblock (cfg, bblock, tblock);
5921                                         ins->inst_target_bb = tblock;
5922                                         start_new_bblock = 1;
5923
5924                                         /* skip the CEE_RET, too */
5925                                         if (ip_in_bb (cfg, bblock, ip + 5))
5926                                                 ip += 6;
5927                                         else
5928                                                 ip += 5;
5929                                         ins_flag = 0;
5930                                         break;
5931                                 }
5932                         }
5933
5934                         if (ip_in_bb (cfg, bblock, ip + 5) 
5935                                 && (!MONO_TYPE_ISSTRUCT (fsig->ret))
5936                                 && (!MONO_TYPE_IS_VOID (fsig->ret) || (cmethod && cmethod->string_ctor))
5937                                 && (CODE_IS_STLOC (ip + 5) || ip [5] == CEE_POP || ip [5] == CEE_RET))
5938                                 /* No need to spill */
5939                                 no_spill = TRUE;
5940                         else
5941                                 no_spill = FALSE;
5942
5943                         if (context_used &&
5944                                         (cmethod->klass->valuetype ||
5945                                         (cmethod->is_inflated && mono_method_get_context (cmethod)->method_inst) ||
5946                                         ((cmethod->flags & METHOD_ATTRIBUTE_STATIC) &&
5947                                                 mono_class_generic_sharing_enabled (cmethod->klass)))) {
5948                                 MonoInst *this = NULL, *rgctx;
5949
5950                                 INLINE_FAILURE;
5951
5952                                 g_assert (cfg->generic_sharing_context && cmethod);
5953                                 g_assert (addr == NULL);
5954
5955                                 /*
5956                                  * We are compiling a call to a
5957                                  * generic method from shared code,
5958                                  * which means that we have to look up
5959                                  * the method in the rgctx and do an
5960                                  * indirect call.
5961                                  */
5962
5963                                 GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD (*ip);
5964
5965                                 if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
5966                                         NEW_ARGLOAD (cfg, this, 0);
5967                                 rgctx = get_runtime_generic_context (cfg, method, this, ip);
5968                                 addr = get_runtime_generic_context_method (cfg, method, bblock, cmethod,
5969                                                 generic_context, rgctx, MONO_RGCTX_INFO_GENERIC_METHOD_CODE, ip);
5970                         }
5971
5972                         if (addr) {
5973                                 if (*ip == CEE_CALL)
5974                                         g_assert (context_used);
5975                                 else if (*ip == CEE_CALLI)
5976                                         g_assert (!rgctx_arg);
5977                                 else
5978                                         g_assert_not_reached ();
5979
5980                                 /* Prevent inlining of methods with indirect calls */
5981                                 INLINE_FAILURE;
5982                                 if (no_spill) {
5983                                         ins = (MonoInst*)mono_emit_rgctx_calli (cfg, bblock, fsig, sp, addr, rgctx_arg, ip);
5984                                         *sp++ = ins;                                    
5985                                 } else {
5986                                         temp = mono_emit_rgctx_calli_spilled (cfg, bblock, fsig, sp, addr, rgctx_arg, ip);
5987                                         if (temp != -1) {
5988                                                 NEW_TEMPLOAD (cfg, *sp, temp);
5989                                                 sp++;
5990                                         }
5991                                 }                       
5992                         } else if (array_rank) {
5993                                 MonoInst *addr;
5994
5995                                 if (strcmp (cmethod->name, "Set") == 0) { /* array Set */ 
5996                                         if (sp [fsig->param_count]->type == STACK_OBJ) {
5997                                                 MonoInst *iargs [2];
5998                                                 MonoInst *array, *to_store, *store;
5999
6000                                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
6001                                                 
6002                                                 array = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
6003                                                 NEW_TEMPSTORE (cfg, store, array->inst_c0, sp [0]);
6004                                                 store->cil_code = ip;
6005                                                 MONO_ADD_INS (bblock, store);
6006                                                 NEW_TEMPLOAD (cfg, iargs [0], array->inst_c0);
6007
6008                                                 to_store = mono_compile_create_var (cfg, type_from_stack_type (sp [fsig->param_count]), OP_LOCAL);
6009                                                 NEW_TEMPSTORE (cfg, store, to_store->inst_c0, sp [fsig->param_count]);
6010                                                 /* FIXME: handle CEE_STIND_R4 */
6011                                                 store->cil_code = ip;
6012                                                 MONO_ADD_INS (bblock, store);
6013                                                 NEW_TEMPLOAD (cfg, iargs [1], to_store->inst_c0);
6014
6015                                                 /*
6016                                                  * We first save the args for the call so that the args are copied to the stack
6017                                                  * and a new instruction tree for them is created. If we don't do this,
6018                                                  * the same MonoInst is added to two different trees and this is not 
6019                                                  * allowed by burg.
6020                                                  */
6021                                                 mono_emit_jit_icall (cfg, bblock, mono_helper_stelem_ref_check, iargs, ip);
6022
6023                                                 NEW_TEMPLOAD (cfg, sp [0], array->inst_c0);
6024                                                 NEW_TEMPLOAD (cfg, sp [fsig->param_count], to_store->inst_c0);
6025                                         }
6026
6027                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, TRUE);
6028                                         NEW_INDSTORE (cfg, ins, addr, sp [fsig->param_count], fsig->params [fsig->param_count - 1]);
6029                                         ins->cil_code = ip;
6030                                         /* FIXME: handle CEE_STIND_R4 */
6031                                         if (ins->opcode == CEE_STOBJ) {
6032                                                 handle_stobj (cfg, bblock, addr, sp [fsig->param_count], ip, mono_class_from_mono_type (fsig->params [fsig->param_count-1]), FALSE, FALSE, TRUE);
6033                                         } else {
6034                                                 MONO_ADD_INS (bblock, ins);
6035                                         }
6036
6037                                 } else if (strcmp (cmethod->name, "Get") == 0) { /* array Get */
6038                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
6039                                         NEW_INDLOAD (cfg, ins, addr, fsig->ret);
6040                                         ins->cil_code = ip;
6041
6042                                         *sp++ = ins;
6043                                 } else if (strcmp (cmethod->name, "Address") == 0) { /* array Address */
6044                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
6045                                         *sp++ = addr;
6046                                 } else {
6047                                         g_assert_not_reached ();
6048                                 }
6049
6050                         } else {
6051                                 /* Prevent inlining of methods which call other methods */
6052                                 INLINE_FAILURE;
6053                                 if (mini_redirect_call (&temp, cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL)) {
6054                                         if (temp != -1) {
6055                                                 NEW_TEMPLOAD (cfg, *sp, temp);
6056                                                 sp++;
6057                                         }
6058                                 } else if (no_spill) {
6059                                         ins = (MonoInst*)mono_emit_rgctx_method_call (cfg, bblock, cmethod, fsig, sp, rgctx_arg, ip, virtual ? sp [0] : NULL);
6060                                         *sp++ = ins;
6061                                 } else {
6062                                         if ((temp = mono_emit_rgctx_method_call_spilled (cfg, bblock, cmethod, fsig, sp, rgctx_arg, ip, virtual ? sp [0] : NULL)) != -1) {
6063                                                 MonoInst *load;
6064                                                 NEW_TEMPLOAD (cfg, load, temp);
6065
6066 #ifdef MONO_ARCH_SOFT_FLOAT
6067                                                 if (load->opcode == CEE_LDIND_R4) {
6068                                                         NEW_TEMPLOADA (cfg, load, temp);
6069                                                         temp = handle_load_float (cfg, bblock, load, ip);
6070                                                         NEW_TEMPLOAD (cfg, load, temp);
6071                                                 }
6072 #endif
6073                                                 *sp++ = load;
6074                                         }
6075                                 }
6076                         }
6077
6078                         ip += 5;
6079                         ins_flag = 0;
6080                         break;
6081                 }
6082                 case CEE_RET:
6083                         if (cfg->method != method) {
6084                                 /* return from inlined method */
6085                                 if (return_var) {
6086                                         MonoInst *store;
6087                                         CHECK_STACK (1);
6088                                         --sp;
6089                                         //g_assert (returnvar != -1);
6090                                         NEW_TEMPSTORE (cfg, store, return_var->inst_c0, *sp);
6091                                         store->cil_code = sp [0]->cil_code;
6092                                         /* FIXME: handle CEE_STIND_R4 */
6093                                         if (store->opcode == CEE_STOBJ) {
6094                                                 g_assert_not_reached ();
6095                                                 NEW_TEMPLOADA (cfg, store, return_var->inst_c0);
6096                                                 /* FIXME: it is possible some optimization will pass the a heap pointer for the struct address, so we'll need the write barrier */
6097                                                 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, return_var->klass, FALSE, FALSE, FALSE);
6098 #ifdef MONO_ARCH_SOFT_FLOAT
6099                                         } else if (store->opcode == CEE_STIND_R4) {
6100                                                 NEW_TEMPLOADA (cfg, store, return_var->inst_c0);
6101                                                 handle_store_float (cfg, bblock, store, *sp, sp [0]->cil_code);
6102 #endif
6103                                         } else
6104                                                 MONO_ADD_INS (bblock, store);
6105                                 } 
6106                         } else {
6107                                 if (cfg->ret) {
6108                                         g_assert (!return_var);
6109                                         CHECK_STACK (1);
6110                                         --sp;
6111                                         MONO_INST_NEW (cfg, ins, OP_NOP);
6112                                         ins->opcode = mini_type_to_stind (cfg, mono_method_signature (method)->ret);
6113                                         if (ins->opcode == CEE_STOBJ) {
6114                                                 NEW_RETLOADA (cfg, ins);
6115                                                 /* FIXME: it is possible some optimization will pass the a heap pointer for the struct address, so we'll need the write barrier */
6116                                                 handle_stobj (cfg, bblock, ins, *sp, ip, cfg->ret->klass, FALSE, FALSE, FALSE);
6117                                         } else {
6118                                                 ins->opcode = OP_SETRET;
6119                                                 ins->cil_code = ip;
6120                                                 ins->inst_i0 = *sp;;
6121                                                 ins->inst_i1 = NULL;
6122                                                 MONO_ADD_INS (bblock, ins);
6123                                         }
6124                                 }
6125                         }
6126                         if (sp != stack_start)
6127                                 UNVERIFIED;
6128                         MONO_INST_NEW (cfg, ins, OP_BR);
6129                         ins->cil_code = ip++;
6130                         ins->inst_target_bb = end_bblock;
6131                         MONO_ADD_INS (bblock, ins);
6132                         link_bblock (cfg, bblock, end_bblock);
6133                         start_new_bblock = 1;
6134                         break;
6135                 case CEE_BR_S:
6136                         CHECK_OPSIZE (2);
6137                         MONO_INST_NEW (cfg, ins, OP_BR);
6138                         ins->cil_code = ip++;
6139                         MONO_ADD_INS (bblock, ins);
6140                         target = ip + 1 + (signed char)(*ip);
6141                         ++ip;
6142                         GET_BBLOCK (cfg, tblock, target);
6143                         link_bblock (cfg, bblock, tblock);
6144                         CHECK_BBLOCK (target, ip, tblock);
6145                         ins->inst_target_bb = tblock;
6146                         if (sp != stack_start) {
6147                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6148                                 sp = stack_start;
6149                                 CHECK_UNVERIFIABLE (cfg);
6150                         }
6151                         start_new_bblock = 1;
6152                         inline_costs += BRANCH_COST;
6153                         break;
6154                 case CEE_BRFALSE_S:
6155                 case CEE_BRTRUE_S:
6156                         CHECK_OPSIZE (2);
6157                         CHECK_STACK (1);
6158                         if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
6159                                 UNVERIFIED;
6160                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
6161                         ins->cil_code = ip++;
6162                         target = ip + 1 + *(signed char*)ip;
6163                         ip++;
6164                         ADD_UNCOND (ins->opcode == CEE_BRTRUE);
6165                         if (sp != stack_start) {
6166                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6167                                 sp = stack_start;
6168                                 CHECK_UNVERIFIABLE (cfg);
6169                         }
6170                         inline_costs += BRANCH_COST;
6171                         break;
6172                 case CEE_BEQ_S:
6173                 case CEE_BGE_S:
6174                 case CEE_BGT_S:
6175                 case CEE_BLE_S:
6176                 case CEE_BLT_S:
6177                 case CEE_BNE_UN_S:
6178                 case CEE_BGE_UN_S:
6179                 case CEE_BGT_UN_S:
6180                 case CEE_BLE_UN_S:
6181                 case CEE_BLT_UN_S:
6182                         CHECK_OPSIZE (2);
6183                         CHECK_STACK (2);
6184                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
6185                         ins->cil_code = ip++;
6186                         target = ip + 1 + *(signed char*)ip;
6187                         ip++;
6188 #ifdef MONO_ARCH_SOFT_FLOAT
6189                         if (sp [-1]->type == STACK_R8 || sp [-2]->type == STACK_R8) {
6190                                 ins->opcode = condbr_to_fp_br (ins->opcode);
6191                                 sp -= 2;
6192                                 ins->inst_left = sp [0];
6193                                 ins->inst_right = sp [1];
6194                                 ins->type = STACK_I4;
6195                                 *sp++ = emit_tree (cfg, bblock, ins, ins->cil_code);
6196                                 MONO_INST_NEW (cfg, ins, CEE_BRTRUE);
6197                                 ADD_UNCOND (TRUE);
6198                         } else {
6199                                 ADD_BINCOND (NULL);
6200                         }
6201 #else
6202                         ADD_BINCOND (NULL);
6203 #endif
6204                         if (sp != stack_start) {
6205                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6206                                 sp = stack_start;
6207                                 CHECK_UNVERIFIABLE (cfg);
6208                         }
6209                         inline_costs += BRANCH_COST;
6210                         break;
6211                 case CEE_BR:
6212                         CHECK_OPSIZE (5);
6213                         MONO_INST_NEW (cfg, ins, OP_BR);
6214                         ins->cil_code = ip++;
6215                         MONO_ADD_INS (bblock, ins);
6216                         target = ip + 4 + (gint32)read32(ip);
6217                         ip += 4;
6218                         GET_BBLOCK (cfg, tblock, target);
6219                         link_bblock (cfg, bblock, tblock);
6220                         CHECK_BBLOCK (target, ip, tblock);
6221                         ins->inst_target_bb = tblock;
6222                         if (sp != stack_start) {
6223                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6224                                 sp = stack_start;
6225                                 CHECK_UNVERIFIABLE (cfg);
6226                         }
6227                         start_new_bblock = 1;
6228                         inline_costs += BRANCH_COST;
6229                         break;
6230                 case CEE_BRFALSE:
6231                 case CEE_BRTRUE:
6232                         CHECK_OPSIZE (5);
6233                         CHECK_STACK (1);
6234                         if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
6235                                 UNVERIFIED;
6236                         MONO_INST_NEW (cfg, ins, *ip);
6237                         ins->cil_code = ip++;
6238                         target = ip + 4 + (gint32)read32(ip);
6239                         ip += 4;
6240                         ADD_UNCOND(ins->opcode == CEE_BRTRUE);
6241                         if (sp != stack_start) {
6242                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6243                                 sp = stack_start;
6244                                 CHECK_UNVERIFIABLE (cfg);
6245                         }
6246                         inline_costs += BRANCH_COST;
6247                         break;
6248                 case CEE_BEQ:
6249                 case CEE_BGE:
6250                 case CEE_BGT:
6251                 case CEE_BLE:
6252                 case CEE_BLT:
6253                 case CEE_BNE_UN:
6254                 case CEE_BGE_UN:
6255                 case CEE_BGT_UN:
6256                 case CEE_BLE_UN:
6257                 case CEE_BLT_UN:
6258                         CHECK_OPSIZE (5);
6259                         CHECK_STACK (2);
6260                         MONO_INST_NEW (cfg, ins, *ip);
6261                         ins->cil_code = ip++;
6262                         target = ip + 4 + (gint32)read32(ip);
6263                         ip += 4;
6264 #ifdef MONO_ARCH_SOFT_FLOAT
6265                         if (sp [-1]->type == STACK_R8 || sp [-2]->type == STACK_R8) {
6266                                 ins->opcode = condbr_to_fp_br (ins->opcode);
6267                                 sp -= 2;
6268                                 ins->inst_left = sp [0];
6269                                 ins->inst_right = sp [1];
6270                                 ins->type = STACK_I4;
6271                                 *sp++ = emit_tree (cfg, bblock, ins, ins->cil_code);
6272                                 MONO_INST_NEW (cfg, ins, CEE_BRTRUE);
6273                                 ADD_UNCOND (TRUE);
6274                         } else {
6275                                 ADD_BINCOND (NULL);
6276                         }
6277 #else
6278                         ADD_BINCOND (NULL);
6279 #endif
6280                         if (sp != stack_start) {
6281                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6282                                 sp = stack_start;
6283                                 CHECK_UNVERIFIABLE (cfg);
6284                         }
6285                         inline_costs += BRANCH_COST;
6286                         break;
6287                 case CEE_SWITCH:
6288                         CHECK_OPSIZE (5);
6289                         CHECK_STACK (1);
6290                         n = read32 (ip + 1);
6291                         MONO_INST_NEW (cfg, ins, OP_SWITCH);
6292                         --sp;
6293                         ins->inst_left = *sp;
6294                         if ((ins->inst_left->type != STACK_I4) && (ins->inst_left->type != STACK_PTR)) 
6295                                 UNVERIFIED;
6296                         ins->cil_code = ip;
6297                         ip += 5;
6298                         CHECK_OPSIZE (n * sizeof (guint32));
6299                         target = ip + n * sizeof (guint32);
6300                         MONO_ADD_INS (bblock, ins);
6301                         GET_BBLOCK (cfg, tblock, target);
6302                         link_bblock (cfg, bblock, tblock);
6303                         ins->klass = GUINT_TO_POINTER (n);
6304                         ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (n + 1));
6305                         ins->inst_many_bb [n] = tblock;
6306
6307                         for (i = 0; i < n; ++i) {
6308                                 GET_BBLOCK (cfg, tblock, target + (gint32)read32(ip));
6309                                 link_bblock (cfg, bblock, tblock);
6310                                 ins->inst_many_bb [i] = tblock;
6311                                 ip += 4;
6312                         }
6313                         if (sp != stack_start) {
6314                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6315                                 sp = stack_start;
6316                                 CHECK_UNVERIFIABLE (cfg);
6317                         }
6318                         /* Needed by the code generated in inssel.brg */
6319                         mono_get_got_var (cfg);
6320                         inline_costs += (BRANCH_COST * 2);
6321                         break;
6322                 case CEE_LDIND_I1:
6323                 case CEE_LDIND_U1:
6324                 case CEE_LDIND_I2:
6325                 case CEE_LDIND_U2:
6326                 case CEE_LDIND_I4:
6327                 case CEE_LDIND_U4:
6328                 case CEE_LDIND_I8:
6329                 case CEE_LDIND_I:
6330                 case CEE_LDIND_R4:
6331                 case CEE_LDIND_R8:
6332                 case CEE_LDIND_REF:
6333                         CHECK_STACK (1);
6334                         MONO_INST_NEW (cfg, ins, *ip);
6335                         ins->cil_code = ip;
6336                         --sp;
6337                         ins->inst_i0 = *sp;
6338                         *sp++ = ins;
6339                         ins->type = ldind_type [*ip - CEE_LDIND_I1];
6340                         ins->flags |= ins_flag;
6341                         ins_flag = 0;
6342                         if (ins->type == STACK_OBJ)
6343                                 ins->klass = mono_defaults.object_class;
6344 #ifdef MONO_ARCH_SOFT_FLOAT
6345                         if (*ip == CEE_LDIND_R4) {
6346                                 int temp;
6347                                 --sp;
6348                                 temp = handle_load_float (cfg, bblock, ins->inst_i0, ip);
6349                                 NEW_TEMPLOAD (cfg, *sp, temp);
6350                                 sp++;
6351                         }
6352 #endif
6353                         ++ip;
6354                         break;
6355                 case CEE_STIND_REF:
6356                 case CEE_STIND_I1:
6357                 case CEE_STIND_I2:
6358                 case CEE_STIND_I4:
6359                 case CEE_STIND_I8:
6360                 case CEE_STIND_R4:
6361                 case CEE_STIND_R8:
6362                         CHECK_STACK (2);
6363 #ifdef MONO_ARCH_SOFT_FLOAT
6364                         if (*ip == CEE_STIND_R4) {
6365                                 sp -= 2;
6366                                 handle_store_float (cfg, bblock, sp [0], sp [1], ip);
6367                                 ip++;
6368                                 break;
6369                         }
6370 #endif
6371 #if HAVE_WRITE_BARRIERS
6372                         if (*ip == CEE_STIND_REF && method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER && !((sp [-1]->opcode == OP_PCONST) && (sp [-1]->inst_p0 == 0))) {
6373                                 /* insert call to write barrier */
6374                                 MonoMethod *write_barrier = mono_marshal_get_write_barrier ();
6375                                 sp -= 2;
6376                                 mono_emit_method_call_spilled (cfg, bblock, write_barrier, mono_method_signature (write_barrier), sp, ip, NULL);
6377                                 ip++;
6378                                 break;
6379                         }
6380 #endif
6381                         MONO_INST_NEW (cfg, ins, *ip);
6382                         ins->cil_code = ip++;
6383                         sp -= 2;
6384                         handle_loaded_temps (cfg, bblock, stack_start, sp);
6385                         MONO_ADD_INS (bblock, ins);
6386                         ins->inst_i0 = sp [0];
6387                         ins->inst_i1 = sp [1];
6388                         ins->flags |= ins_flag;
6389                         ins_flag = 0;
6390                         inline_costs += 1;
6391                         break;
6392                 case CEE_MUL:
6393                         CHECK_STACK (2);
6394                         ADD_BINOP (*ip);
6395
6396 #ifdef MONO_ARCH_NO_EMULATE_MUL_IMM
6397                         /* FIXME: This breaks with ssapre (mono -O=ssapre loader.exe) */
6398                         if ((ins->inst_right->opcode == OP_ICONST) && !(cfg->opt & MONO_OPT_SSAPRE)) {
6399                                 switch (ins->opcode) {
6400                                 case CEE_MUL:
6401                                         ins->opcode = OP_IMUL_IMM;
6402                                         ins->inst_imm = ins->inst_right->inst_c0;
6403                                         break;
6404                                 case OP_LMUL:
6405                                         ins->opcode = OP_LMUL_IMM;
6406                                         ins->inst_imm = ins->inst_right->inst_c0;
6407                                         break;
6408                                 default:
6409                                         g_assert_not_reached ();
6410                                 }
6411                         }
6412 #endif
6413
6414                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
6415                                 --sp;
6416                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
6417                         }
6418                         ip++;
6419                         break;
6420                 case CEE_ADD:
6421                 case CEE_SUB:
6422                 case CEE_DIV:
6423                 case CEE_DIV_UN:
6424                 case CEE_REM:
6425                 case CEE_REM_UN:
6426                 case CEE_AND:
6427                 case CEE_OR:
6428                 case CEE_XOR:
6429                 case CEE_SHL:
6430                 case CEE_SHR:
6431                 case CEE_SHR_UN:
6432                         CHECK_STACK (2);
6433                         ADD_BINOP (*ip);
6434                         /* special case that gives a nice speedup and happens to workaorund a ppc jit but (for the release)
6435                          * later apply the speedup to the left shift as well
6436                          * See BUG# 57957.
6437                          */
6438                         if ((ins->opcode == OP_LSHR_UN) && (ins->type == STACK_I8) 
6439                                         && (ins->inst_right->opcode == OP_ICONST) && (ins->inst_right->inst_c0 == 32)) {
6440                                 ins->opcode = OP_LONG_SHRUN_32;
6441                                 /*g_print ("applied long shr speedup to %s\n", cfg->method->name);*/
6442                                 ip++;
6443                                 break;
6444                         }
6445                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
6446                                 --sp;
6447                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
6448                         }
6449                         ip++;
6450                         break;
6451                 case CEE_NEG:
6452                 case CEE_NOT:
6453                 case CEE_CONV_I1:
6454                 case CEE_CONV_I2:
6455                 case CEE_CONV_I4:
6456                 case CEE_CONV_R4:
6457                 case CEE_CONV_R8:
6458                 case CEE_CONV_U4:
6459                 case CEE_CONV_I8:
6460                 case CEE_CONV_U8:
6461                 case CEE_CONV_OVF_I8:
6462                 case CEE_CONV_OVF_U8:
6463                 case CEE_CONV_R_UN:
6464                         CHECK_STACK (1);
6465                         ADD_UNOP (*ip);
6466                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
6467                                 --sp;
6468                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
6469                         }
6470                         ip++;                   
6471                         break;
6472                 case CEE_CONV_OVF_I4:
6473                 case CEE_CONV_OVF_I1:
6474                 case CEE_CONV_OVF_I2:
6475                 case CEE_CONV_OVF_I:
6476                 case CEE_CONV_OVF_U:
6477                         CHECK_STACK (1);
6478
6479                         if (sp [-1]->type == STACK_R8) {
6480                                 ADD_UNOP (CEE_CONV_OVF_I8);
6481                                 ADD_UNOP (*ip);
6482                         } else {
6483                                 ADD_UNOP (*ip);
6484                         }
6485
6486                         ip++;
6487                         break;
6488                 case CEE_CONV_OVF_U1:
6489                 case CEE_CONV_OVF_U2:
6490                 case CEE_CONV_OVF_U4:
6491                         CHECK_STACK (1);
6492
6493                         if (sp [-1]->type == STACK_R8) {
6494                                 ADD_UNOP (CEE_CONV_OVF_U8);
6495                                 ADD_UNOP (*ip);
6496                         } else {
6497                                 ADD_UNOP (*ip);
6498                         }
6499
6500                         ip++;
6501                         break;
6502                 case CEE_CONV_OVF_I1_UN:
6503                 case CEE_CONV_OVF_I2_UN:
6504                 case CEE_CONV_OVF_I4_UN:
6505                 case CEE_CONV_OVF_I8_UN:
6506                 case CEE_CONV_OVF_U1_UN:
6507                 case CEE_CONV_OVF_U2_UN:
6508                 case CEE_CONV_OVF_U4_UN:
6509                 case CEE_CONV_OVF_U8_UN:
6510                 case CEE_CONV_OVF_I_UN:
6511                 case CEE_CONV_OVF_U_UN:
6512                         CHECK_STACK (1);
6513                         ADD_UNOP (*ip);
6514                         ip++;
6515                         break;
6516                 case CEE_CPOBJ:
6517                         CHECK_OPSIZE (5);
6518                         CHECK_STACK (2);
6519                         token = read32 (ip + 1);
6520                         klass = mini_get_class (method, token, generic_context);
6521                         CHECK_TYPELOAD (klass);
6522                         sp -= 2;
6523                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
6524                                 MonoInst *store, *load;
6525                                 MONO_INST_NEW (cfg, load, CEE_LDIND_REF);
6526                                 load->cil_code = ip;
6527                                 load->inst_i0 = sp [1];
6528                                 load->type = STACK_OBJ;
6529                                 load->klass = klass;
6530                                 load->flags |= ins_flag;
6531                                 MONO_INST_NEW (cfg, store, CEE_STIND_REF);
6532                                 store->cil_code = ip;
6533                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
6534                                 MONO_ADD_INS (bblock, store);
6535                                 store->inst_i0 = sp [0];
6536                                 store->inst_i1 = load;
6537                                 store->flags |= ins_flag;
6538                         } else {
6539                                 guint32 align;
6540
6541                                 n = mono_class_value_size (klass, &align);
6542                                 if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
6543                                         MonoInst *copy;
6544                                         NEW_MEMCPY (cfg, copy, sp [0], sp [1], n, align);
6545                                         MONO_ADD_INS (bblock, copy);
6546                                 } else {
6547                                         MonoMethod *memcpy_method = get_memcpy_method ();
6548                                         MonoInst *iargs [3];
6549                                         iargs [0] = sp [0];
6550                                         iargs [1] = sp [1];
6551                                         NEW_ICONST (cfg, iargs [2], n);
6552                                         iargs [2]->cil_code = ip;
6553
6554                                         mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
6555                                 }
6556                         }
6557                         ins_flag = 0;
6558                         ip += 5;
6559                         break;
6560                 case CEE_LDOBJ: {
6561                         MonoInst *iargs [3];
6562                         int loc_index = -1;
6563                         int stloc_len = 0;
6564                         guint32 align;
6565
6566                         CHECK_OPSIZE (5);
6567                         CHECK_STACK (1);
6568                         --sp;
6569                         token = read32 (ip + 1);
6570                         klass = mini_get_class (method, token, generic_context);
6571                         CHECK_TYPELOAD (klass);
6572                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
6573                                 MONO_INST_NEW (cfg, ins, CEE_LDIND_REF);
6574                                 ins->cil_code = ip;
6575                                 ins->inst_i0 = sp [0];
6576                                 ins->type = STACK_OBJ;
6577                                 ins->klass = klass;
6578                                 ins->flags |= ins_flag;
6579                                 ins_flag = 0;
6580                                 *sp++ = ins;
6581                                 ip += 5;
6582                                 break;
6583                         }
6584
6585                         /* Optimize the common ldobj+stloc combination */
6586                         switch (ip [5]) {
6587                         case CEE_STLOC_S:
6588                                 loc_index = ip [6];
6589                                 stloc_len = 2;
6590                                 break;
6591                         case CEE_STLOC_0:
6592                         case CEE_STLOC_1:
6593                         case CEE_STLOC_2:
6594                         case CEE_STLOC_3:
6595                                 loc_index = ip [5] - CEE_STLOC_0;
6596                                 stloc_len = 1;
6597                                 break;
6598                         default:
6599                                 break;
6600                         }
6601
6602                         if ((loc_index != -1) && ip_in_bb (cfg, bblock, ip + 5)) {
6603                                 CHECK_LOCAL (loc_index);
6604                                 NEW_LOCSTORE (cfg, ins, loc_index, *sp);
6605
6606                                 /* FIXME: handle CEE_STIND_R4 */
6607                                 if (ins->opcode == CEE_STOBJ) {
6608                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
6609                                         ins->cil_code = ip;
6610                                         g_assert (ins->opcode == CEE_STOBJ);
6611                                         NEW_LOCLOADA (cfg, ins, loc_index);
6612                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
6613                                         ip += 5;
6614                                         ip += stloc_len;
6615                                         break;
6616                                 }
6617                         }
6618
6619                         n = mono_class_value_size (klass, &align);
6620                         ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
6621                         NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
6622                         if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
6623                                 MonoInst *copy;
6624                                 NEW_MEMCPY (cfg, copy, iargs [0], *sp, n, align);
6625                                 MONO_ADD_INS (bblock, copy);
6626                         } else {
6627                                 MonoMethod *memcpy_method = get_memcpy_method ();
6628                                 iargs [1] = *sp;
6629                                 NEW_ICONST (cfg, iargs [2], n);
6630                                 iargs [2]->cil_code = ip;
6631
6632                                 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
6633                         }
6634                         NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
6635                         ++sp;
6636                         ip += 5;
6637                         ins_flag = 0;
6638                         inline_costs += 1;
6639                         break;
6640                 }
6641                 case CEE_LDSTR:
6642                         CHECK_STACK_OVF (1);
6643                         CHECK_OPSIZE (5);
6644                         n = read32 (ip + 1);
6645
6646                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
6647                                 /* FIXME: moving GC */
6648                                 NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, n));
6649                                 ins->cil_code = ip;
6650                                 ins->type = STACK_OBJ;
6651                                 ins->klass = mono_defaults.string_class;
6652                                 *sp = ins;
6653                         }
6654                         else if (method->wrapper_type != MONO_WRAPPER_NONE) {
6655                                 int temp;
6656                                 MonoInst *iargs [1];
6657
6658                                 NEW_PCONST (cfg, iargs [0], mono_method_get_wrapper_data (method, n));                          
6659                                 temp = mono_emit_jit_icall (cfg, bblock, mono_string_new_wrapper, iargs, ip);
6660                                 NEW_TEMPLOAD (cfg, *sp, temp);
6661
6662                         } else {
6663
6664                                 if (cfg->opt & MONO_OPT_SHARED) {
6665                                         int temp;
6666                                         MonoInst *iargs [3];
6667                                         MonoInst* domain_var;
6668                                         
6669                                         if (cfg->compile_aot) {
6670                                                 /* FIXME: bug when inlining methods from different assemblies (n is a token valid just in one). */
6671                                                 cfg->ldstr_list = g_list_prepend (cfg->ldstr_list, GINT_TO_POINTER (n));
6672                                         }
6673                                         /* avoid depending on undefined C behavior in sequence points */
6674                                         domain_var = mono_get_domainvar (cfg);
6675                                         NEW_TEMPLOAD (cfg, iargs [0], domain_var->inst_c0);
6676                                         NEW_IMAGECONST (cfg, iargs [1], image);
6677                                         NEW_ICONST (cfg, iargs [2], mono_metadata_token_index (n));
6678                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldstr, iargs, ip);
6679                                         NEW_TEMPLOAD (cfg, *sp, temp);
6680                                         mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
6681                                 } else {
6682                                         if (bblock->out_of_line) {
6683                                                 MonoInst *iargs [2];
6684                                                 int temp;
6685
6686                                                 if (cfg->method->klass->image == mono_defaults.corlib) {
6687                                                         /* 
6688                                                          * Avoid relocations and save some code size by using a 
6689                                                          * version of helper_ldstr specialized to mscorlib.
6690                                                          */
6691                                                         NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (n));
6692                                                         temp = mono_emit_jit_icall (cfg, bblock, mono_helper_ldstr_mscorlib, iargs, ip);
6693                                                 } else {
6694                                                         /* Avoid creating the string object */
6695                                                         NEW_IMAGECONST (cfg, iargs [0], image);
6696                                                         NEW_ICONST (cfg, iargs [1], mono_metadata_token_index (n));
6697                                                         temp = mono_emit_jit_icall (cfg, bblock, mono_helper_ldstr, iargs, ip);
6698                                                 }
6699                                                 NEW_TEMPLOAD (cfg, *sp, temp);
6700                                         } 
6701                                         else
6702                                         if (cfg->compile_aot) {
6703                                                 NEW_LDSTRCONST (cfg, ins, image, n);
6704                                                 *sp = ins;
6705                                         } 
6706                                         else {
6707                                                 NEW_PCONST (cfg, ins, NULL);
6708                                                 ins->cil_code = ip;
6709                                                 ins->type = STACK_OBJ;
6710                                                 ins->inst_p0 = mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
6711                                                 ins->klass = mono_defaults.string_class;
6712                                                 *sp = ins;
6713                                         }
6714                                 }
6715                         }
6716
6717                         sp++;
6718                         ip += 5;
6719                         break;
6720                 case CEE_NEWOBJ: {
6721                         MonoInst *iargs [2];
6722                         MonoMethodSignature *fsig;
6723                         int temp;
6724                         gboolean generic_shared = FALSE;
6725
6726                         CHECK_OPSIZE (5);
6727                         token = read32 (ip + 1);
6728                         cmethod = mini_get_method (method, token, NULL, generic_context);
6729                         if (!cmethod)
6730                                 goto load_error;
6731                         fsig = mono_method_get_signature (cmethod, image, token);
6732
6733                         mono_save_token_info (cfg, image, token, cmethod);
6734
6735                         if (!mono_class_init (cmethod->klass))
6736                                 goto load_error;
6737
6738                         if (cfg->generic_sharing_context) {
6739                                 int context_used = mono_method_check_context_used (cmethod);
6740
6741                                 if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD)
6742                                         GENERIC_SHARING_FAILURE (CEE_NEWOBJ);
6743
6744                                 if (context_used)
6745                                         generic_shared = TRUE;
6746                         }
6747
6748                         if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
6749                                 if (check_linkdemand (cfg, method, cmethod, bblock, ip))
6750                                         INLINE_FAILURE;
6751                                 CHECK_CFG_EXCEPTION;
6752                         } else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
6753                                 ensure_method_is_allowed_to_call_method (cfg, method, cmethod, bblock, ip);
6754                         }
6755
6756                         n = fsig->param_count;
6757                         CHECK_STACK (n);
6758  
6759                         /* 
6760                          * Generate smaller code for the common newobj <exception> instruction in
6761                          * argument checking code.
6762                          */
6763                         if (bblock->out_of_line && cmethod->klass->image == mono_defaults.corlib && n <= 2 && 
6764                                 ((n < 1) || (!fsig->params [0]->byref && fsig->params [0]->type == MONO_TYPE_STRING)) && 
6765                                 ((n < 2) || (!fsig->params [1]->byref && fsig->params [1]->type == MONO_TYPE_STRING))) {
6766                                 MonoInst *iargs [3];
6767                                 int temp;
6768                                 
6769                                 sp -= n;
6770
6771                                 NEW_ICONST (cfg, iargs [0], cmethod->klass->type_token);
6772                                 switch (n) {
6773                                 case 0:
6774                                         temp = mono_emit_jit_icall (cfg, bblock, mono_create_corlib_exception_0, iargs, ip);
6775                                         break;
6776                                 case 1:
6777                                         iargs [1] = sp [0];
6778                                         temp = mono_emit_jit_icall (cfg, bblock, mono_create_corlib_exception_1, iargs, ip);
6779                                         break;
6780                                 case 2:
6781                                         iargs [1] = sp [0];
6782                                         iargs [2] = sp [1];
6783                                         temp = mono_emit_jit_icall (cfg, bblock, mono_create_corlib_exception_2, iargs, ip);
6784                                         break;
6785                                 default:
6786                                         g_assert_not_reached ();
6787                                 }
6788                                 NEW_TEMPLOAD (cfg, ins, temp);
6789                                 *sp ++ = ins;
6790
6791                                 ip += 5;
6792                                 inline_costs += 5;
6793                                 break;
6794                         }
6795
6796                         /* move the args to allow room for 'this' in the first position */
6797                         while (n--) {
6798                                 --sp;
6799                                 sp [1] = sp [0];
6800                         }
6801
6802                         handle_loaded_temps (cfg, bblock, stack_start, sp);
6803
6804                         if (mini_class_is_system_array (cmethod->klass)) {
6805                                 g_assert (!generic_shared);
6806
6807                                 NEW_METHODCONST (cfg, *sp, cmethod);
6808                                 temp = handle_array_new (cfg, bblock, fsig->param_count, sp, ip);
6809                         } else if (cmethod->string_ctor) {
6810                                 g_assert (!generic_shared);
6811
6812                                 /* we simply pass a null pointer */
6813                                 NEW_PCONST (cfg, *sp, NULL); 
6814                                 /* now call the string ctor */
6815                                 temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, NULL);
6816                         } else {
6817                                 MonoInst* callvirt_this_arg = NULL;
6818                                 
6819                                 if (cmethod->klass->valuetype) {
6820                                         iargs [0] = mono_compile_create_var (cfg, &cmethod->klass->byval_arg, OP_LOCAL);
6821                                         temp = iargs [0]->inst_c0;
6822
6823                                         NEW_TEMPLOADA (cfg, *sp, temp);
6824
6825                                         handle_initobj (cfg, bblock, *sp, NULL, cmethod->klass, stack_start, sp);
6826
6827                                         NEW_TEMPLOADA (cfg, *sp, temp);
6828
6829                                         /* 
6830                                          * The code generated by mini_emit_virtual_call () expects
6831                                          * iargs [0] to be a boxed instance, but luckily the vcall
6832                                          * will be transformed into a normal call there.
6833                                          */
6834                                 } else if (generic_shared) {
6835                                         MonoInst *this = NULL, *rgctx, *vtable;
6836
6837                                         GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD (*ip);
6838
6839                                         if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
6840                                                 NEW_ARGLOAD (cfg, this, 0);
6841                                         rgctx = get_runtime_generic_context (cfg, method, this, ip);
6842                                         vtable = get_runtime_generic_context_ptr (cfg, method, bblock, cmethod->klass,
6843                                                 token, MINI_TOKEN_SOURCE_METHOD, generic_context,
6844                                                 rgctx, MONO_RGCTX_INFO_VTABLE, ip);
6845
6846                                         temp = handle_alloc_from_inst (cfg, bblock, cmethod->klass, vtable, FALSE, ip);
6847                                         NEW_TEMPLOAD (cfg, *sp, temp);
6848                                 } else {
6849                                         MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
6850                                         if (mini_field_access_needs_cctor_run (cfg, method, vtable) && !(g_slist_find (class_inits, vtable))) {
6851                                                 guint8 *tramp = mono_create_class_init_trampoline (vtable);
6852                                                 mono_emit_native_call (cfg, bblock, tramp, 
6853                                                                                            helper_sig_class_init_trampoline,
6854                                                                                            NULL, ip, FALSE, FALSE);
6855                                                 if (cfg->verbose_level > 2)
6856                                                         g_print ("class %s.%s needs init call for ctor\n", cmethod->klass->name_space, cmethod->klass->name);
6857                                                 class_inits = g_slist_prepend (class_inits, vtable);
6858                                         }
6859                                         temp = handle_alloc (cfg, bblock, cmethod->klass, FALSE, ip);
6860                                         NEW_TEMPLOAD (cfg, *sp, temp);
6861                                 }
6862
6863                                 /* Avoid virtual calls to ctors if possible */
6864                                 if (cmethod->klass->marshalbyref)
6865                                         callvirt_this_arg = sp [0];
6866                                 
6867                                 if ((cfg->opt & MONO_OPT_INLINE) && cmethod && !generic_shared &&
6868                                     mono_method_check_inlining (cfg, cmethod) &&
6869                                     !mono_class_is_subclass_of (cmethod->klass, mono_defaults.exception_class, FALSE) &&
6870                                     !g_list_find (dont_inline, cmethod)) {
6871                                         int costs;
6872                                         MonoBasicBlock *ebblock;
6873                                         if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock, FALSE))) {
6874
6875                                                 ip += 5;
6876                                                 real_offset += 5;
6877                                                 
6878                                                 GET_BBLOCK (cfg, bblock, ip);
6879                                                 ebblock->next_bb = bblock;
6880                                                 link_bblock (cfg, ebblock, bblock);
6881
6882                                                 NEW_TEMPLOAD (cfg, *sp, temp);
6883                                                 sp++;
6884
6885                                                 /* indicates start of a new block, and triggers a load 
6886                                                    of all stack arguments at bb boundarie */
6887                                                 bblock = ebblock;
6888
6889                                                 inline_costs += costs;
6890                                                 break;
6891                                                 
6892                                         } else {
6893                                                 /* Prevent inlining of methods which call other methods */
6894                                                 INLINE_FAILURE;
6895                                                 mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, callvirt_this_arg);
6896                                         }
6897                                 } else if (generic_shared && cmethod->klass->valuetype) {
6898                                         MonoInst *this = NULL, *rgctx, *cmethod_addr;
6899
6900                                         g_assert (!callvirt_this_arg);
6901
6902                                         GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD (*ip);
6903
6904                                         if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
6905                                                 NEW_ARGLOAD (cfg, this, 0);
6906                                         rgctx = get_runtime_generic_context (cfg, method, this, ip);
6907                                         cmethod_addr = get_runtime_generic_context_method (cfg, method, bblock, cmethod,
6908                                                         generic_context, rgctx, MONO_RGCTX_INFO_GENERIC_METHOD_CODE, ip);
6909
6910                                         mono_emit_calli_spilled (cfg, bblock, fsig, sp, cmethod_addr, ip);
6911                                 } else {
6912                                         /* Prevent inlining of methods which call other methods */
6913                                         INLINE_FAILURE;
6914                                         /* now call the actual ctor */
6915                                         mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, callvirt_this_arg);
6916                                 }
6917                         }
6918
6919                         NEW_TEMPLOAD (cfg, *sp, temp);
6920                         sp++;
6921                         
6922                         ip += 5;
6923                         inline_costs += 5;
6924                         break;
6925                 }
6926                 case CEE_ISINST: {
6927                         gboolean shared_access = FALSE;
6928
6929                         CHECK_STACK (1);
6930                         --sp;
6931                         CHECK_OPSIZE (5);
6932                         token = read32 (ip + 1);
6933                         klass = mini_get_class (method, token, generic_context);
6934                         CHECK_TYPELOAD (klass);
6935                         if (sp [0]->type != STACK_OBJ)
6936                                 UNVERIFIED;
6937
6938                         if (cfg->generic_sharing_context) {
6939                                 int context_used = mono_class_check_context_used (klass);
6940
6941                                 if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD)
6942                                         GENERIC_SHARING_FAILURE (CEE_ISINST);
6943
6944                                 if (context_used)
6945                                         shared_access = TRUE;
6946                         }
6947
6948                         /* Needed by the code generated in inssel.brg */
6949                         if (!shared_access)
6950                                 mono_get_got_var (cfg);
6951
6952                         if (shared_access) {
6953                                 MonoInst *this = NULL, *rgctx;
6954                                 MonoInst *args [2];
6955                                 int temp;
6956
6957                                 GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD (*ip);
6958
6959                                 /* obj */
6960                                 args [0] = *sp;
6961
6962                                 /* klass */
6963                                 if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
6964                                         NEW_ARGLOAD (cfg, this, 0);
6965                                 rgctx = get_runtime_generic_context (cfg, method, this, ip);
6966                                 args [1] = get_runtime_generic_context_ptr (cfg, method, bblock, klass,
6967                                         token, MINI_TOKEN_SOURCE_CLASS, generic_context, rgctx, MONO_RGCTX_INFO_KLASS, ip);
6968
6969                                 temp = mono_emit_jit_icall (cfg, bblock, mono_object_isinst, args, ip);
6970                                 NEW_TEMPLOAD (cfg, *sp, temp);
6971
6972                                 sp++;
6973                                 ip += 5;
6974                                 inline_costs += 2;
6975                         } else if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
6976                         
6977                                 MonoMethod *mono_isinst;
6978                                 MonoInst *iargs [1];
6979                                 MonoBasicBlock *ebblock;
6980                                 int costs;
6981                                 int temp;
6982                                 
6983                                 mono_isinst = mono_marshal_get_isinst (klass); 
6984                                 iargs [0] = sp [0];
6985                                 
6986                                 costs = inline_method (cfg, mono_isinst, mono_method_signature (mono_isinst), bblock, 
6987                                                        iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
6988                         
6989                                 g_assert (costs > 0);
6990                                 
6991                                 ip += 5;
6992                                 real_offset += 5;
6993                         
6994                                 GET_BBLOCK (cfg, bblock, ip);
6995                                 ebblock->next_bb = bblock;
6996                                 link_bblock (cfg, ebblock, bblock);
6997
6998                                 temp = iargs [0]->inst_i0->inst_c0;
6999                                 NEW_TEMPLOAD (cfg, *sp, temp);
7000                                 
7001                                 sp++;
7002                                 bblock = ebblock;
7003                                 inline_costs += costs;
7004                         } else {
7005                                 MONO_INST_NEW (cfg, ins, *ip);
7006                                 ins->type = STACK_OBJ;
7007                                 ins->inst_left = *sp;
7008                                 ins->inst_newa_class = klass;
7009                                 ins->klass = klass;
7010                                 ins->cil_code = ip;
7011                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 5);
7012                                 ip += 5;
7013                         }
7014                         break;
7015                 }
7016                 case CEE_UNBOX_ANY: {
7017                         MonoInst *add, *vtoffset;
7018                         MonoInst *iargs [3];
7019                         guint32 align;
7020
7021                         CHECK_STACK (1);
7022                         --sp;
7023                         CHECK_OPSIZE (5);
7024                         token = read32 (ip + 1);
7025                         klass = mini_get_class (method, token, generic_context);
7026                         CHECK_TYPELOAD (klass);
7027
7028                         if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
7029                                 GENERIC_SHARING_FAILURE (CEE_UNBOX_ANY);
7030
7031                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
7032                                 /* CASTCLASS */
7033                                 if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
7034                                         MonoMethod *mono_castclass;
7035                                         MonoInst *iargs [1];
7036                                         MonoBasicBlock *ebblock;
7037                                         int costs;
7038                                         int temp;
7039                                         
7040                                         mono_castclass = mono_marshal_get_castclass (klass); 
7041                                         iargs [0] = sp [0];
7042                                         
7043                                         costs = inline_method (cfg, mono_castclass, mono_method_signature (mono_castclass), bblock, 
7044                                                         iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
7045                                 
7046                                         g_assert (costs > 0);
7047                                         
7048                                         ip += 5;
7049                                         real_offset += 5;
7050                                 
7051                                         GET_BBLOCK (cfg, bblock, ip);
7052                                         ebblock->next_bb = bblock;
7053                                         link_bblock (cfg, ebblock, bblock);
7054         
7055                                         temp = iargs [0]->inst_i0->inst_c0;
7056                                         NEW_TEMPLOAD (cfg, *sp, temp);
7057                                         
7058                                         sp++;
7059                                         bblock = ebblock;
7060                                         inline_costs += costs;                          
7061                                 } else {
7062                                         /* Needed by the code generated in inssel.brg */
7063                                         mono_get_got_var (cfg);
7064                 
7065                                         MONO_INST_NEW (cfg, ins, CEE_CASTCLASS);
7066                                         ins->type = STACK_OBJ;
7067                                         ins->inst_left = *sp;
7068                                         ins->klass = klass;
7069                                         ins->inst_newa_class = klass;
7070                                         ins->cil_code = ip;
7071                                         *sp++ = ins;
7072                                         ip += 5;
7073                                 }
7074                                 break;
7075                         }
7076
7077                         if (mono_class_is_nullable (klass)) {
7078                                 int v = handle_unbox_nullable (cfg, bblock, *sp, ip, klass);
7079                                 NEW_TEMPLOAD (cfg, *sp, v);
7080                                 sp ++;
7081                                 ip += 5;
7082                                 break;
7083                         }
7084
7085                         /* Needed by the code generated in inssel.brg */
7086                         mono_get_got_var (cfg);
7087
7088                         MONO_INST_NEW (cfg, ins, OP_UNBOXCAST);
7089                         ins->type = STACK_OBJ;
7090                         ins->inst_left = *sp;
7091                         ins->klass = klass;
7092                         ins->inst_newa_class = klass;
7093                         ins->cil_code = ip;
7094
7095                         MONO_INST_NEW (cfg, add, OP_PADD);
7096                         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
7097                         add->inst_left = ins;
7098                         add->inst_right = vtoffset;
7099                         add->type = STACK_MP;
7100                         add->klass = mono_defaults.object_class;
7101                         *sp = add;
7102                         ip += 5;
7103                         /* LDOBJ impl */
7104                         n = mono_class_value_size (klass, &align);
7105                         ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
7106                         NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
7107                         if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
7108                                 MonoInst *copy;
7109                                 NEW_MEMCPY (cfg, copy, iargs [0], *sp, n, align);
7110                                 MONO_ADD_INS (bblock, copy);
7111                         } else {
7112                                 MonoMethod *memcpy_method = get_memcpy_method ();
7113                                 iargs [1] = *sp;
7114                                 NEW_ICONST (cfg, iargs [2], n);
7115                                 iargs [2]->cil_code = ip;
7116
7117                                 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
7118                         }
7119                         NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
7120                         ++sp;
7121                         inline_costs += 2;
7122                         break;
7123                 }
7124                 case CEE_UNBOX: {
7125                         MonoInst *add, *vtoffset;
7126
7127                         CHECK_STACK (1);
7128                         --sp;
7129                         CHECK_OPSIZE (5);
7130                         token = read32 (ip + 1);
7131                         klass = mini_get_class (method, token, generic_context);
7132                         CHECK_TYPELOAD (klass);
7133
7134                         if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
7135                                 GENERIC_SHARING_FAILURE (CEE_UNBOX);
7136
7137                         if (mono_class_is_nullable (klass)) {
7138                                 int v = handle_unbox_nullable (cfg, bblock, *sp, ip, klass);
7139                                 NEW_TEMPLOAD (cfg, *sp, v);
7140                                 sp ++;
7141                                 ip += 5;
7142                                 break;
7143                         }
7144
7145                         /* Needed by the code generated in inssel.brg */
7146                         mono_get_got_var (cfg);
7147
7148                         MONO_INST_NEW (cfg, ins, OP_UNBOXCAST);
7149                         ins->type = STACK_OBJ;
7150                         ins->inst_left = *sp;
7151                         ins->klass = klass;
7152                         ins->inst_newa_class = klass;
7153                         ins->cil_code = ip;
7154
7155                         MONO_INST_NEW (cfg, add, OP_PADD);
7156                         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
7157                         add->inst_left = ins;
7158                         add->inst_right = vtoffset;
7159                         add->type = STACK_MP;
7160                         add->klass = klass;
7161                         *sp++ = add;
7162                         ip += 5;
7163                         inline_costs += 2;
7164                         break;
7165                 }
7166                 case CEE_CASTCLASS:
7167                         CHECK_STACK (1);
7168                         --sp;
7169                         CHECK_OPSIZE (5);
7170                         token = read32 (ip + 1);
7171                         klass = mini_get_class (method, token, generic_context);
7172                         CHECK_TYPELOAD (klass);
7173                         if (sp [0]->type != STACK_OBJ)
7174                                 UNVERIFIED;
7175
7176                         if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
7177                                 GENERIC_SHARING_FAILURE (CEE_CASTCLASS);
7178
7179                         /* Needed by the code generated in inssel.brg */
7180                         mono_get_got_var (cfg);
7181                 
7182                         if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
7183                                 
7184                                 MonoMethod *mono_castclass;
7185                                 MonoInst *iargs [1];
7186                                 MonoBasicBlock *ebblock;
7187                                 int costs;
7188                                 int temp;
7189                                 
7190                                 mono_castclass = mono_marshal_get_castclass (klass); 
7191                                 iargs [0] = sp [0];
7192                                 
7193                                 costs = inline_method (cfg, mono_castclass, mono_method_signature (mono_castclass), bblock, 
7194                                                 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
7195                         
7196                                 g_assert (costs > 0);
7197                                 
7198                                 ip += 5;
7199                                 real_offset += 5;
7200                         
7201                                 GET_BBLOCK (cfg, bblock, ip);
7202                                 ebblock->next_bb = bblock;
7203                                 link_bblock (cfg, ebblock, bblock);
7204
7205                                 temp = iargs [0]->inst_i0->inst_c0;
7206                                 NEW_TEMPLOAD (cfg, *sp, temp);
7207                                 
7208                                 sp++;
7209                                 bblock = ebblock;
7210                                 inline_costs += costs;
7211                         } else {
7212                                 MONO_INST_NEW (cfg, ins, *ip);
7213                                 ins->type = STACK_OBJ;
7214                                 ins->inst_left = *sp;
7215                                 ins->klass = klass;
7216                                 ins->inst_newa_class = klass;
7217                                 ins->cil_code = ip;
7218                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 5);
7219                                 ip += 5;
7220                         }
7221                         break;
7222                 case CEE_THROW:
7223                         CHECK_STACK (1);
7224                         MONO_INST_NEW (cfg, ins, OP_THROW);
7225                         --sp;
7226                         ins->inst_left = *sp;
7227                         ins->cil_code = ip++;
7228                         bblock->out_of_line = TRUE;
7229                         MONO_ADD_INS (bblock, ins);
7230                         MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
7231                         ins->cil_code = ip - 1;
7232                         MONO_ADD_INS (bblock, ins);
7233                         sp = stack_start;
7234                         
7235                         link_bblock (cfg, bblock, end_bblock);
7236                         start_new_bblock = 1;
7237                         break;
7238                 case CEE_LDFLD:
7239                 case CEE_LDFLDA:
7240                 case CEE_STFLD: {
7241                         MonoInst *offset_ins;
7242                         MonoClassField *field;
7243                         MonoBasicBlock *ebblock;
7244                         int costs;
7245                         guint foffset;
7246
7247                         if (*ip == CEE_STFLD) {
7248                                 CHECK_STACK (2);
7249                                 sp -= 2;
7250                         } else {
7251                                 CHECK_STACK (1);
7252                                 --sp;
7253                         }
7254                         if (sp [0]->type == STACK_I4 || sp [0]->type == STACK_I8 || sp [0]->type == STACK_R8)
7255                                 UNVERIFIED;
7256                         if (*ip != CEE_LDFLD && sp [0]->type == STACK_VTYPE)
7257                                 UNVERIFIED;
7258                         CHECK_OPSIZE (5);
7259                         token = read32 (ip + 1);
7260                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
7261                                 field = mono_method_get_wrapper_data (method, token);
7262                                 klass = field->parent;
7263                         } else {
7264                                 field = mono_field_from_token (image, token, &klass, generic_context);
7265                         }
7266                         if (!field)
7267                                 goto load_error;
7268                         mono_class_init (klass);
7269                         if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_field (method, field))
7270                                 FIELD_ACCESS_FAILURE;
7271
7272                         foffset = klass->valuetype? field->offset - sizeof (MonoObject): field->offset;
7273                         /* FIXME: mark instructions for use in SSA */
7274                         if (*ip == CEE_STFLD) {
7275                                 if (target_type_is_incompatible (cfg, field->type, sp [1]))
7276                                         UNVERIFIED;
7277                                 if ((klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) || klass->contextbound || klass == mono_defaults.marshalbyrefobject_class) {
7278                                         MonoMethod *stfld_wrapper = mono_marshal_get_stfld_wrapper (field->type); 
7279                                         MonoInst *iargs [5];
7280
7281                                         iargs [0] = sp [0];
7282                                         NEW_CLASSCONST (cfg, iargs [1], klass);
7283                                         NEW_FIELDCONST (cfg, iargs [2], field);
7284                                         NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : 
7285                                                     field->offset);
7286                                         iargs [4] = sp [1];
7287
7288                                         if (cfg->opt & MONO_OPT_INLINE) {
7289                                                 costs = inline_method (cfg, stfld_wrapper, mono_method_signature (stfld_wrapper), bblock, 
7290                                                                 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
7291                                                 g_assert (costs > 0);
7292                                                       
7293                                                 ip += 5;
7294                                                 real_offset += 5;
7295
7296                                                 GET_BBLOCK (cfg, bblock, ip);
7297                                                 ebblock->next_bb = bblock;
7298                                                 link_bblock (cfg, ebblock, bblock);
7299
7300                                                 /* indicates start of a new block, and triggers a load 
7301                                                    of all stack arguments at bb boundarie */
7302                                                 bblock = ebblock;
7303
7304                                                 inline_costs += costs;
7305                                                 break;
7306                                         } else {
7307                                                 mono_emit_method_call_spilled (cfg, bblock, stfld_wrapper, mono_method_signature (stfld_wrapper), iargs, ip, NULL);
7308                                         }
7309 #if HAVE_WRITE_BARRIERS
7310                                 } else if (mini_type_to_stind (cfg, field->type) == CEE_STIND_REF) {
7311                                         /* insert call to write barrier */
7312                                         MonoMethod *write_barrier = mono_marshal_get_write_barrier ();
7313                                         MonoInst *iargs [2];
7314                                         NEW_ICONST (cfg, offset_ins, foffset);
7315                                         MONO_INST_NEW (cfg, ins, OP_PADD);
7316                                         ins->cil_code = ip;
7317                                         ins->inst_left = *sp;
7318                                         ins->inst_right = offset_ins;
7319                                         ins->type = STACK_MP;
7320                                         ins->klass = mono_defaults.object_class;
7321                                         iargs [0] = ins;
7322                                         iargs [1] = sp [1];
7323                                         mono_emit_method_call_spilled (cfg, bblock, write_barrier, mono_method_signature (write_barrier), iargs, ip, NULL);
7324 #endif
7325 #ifdef MONO_ARCH_SOFT_FLOAT
7326                                 } else if (mini_type_to_stind (cfg, field->type) == CEE_STIND_R4) {
7327                                         NEW_ICONST (cfg, offset_ins, foffset);
7328                                         MONO_INST_NEW (cfg, ins, OP_PADD);
7329                                         ins->cil_code = ip;
7330                                         ins->inst_left = *sp;
7331                                         ins->inst_right = offset_ins;
7332                                         ins->type = STACK_MP;
7333                                         ins->klass = mono_defaults.object_class;
7334                                         handle_store_float (cfg, bblock, ins, sp [1], ip);
7335 #endif
7336                                 } else {
7337                                         MonoInst *store;
7338                                         NEW_ICONST (cfg, offset_ins, foffset);
7339                                         MONO_INST_NEW (cfg, ins, OP_PADD);
7340                                         ins->cil_code = ip;
7341                                         ins->inst_left = *sp;
7342                                         ins->inst_right = offset_ins;
7343                                         ins->type = STACK_MP;
7344
7345                                         MONO_INST_NEW (cfg, store, mini_type_to_stind (cfg, field->type));
7346                                         store->cil_code = ip;
7347                                         store->inst_left = ins;
7348                                         store->inst_right = sp [1];
7349                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
7350                                         store->flags |= ins_flag;
7351                                         ins_flag = 0;
7352                                         if (store->opcode == CEE_STOBJ) {
7353                                                 handle_stobj (cfg, bblock, ins, sp [1], ip, 
7354                                                               mono_class_from_mono_type (field->type), FALSE, FALSE, TRUE);
7355                                         } else
7356                                                 MONO_ADD_INS (bblock, store);
7357                                 }
7358                         } else {
7359                                 if ((klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) || klass->contextbound || klass == mono_defaults.marshalbyrefobject_class) {
7360                                         MonoMethod *wrapper = (*ip == CEE_LDFLDA) ? mono_marshal_get_ldflda_wrapper (field->type) : mono_marshal_get_ldfld_wrapper (field->type); 
7361                                         MonoInst *iargs [4];
7362                                         int temp;
7363                                         
7364                                         iargs [0] = sp [0];
7365                                         NEW_CLASSCONST (cfg, iargs [1], klass);
7366                                         NEW_FIELDCONST (cfg, iargs [2], field);
7367                                         NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
7368                                         if ((cfg->opt & MONO_OPT_INLINE) && !MONO_TYPE_ISSTRUCT (mono_method_signature (wrapper)->ret)) {
7369                                                 costs = inline_method (cfg, wrapper, mono_method_signature (wrapper), bblock, 
7370                                                                 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
7371                                                 g_assert (costs > 0);
7372                                                       
7373                                                 ip += 5;
7374                                                 real_offset += 5;
7375
7376                                                 GET_BBLOCK (cfg, bblock, ip);
7377                                                 ebblock->next_bb = bblock;
7378                                                 link_bblock (cfg, ebblock, bblock);
7379
7380                                                 temp = iargs [0]->inst_i0->inst_c0;
7381
7382                                                 NEW_TEMPLOAD (cfg, *sp, temp);
7383                                                 sp++;
7384
7385                                                 /* indicates start of a new block, and triggers a load of
7386                                                    all stack arguments at bb boundarie */
7387                                                 bblock = ebblock;
7388                                                 
7389                                                 inline_costs += costs;
7390                                                 break;
7391                                         } else {
7392                                                 temp = mono_emit_method_call_spilled (cfg, bblock, wrapper, mono_method_signature (wrapper), iargs, ip, NULL);
7393                                                 NEW_TEMPLOAD (cfg, *sp, temp);
7394                                                 sp++;
7395                                         }
7396                                 } else {
7397                                         NEW_ICONST (cfg, offset_ins, foffset);
7398                                         MONO_INST_NEW (cfg, ins, OP_PADD);
7399                                         ins->cil_code = ip;
7400                                         ins->inst_left = *sp;
7401                                         ins->inst_right = offset_ins;
7402                                         ins->type = STACK_MP;
7403
7404                                         if (*ip == CEE_LDFLDA) {
7405                                                 ins->klass = mono_class_from_mono_type (field->type);
7406                                                 *sp++ = ins;
7407                                         } else {
7408                                                 MonoInst *load;
7409                                                 MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, field->type));
7410                                                 type_to_eval_stack_type (cfg, field->type, load);
7411                                                 load->cil_code = ip;
7412                                                 load->inst_left = ins;
7413                                                 load->flags |= ins_flag;
7414                                                 ins_flag = 0;
7415 #ifdef MONO_ARCH_SOFT_FLOAT
7416                                                 if (mini_type_to_ldind (cfg, field->type) == CEE_LDIND_R4) {
7417                                                         int temp;
7418                                                         temp = handle_load_float (cfg, bblock, ins, ip);
7419                                                         NEW_TEMPLOAD (cfg, *sp, temp);
7420                                                         sp++;
7421                                                 } else
7422 #endif
7423                                                 *sp++ = load;
7424                                         }
7425                                 }
7426                         }
7427                         ip += 5;
7428                         break;
7429                 }
7430                 case CEE_LDSFLD:
7431                 case CEE_LDSFLDA:
7432                 case CEE_STSFLD: {
7433                         MonoClassField *field;
7434                         gpointer addr = NULL;
7435                         gboolean shared_access = FALSE;
7436                         int relation = 0;
7437
7438                         CHECK_OPSIZE (5);
7439                         token = read32 (ip + 1);
7440                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
7441                                 field = mono_method_get_wrapper_data (method, token);
7442                                 klass = field->parent;
7443                         }
7444                         else
7445                                 field = mono_field_from_token (image, token, &klass, generic_context);
7446                         if (!field)
7447                                 goto load_error;
7448                         mono_class_init (klass);
7449                         if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_field (method, field))
7450                                 FIELD_ACCESS_FAILURE;
7451
7452                         /*
7453                          * We can only support shared generic static
7454                          * field access on architectures where the
7455                          * trampoline code has been extended to handle
7456                          * the generic class init.
7457                          */
7458 #ifndef MONO_ARCH_VTABLE_REG
7459                         GENERIC_SHARING_FAILURE (*ip);
7460 #endif
7461
7462                         if (cfg->generic_sharing_context) {
7463                                 int context_used = mono_class_check_context_used (klass);
7464
7465                                 if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD ||
7466                                                 klass->valuetype)
7467                                         GENERIC_SHARING_FAILURE (*ip);
7468
7469                                 if (context_used) {
7470                                         relation = mono_class_generic_class_relation (klass, MONO_RGCTX_INFO_VTABLE,
7471                                                 method->klass, generic_context, NULL);
7472                                         shared_access = TRUE;
7473                                 }
7474                         }
7475
7476                         g_assert (!(field->type->attrs & FIELD_ATTRIBUTE_LITERAL));
7477
7478                         if ((*ip) == CEE_STSFLD)
7479                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
7480
7481                         /* The special_static_fields field is init'd in mono_class_vtable, so it needs
7482                          * to be called here.
7483                          */
7484                         if (!(cfg->opt & MONO_OPT_SHARED))
7485                                 mono_class_vtable (cfg->domain, klass);
7486                         mono_domain_lock (cfg->domain);
7487                         if (cfg->domain->special_static_fields)
7488                                 addr = g_hash_table_lookup (cfg->domain->special_static_fields, field);
7489                         mono_domain_unlock (cfg->domain);
7490
7491                         if (shared_access) {
7492                                 MonoInst *this, *rgctx, *static_data;
7493
7494                                 GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD (*ip);
7495
7496                                 /*
7497                                 g_print ("sharing static field access in %s.%s.%s - depth %d offset %d\n",
7498                                         method->klass->name_space, method->klass->name, method->name,
7499                                         depth, field->offset);
7500                                 */
7501
7502                                 if (mono_class_needs_cctor_run (klass, method)) {
7503                                         MonoMethodSignature *sig = helper_sig_generic_class_init_trampoline;
7504                                         MonoCallInst *call;
7505                                         MonoInst *vtable;
7506
7507                                         if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
7508                                                 NEW_ARGLOAD (cfg, this, 0);
7509                                         else
7510                                                 this = NULL;
7511
7512                                         if (relation == MINI_GENERIC_CLASS_RELATION_SELF && this) {
7513                                                 MONO_INST_NEW (cfg, vtable, CEE_LDIND_I);
7514                                                 vtable->cil_code = ip;
7515                                                 vtable->inst_left = this;
7516                                                 vtable->type = STACK_PTR;
7517                                                 vtable->klass = klass;
7518                                         } else {
7519                                                 MonoInst *rgctx = get_runtime_generic_context (cfg, method, this, ip);
7520
7521                                                 vtable = get_runtime_generic_context_ptr (cfg, method, bblock, klass,
7522                                                         token, MINI_TOKEN_SOURCE_FIELD, generic_context,
7523                                                         rgctx, MONO_RGCTX_INFO_VTABLE, ip);
7524                                         }
7525
7526                                         call = mono_emit_call_args (cfg, bblock, sig, NULL, FALSE, FALSE, ip, FALSE);
7527                                         call->inst.opcode = OP_TRAMPCALL_VTABLE;
7528                                         call->fptr = mono_get_trampoline_code (MONO_TRAMPOLINE_GENERIC_CLASS_INIT);
7529
7530                                         call->inst.inst_left = vtable;
7531
7532                                         mono_spill_call (cfg, bblock, call, sig, FALSE, ip, FALSE);
7533                                 }
7534
7535                                 /*
7536                                  * The pointer we're computing here is
7537                                  *
7538                                  *   super_info.static_data + field->offset
7539                                  */
7540
7541                                 if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
7542                                         NEW_ARGLOAD (cfg, this, 0);
7543                                 else
7544                                         this = NULL;
7545                                 rgctx = get_runtime_generic_context (cfg, method, this, ip);
7546                                 static_data = get_runtime_generic_context_ptr (cfg, method, bblock, klass,
7547                                         token, MINI_TOKEN_SOURCE_FIELD, generic_context,
7548                                         rgctx, MONO_RGCTX_INFO_STATIC_DATA, ip);
7549
7550                                 if (field->offset == 0) {
7551                                         ins = static_data;
7552                                 } else {
7553                                         MonoInst *field_offset;
7554
7555                                         NEW_ICONST (cfg, field_offset, field->offset);
7556
7557                                         MONO_INST_NEW (cfg, ins, OP_PADD);
7558                                         ins->cil_code = ip;
7559                                         ins->inst_left = static_data;
7560                                         ins->inst_right = field_offset;
7561                                         ins->type = STACK_PTR;
7562                                         ins->klass = klass;
7563                                 }
7564                         } else if ((cfg->opt & MONO_OPT_SHARED) || (cfg->compile_aot && addr)) {
7565                                 int temp;
7566                                 MonoInst *iargs [2];
7567                                 MonoInst *domain_var;
7568                                 
7569                                 g_assert (field->parent);
7570                                 /* avoid depending on undefined C behavior in sequence points */
7571                                 domain_var = mono_get_domainvar (cfg);
7572                                 NEW_TEMPLOAD (cfg, iargs [0], domain_var->inst_c0);
7573                                 NEW_FIELDCONST (cfg, iargs [1], field);
7574                                 temp = mono_emit_jit_icall (cfg, bblock, mono_class_static_field_address, iargs, ip);
7575                                 NEW_TEMPLOAD (cfg, ins, temp);
7576                         } else {
7577                                 MonoVTable *vtable;
7578                                 vtable = mono_class_vtable (cfg->domain, klass);
7579                                 if (!addr) {
7580                                         if (mini_field_access_needs_cctor_run (cfg, method, vtable) && !(g_slist_find (class_inits, vtable))) {
7581                                                 guint8 *tramp = mono_create_class_init_trampoline (vtable);
7582                                                 mono_emit_native_call (cfg, bblock, tramp, 
7583                                                                                            helper_sig_class_init_trampoline,
7584                                                                                            NULL, ip, FALSE, FALSE);
7585                                                 if (cfg->verbose_level > 2)
7586                                                         g_print ("class %s.%s needs init call for %s\n", klass->name_space, klass->name, field->name);
7587                                                 class_inits = g_slist_prepend (class_inits, vtable);
7588                                         } else {
7589                                                 if (cfg->run_cctors) {
7590                                                         /* This makes so that inline cannot trigger */
7591                                                         /* .cctors: too many apps depend on them */
7592                                                         /* running with a specific order... */
7593                                                         if (! vtable->initialized)
7594                                                                 INLINE_FAILURE;
7595                                                         mono_runtime_class_init (vtable);
7596                                                 }
7597                                         }
7598                                         addr = (char*)vtable->data + field->offset;
7599
7600                                         if (cfg->compile_aot)
7601                                                 NEW_SFLDACONST (cfg, ins, field);
7602                                         else
7603                                                 NEW_PCONST (cfg, ins, addr);
7604                                         ins->cil_code = ip;
7605                                 } else {
7606                                         /* 
7607                                          * insert call to mono_threads_get_static_data (GPOINTER_TO_UINT (addr)) 
7608                                          * This could be later optimized to do just a couple of
7609                                          * memory dereferences with constant offsets.
7610                                          */
7611                                         int temp;
7612                                         MonoInst *iargs [1];
7613                                         NEW_ICONST (cfg, iargs [0], GPOINTER_TO_UINT (addr));
7614                                         temp = mono_emit_jit_icall (cfg, bblock, mono_get_special_static_data, iargs, ip);
7615                                         NEW_TEMPLOAD (cfg, ins, temp);
7616                                 }
7617                         }
7618
7619                         /* FIXME: mark instructions for use in SSA */
7620                         if (*ip == CEE_LDSFLDA) {
7621                                 ins->klass = mono_class_from_mono_type (field->type);
7622                                 *sp++ = ins;
7623                         } else if (*ip == CEE_STSFLD) {
7624                                 MonoInst *store;
7625                                 CHECK_STACK (1);
7626                                 sp--;
7627                                 MONO_INST_NEW (cfg, store, mini_type_to_stind (cfg, field->type));
7628                                 store->cil_code = ip;
7629                                 store->inst_left = ins;
7630                                 store->inst_right = sp [0];
7631                                 store->flags |= ins_flag;
7632                                 ins_flag = 0;
7633
7634 #ifdef MONO_ARCH_SOFT_FLOAT
7635                                 if (store->opcode == CEE_STIND_R4)
7636                                         handle_store_float (cfg, bblock, ins, sp [0], ip);
7637                                 else
7638 #endif
7639                                 if (store->opcode == CEE_STOBJ) {
7640                                         handle_stobj (cfg, bblock, ins, sp [0], ip, mono_class_from_mono_type (field->type), FALSE, FALSE, FALSE);
7641                                 } else
7642                                         MONO_ADD_INS (bblock, store);
7643                         } else {
7644                                 gboolean is_const = FALSE;
7645                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
7646                                 if (!shared_access && !((cfg->opt & MONO_OPT_SHARED) || cfg->compile_aot) && 
7647                                     vtable->initialized && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY)) {
7648                                         gpointer addr = (char*)vtable->data + field->offset;
7649                                         int ro_type = field->type->type;
7650                                         if (ro_type == MONO_TYPE_VALUETYPE && field->type->data.klass->enumtype) {
7651                                                 ro_type = field->type->data.klass->enum_basetype->type;
7652                                         }
7653                                         /* g_print ("RO-FIELD %s.%s:%s\n", klass->name_space, klass->name, field->name);*/
7654                                         is_const = TRUE;
7655                                         switch (ro_type) {
7656                                         case MONO_TYPE_BOOLEAN:
7657                                         case MONO_TYPE_U1:
7658                                                 NEW_ICONST (cfg, *sp, *((guint8 *)addr));
7659                                                 sp++;
7660                                                 break;
7661                                         case MONO_TYPE_I1:
7662                                                 NEW_ICONST (cfg, *sp, *((gint8 *)addr));
7663                                                 sp++;
7664                                                 break;                                          
7665                                         case MONO_TYPE_CHAR:
7666                                         case MONO_TYPE_U2:
7667                                                 NEW_ICONST (cfg, *sp, *((guint16 *)addr));
7668                                                 sp++;
7669                                                 break;
7670                                         case MONO_TYPE_I2:
7671                                                 NEW_ICONST (cfg, *sp, *((gint16 *)addr));
7672                                                 sp++;
7673                                                 break;
7674                                                 break;
7675                                         case MONO_TYPE_I4:
7676                                                 NEW_ICONST (cfg, *sp, *((gint32 *)addr));
7677                                                 sp++;
7678                                                 break;                                          
7679                                         case MONO_TYPE_U4:
7680                                                 NEW_ICONST (cfg, *sp, *((guint32 *)addr));
7681                                                 sp++;
7682                                                 break;
7683 #ifndef HAVE_MOVING_COLLECTOR
7684                                         case MONO_TYPE_I:
7685                                         case MONO_TYPE_U:
7686                                         case MONO_TYPE_STRING:
7687                                         case MONO_TYPE_OBJECT:
7688                                         case MONO_TYPE_CLASS:
7689                                         case MONO_TYPE_SZARRAY:
7690                                         case MONO_TYPE_PTR:
7691                                         case MONO_TYPE_FNPTR:
7692                                         case MONO_TYPE_ARRAY:
7693                                                 NEW_PCONST (cfg, *sp, *((gpointer *)addr));
7694                                                 type_to_eval_stack_type (cfg, field->type, *sp);
7695                                                 sp++;
7696                                                 break;
7697 #endif
7698                                         case MONO_TYPE_I8:
7699                                         case MONO_TYPE_U8:
7700                                                 MONO_INST_NEW (cfg, *sp, OP_I8CONST);
7701                                                 sp [0]->type = STACK_I8;
7702                                                 sp [0]->inst_l = *((gint64 *)addr);
7703                                                 sp++;
7704                                                 break;
7705                                         case MONO_TYPE_R4:
7706                                         case MONO_TYPE_R8:
7707                                         case MONO_TYPE_VALUETYPE:
7708                                         default:
7709                                                 is_const = FALSE;
7710                                                 break;
7711                                         }
7712                                 }
7713
7714                                 if (!is_const) {
7715                                         MonoInst *load;
7716                                         CHECK_STACK_OVF (1);
7717                                         MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, field->type));
7718                                         type_to_eval_stack_type (cfg, field->type, load);
7719                                         load->cil_code = ip;
7720                                         load->inst_left = ins;
7721                                         load->flags |= ins_flag;
7722 #ifdef MONO_ARCH_SOFT_FLOAT
7723                                         if (load->opcode == CEE_LDIND_R4) {
7724                                                 int temp;
7725                                                 temp = handle_load_float (cfg, bblock, ins, ip);
7726                                                 NEW_TEMPLOAD (cfg, load, temp);
7727                                         }
7728 #endif
7729                                         *sp++ = load;
7730                                         ins_flag = 0;
7731                                 }
7732                         }
7733                         ip += 5;
7734                         break;
7735                 }
7736                 case CEE_STOBJ:
7737                         CHECK_STACK (2);
7738                         sp -= 2;
7739                         CHECK_OPSIZE (5);
7740                         token = read32 (ip + 1);
7741                         klass = mini_get_class (method, token, generic_context);
7742                         CHECK_TYPELOAD (klass);
7743                         n = mini_type_to_stind (cfg, &klass->byval_arg);
7744                         /* FIXME: handle CEE_STIND_R4 */
7745                         if (n == CEE_STOBJ) {
7746                                 handle_stobj (cfg, bblock, sp [0], sp [1], ip, klass, FALSE, FALSE, TRUE);
7747                         } else {
7748                                 /* FIXME: should check item at sp [1] is compatible with the type of the store. */
7749                                 MonoInst *store;
7750                                 MONO_INST_NEW (cfg, store, n);
7751                                 store->cil_code = ip;
7752                                 store->inst_left = sp [0];
7753                                 store->inst_right = sp [1];
7754                                 store->flags |= ins_flag;
7755                                 MONO_ADD_INS (bblock, store);
7756                         }
7757                         ins_flag = 0;
7758                         ip += 5;
7759                         inline_costs += 1;
7760                         break;
7761                 case CEE_BOX: {
7762                         MonoInst *val;
7763
7764                         CHECK_STACK (1);
7765                         --sp;
7766                         val = *sp;
7767                         CHECK_OPSIZE (5);
7768                         token = read32 (ip + 1);
7769                         klass = mini_get_class (method, token, generic_context);
7770                         CHECK_TYPELOAD (klass);
7771
7772                         if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
7773                                 GENERIC_SHARING_FAILURE (CEE_BOX);
7774
7775                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
7776                                 *sp++ = val;
7777                                 ip += 5;
7778                                 break;
7779                         }
7780                         if (klass == mono_defaults.void_class)
7781                                 UNVERIFIED;
7782                         if (target_type_is_incompatible (cfg, &klass->byval_arg, *sp))
7783                                 UNVERIFIED;
7784                         /* frequent check in generic code: box (struct), brtrue */
7785                         if (!mono_class_is_nullable (klass) &&
7786                             ip + 5 < end && ip_in_bb (cfg, bblock, ip + 5) && (ip [5] == CEE_BRTRUE || ip [5] == CEE_BRTRUE_S)) {
7787                                 /*g_print ("box-brtrue opt at 0x%04x in %s\n", real_offset, method->name);*/
7788                                 MONO_INST_NEW (cfg, ins, CEE_POP);
7789                                 MONO_ADD_INS (bblock, ins);
7790                                 ins->cil_code = ip;
7791                                 ins->inst_i0 = *sp;
7792                                 ip += 5;
7793                                 MONO_INST_NEW (cfg, ins, OP_BR);
7794                                 ins->cil_code = ip;
7795                                 MONO_ADD_INS (bblock, ins);
7796                                 if (*ip == CEE_BRTRUE_S) {
7797                                         CHECK_OPSIZE (2);
7798                                         ip++;
7799                                         target = ip + 1 + (signed char)(*ip);
7800                                         ip++;
7801                                 } else {
7802                                         CHECK_OPSIZE (5);
7803                                         ip++;
7804                                         target = ip + 4 + (gint)(read32 (ip));
7805                                         ip += 4;
7806                                 }
7807                                 GET_BBLOCK (cfg, tblock, target);
7808                                 link_bblock (cfg, bblock, tblock);
7809                                 CHECK_BBLOCK (target, ip, tblock);
7810                                 ins->inst_target_bb = tblock;
7811                                 GET_BBLOCK (cfg, tblock, ip);
7812                                 link_bblock (cfg, bblock, tblock);
7813                                 if (sp != stack_start) {
7814                                         handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
7815                                         sp = stack_start;
7816                                         CHECK_UNVERIFIABLE (cfg);
7817                                 }
7818                                 start_new_bblock = 1;
7819                                 break;
7820                         }
7821                         *sp++ = handle_box (cfg, bblock, val, ip, klass);
7822                         ip += 5;
7823                         inline_costs += 1;
7824                         break;
7825                 }
7826                 case CEE_NEWARR: {
7827                         gboolean shared_access = FALSE;
7828
7829                         CHECK_STACK (1);
7830                         --sp;
7831
7832                         CHECK_OPSIZE (5);
7833                         token = read32 (ip + 1);
7834
7835                         /* allocate the domainvar - becaus this is used in decompose_foreach */
7836                         if (cfg->opt & MONO_OPT_SHARED) {
7837                                 mono_get_domainvar (cfg);
7838                                 /* LAME-IR: Mark it as used since otherwise it will be optimized away */
7839                                 cfg->domainvar->flags |= MONO_INST_VOLATILE;
7840                         }
7841
7842                         /* Ditto */
7843                         mono_get_got_var (cfg);
7844
7845                         klass = mini_get_class (method, token, generic_context);
7846                         CHECK_TYPELOAD (klass);
7847
7848                         if (cfg->generic_sharing_context) {
7849                                 int context_used = mono_class_check_context_used (klass);
7850
7851                                 if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD || klass->valuetype)
7852                                         GENERIC_SHARING_FAILURE (CEE_NEWARR);
7853
7854                                 if (context_used)
7855                                         shared_access = TRUE;
7856                         }
7857
7858                         if (shared_access) {
7859                                 MonoInst *this = NULL, *rgctx;
7860                                 MonoInst *args [3];
7861                                 int temp;
7862
7863                                 GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD (*ip);
7864
7865                                 /* domain */
7866                                 NEW_DOMAINCONST (cfg, args [0]);
7867
7868                                 /* klass */
7869                                 if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
7870                                         NEW_ARGLOAD (cfg, this, 0);
7871                                 rgctx = get_runtime_generic_context (cfg, method, this, ip);
7872                                 args [1] = get_runtime_generic_context_ptr (cfg, method, bblock, klass,
7873                                         token, MINI_TOKEN_SOURCE_CLASS, generic_context, rgctx, MONO_RGCTX_INFO_KLASS, ip);
7874
7875                                 /* array len */
7876                                 args [2] = *sp;
7877
7878                                 temp = mono_emit_jit_icall (cfg, bblock, mono_array_new, args, ip);
7879                                 NEW_TEMPLOAD (cfg, ins, temp);
7880                         } else {
7881                                 MONO_INST_NEW (cfg, ins, *ip);
7882                                 ins->cil_code = ip;
7883                                 ins->inst_newa_class = klass;
7884                                 ins->inst_newa_len = *sp;
7885                                 ins->type = STACK_OBJ;
7886                                 ins->klass = mono_array_class_get (klass, 1);
7887                         }
7888
7889                         ip += 5;
7890                         *sp++ = ins;
7891                         /* 
7892                          * we store the object so calls to create the array are not interleaved
7893                          * with the arguments of other calls.
7894                          */
7895                         if (1) {
7896                                 MonoInst *store, *temp, *load;
7897                                 const char *data_ptr;
7898                                 int data_size = 0;
7899                                 --sp;
7900                                 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
7901                                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
7902                                 store->cil_code = ins->cil_code;
7903                                 MONO_ADD_INS (bblock, store);
7904                                 /* 
7905                                  * we inline/optimize the initialization sequence if possible.
7906                                  * we should also allocate the array as not cleared, since we spend as much time clearing to 0 as initializing
7907                                  * for small sizes open code the memcpy
7908                                  * ensure the rva field is big enough
7909                                  */
7910                                 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))) {
7911                                         MonoMethod *memcpy_method = get_memcpy_method ();
7912                                         MonoInst *data_offset, *add;
7913                                         MonoInst *iargs [3];
7914                                         NEW_ICONST (cfg, iargs [2], data_size);
7915                                         NEW_TEMPLOAD (cfg, load, temp->inst_c0);
7916                                         load->cil_code = ins->cil_code;
7917                                         NEW_ICONST (cfg, data_offset, G_STRUCT_OFFSET (MonoArray, vector));
7918                                         MONO_INST_NEW (cfg, add, OP_PADD);
7919                                         add->inst_left = load;
7920                                         add->inst_right = data_offset;
7921                                         add->cil_code = ip;
7922                                         iargs [0] = add;
7923                                         if (cfg->compile_aot) {
7924                                                 NEW_AOTCONST_TOKEN (cfg, iargs [1], MONO_PATCH_INFO_RVA, method->klass->image, GPOINTER_TO_UINT(data_ptr), STACK_PTR, NULL);
7925                                         } else {
7926                                                 NEW_PCONST (cfg, iargs [1], (char*)data_ptr);
7927                                         }
7928                                         mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
7929                                         ip += 11;
7930                                 }
7931                                 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
7932                                 load->cil_code = ins->cil_code;
7933                                 *sp++ = load;
7934                         }
7935                         inline_costs += 1;
7936                         break;
7937                 }
7938                 case CEE_LDLEN:
7939                         CHECK_STACK (1);
7940                         --sp;
7941                         if (sp [0]->type != STACK_OBJ)
7942                                 UNVERIFIED;
7943                         MONO_INST_NEW (cfg, ins, *ip);
7944                         ins->cil_code = ip++;
7945                         ins->inst_left = *sp;
7946                         ins->type = STACK_PTR;
7947                         *sp++ = ins;
7948                         break;
7949                 case CEE_LDELEMA:
7950                         CHECK_STACK (2);
7951                         sp -= 2;
7952                         CHECK_OPSIZE (5);
7953                         if (sp [0]->type != STACK_OBJ)
7954                                 UNVERIFIED;
7955
7956                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
7957                         CHECK_TYPELOAD (klass);
7958                         /* we need to make sure that this array is exactly the type it needs
7959                          * to be for correctness. the wrappers are lax with their usage
7960                          * so we need to ignore them here
7961                          */
7962                         if (!klass->valuetype && method->wrapper_type == MONO_WRAPPER_NONE) {
7963                                 MonoInst* check;
7964
7965                                 /* Needed by the code generated in inssel.brg */
7966                                 mono_get_got_var (cfg);
7967
7968                                 MONO_INST_NEW (cfg, check, OP_CHECK_ARRAY_TYPE);
7969                                 check->cil_code = ip;
7970                                 check->klass = klass;
7971                                 check->inst_left = sp [0];
7972                                 check->type = STACK_OBJ;
7973                                 check->klass = klass;
7974                                 sp [0] = check;
7975                         }
7976                         
7977                         mono_class_init (klass);
7978                         NEW_LDELEMA (cfg, ins, sp, klass);
7979                         ins->cil_code = ip;
7980                         *sp++ = ins;
7981                         ip += 5;
7982                         break;
7983                 case CEE_LDELEM_ANY: {
7984                         MonoInst *load;
7985                         CHECK_STACK (2);
7986                         sp -= 2;
7987                         if (sp [0]->type != STACK_OBJ)
7988                                 UNVERIFIED;
7989                         CHECK_OPSIZE (5);
7990                         token = read32 (ip + 1);
7991                         klass = mini_get_class (method, token, generic_context);
7992                         CHECK_TYPELOAD (klass);
7993                         mono_class_init (klass);
7994                         NEW_LDELEMA (cfg, load, sp, klass);
7995                         load->cil_code = ip;
7996                         MONO_INST_NEW (cfg, ins, mini_type_to_ldind (cfg, &klass->byval_arg));
7997                         ins->cil_code = ip;
7998                         ins->inst_left = load;
7999                         *sp++ = ins;
8000                         type_to_eval_stack_type (cfg, &klass->byval_arg, ins);
8001                         ip += 5;
8002                         break;
8003                 }
8004                 case CEE_LDELEM_I1:
8005                 case CEE_LDELEM_U1:
8006                 case CEE_LDELEM_I2:
8007                 case CEE_LDELEM_U2:
8008                 case CEE_LDELEM_I4:
8009                 case CEE_LDELEM_U4:
8010                 case CEE_LDELEM_I8:
8011                 case CEE_LDELEM_I:
8012                 case CEE_LDELEM_R4:
8013                 case CEE_LDELEM_R8:
8014                 case CEE_LDELEM_REF: {
8015                         MonoInst *load;
8016                         /*
8017                          * translate to:
8018                          * ldind.x (ldelema (array, index))
8019                          * ldelema does the bounds check
8020                          */
8021                         CHECK_STACK (2);
8022                         sp -= 2;
8023                         if (sp [0]->type != STACK_OBJ)
8024                                 UNVERIFIED;
8025                         klass = array_access_to_klass (*ip, sp [0]);
8026                         NEW_LDELEMA (cfg, load, sp, klass);
8027                         load->cil_code = ip;
8028 #ifdef MONO_ARCH_SOFT_FLOAT
8029                         if (*ip == CEE_LDELEM_R4) {
8030                                 int temp;
8031                                 temp = handle_load_float (cfg, bblock, load, ip);
8032                                 NEW_TEMPLOAD (cfg, *sp, temp);
8033                                 sp++;
8034                                 ++ip;
8035                                 break;
8036                         }
8037 #endif
8038                         MONO_INST_NEW (cfg, ins, ldelem_to_ldind [*ip - CEE_LDELEM_I1]);
8039                         ins->cil_code = ip;
8040                         ins->inst_left = load;
8041                         *sp++ = ins;
8042                         ins->type = ldind_type [ins->opcode - CEE_LDIND_I1];
8043                         ins->klass = klass;
8044                         ++ip;
8045                         break;
8046                 }
8047                 case CEE_STELEM_I:
8048                 case CEE_STELEM_I1:
8049                 case CEE_STELEM_I2:
8050                 case CEE_STELEM_I4:
8051                 case CEE_STELEM_I8:
8052                 case CEE_STELEM_R4:
8053                 case CEE_STELEM_R8: {
8054                         MonoInst *load;
8055                         /*
8056                          * translate to:
8057                          * stind.x (ldelema (array, index), val)
8058                          * ldelema does the bounds check
8059                          */
8060                         CHECK_STACK (3);
8061                         sp -= 3;
8062                         if (sp [0]->type != STACK_OBJ)
8063                                 UNVERIFIED;
8064                         klass = array_access_to_klass (*ip, sp [0]);
8065                         NEW_LDELEMA (cfg, load, sp, klass);
8066                         load->cil_code = ip;
8067 #ifdef MONO_ARCH_SOFT_FLOAT
8068                         if (*ip == CEE_STELEM_R4) {
8069                                 handle_store_float (cfg, bblock, load, sp [2], ip);
8070                                 ip++;
8071                                 break;
8072                         }
8073 #endif
8074                         MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
8075                         ins->cil_code = ip;
8076                         ins->inst_left = load;
8077                         ins->inst_right = sp [2];
8078                         ++ip;
8079                         handle_loaded_temps (cfg, bblock, stack_start, sp);
8080                         MONO_ADD_INS (bblock, ins);
8081                         inline_costs += 1;
8082                         break;
8083                 }
8084                 case CEE_STELEM_ANY: {
8085                         MonoInst *load;
8086                         /*
8087                          * translate to:
8088                          * stind.x (ldelema (array, index), val)
8089                          * ldelema does the bounds check
8090                          */
8091                         CHECK_STACK (3);
8092                         sp -= 3;
8093                         if (sp [0]->type != STACK_OBJ)
8094                                 UNVERIFIED;
8095                         CHECK_OPSIZE (5);
8096                         token = read32 (ip + 1);
8097                         klass = mini_get_class (method, token, generic_context);
8098                         CHECK_TYPELOAD (klass);
8099                         mono_class_init (klass);
8100                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
8101                                 /* storing a NULL doesn't need any of the complex checks in stelemref */
8102                                 if (sp [2]->opcode == OP_PCONST && sp [2]->inst_p0 == NULL) {
8103                                         MonoInst *load;
8104                                         NEW_LDELEMA (cfg, load, sp, mono_defaults.object_class);
8105                                         load->cil_code = ip;
8106                                         MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
8107                                         ins->cil_code = ip;
8108                                         ins->inst_left = load;
8109                                         ins->inst_right = sp [2];
8110                                         MONO_ADD_INS (bblock, ins);
8111                                 } else {
8112                                         MonoMethod* helper = mono_marshal_get_stelemref ();
8113                                         MonoInst *iargs [3];
8114                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
8115
8116                                         iargs [2] = sp [2];
8117                                         iargs [1] = sp [1];
8118                                         iargs [0] = sp [0];
8119
8120                                         mono_emit_method_call_spilled (cfg, bblock, helper, mono_method_signature (helper), iargs, ip, NULL);
8121                                 }
8122                         } else {
8123                                 NEW_LDELEMA (cfg, load, sp, klass);
8124                                 load->cil_code = ip;
8125
8126                                 n = mini_type_to_stind (cfg, &klass->byval_arg);
8127                                 /* FIXME: CEE_STIND_R4 */
8128                                 if (n == CEE_STOBJ)
8129                                         handle_stobj (cfg, bblock, load, sp [2], ip, klass, FALSE, FALSE, TRUE);
8130                                 else {
8131                                         MONO_INST_NEW (cfg, ins, n);
8132                                         ins->cil_code = ip;
8133                                         ins->inst_left = load;
8134                                         ins->inst_right = sp [2];
8135                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
8136                                         MONO_ADD_INS (bblock, ins);
8137                                 }
8138                         }
8139                         ip += 5;
8140                         inline_costs += 1;
8141                         break;
8142                 }
8143                 case CEE_STELEM_REF: {
8144                         MonoInst *iargs [3];
8145                         MonoMethod* helper = mono_marshal_get_stelemref ();
8146
8147                         CHECK_STACK (3);
8148                         sp -= 3;
8149                         if (sp [0]->type != STACK_OBJ)
8150                                 UNVERIFIED;
8151                         if (sp [2]->type != STACK_OBJ)
8152                                 UNVERIFIED;
8153
8154                         handle_loaded_temps (cfg, bblock, stack_start, sp);
8155
8156                         /* storing a NULL doesn't need any of the complex checks in stelemref */
8157                         if (sp [2]->opcode == OP_PCONST && sp [2]->inst_p0 == NULL) {
8158                                 MonoInst *load;
8159                                 NEW_LDELEMA (cfg, load, sp, mono_defaults.object_class);
8160                                 load->cil_code = ip;
8161                                 MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
8162                                 ins->cil_code = ip;
8163                                 ins->inst_left = load;
8164                                 ins->inst_right = sp [2];
8165                                 MONO_ADD_INS (bblock, ins);
8166                         } else {
8167                                 iargs [2] = sp [2];
8168                                 iargs [1] = sp [1];
8169                                 iargs [0] = sp [0];
8170                         
8171                                 mono_emit_method_call_spilled (cfg, bblock, helper, mono_method_signature (helper), iargs, ip, NULL);
8172                                 inline_costs += 1;
8173                         }
8174
8175                         ++ip;
8176                         break;
8177                 }
8178                 case CEE_CKFINITE: {
8179                         MonoInst *store, *temp;
8180                         CHECK_STACK (1);
8181
8182                         /* this instr. can throw exceptions as side effect,
8183                          * so we cant eliminate dead code which contains CKFINITE opdodes.
8184                          * Spilling to memory makes sure that we always perform
8185                          * this check */
8186
8187                         
8188                         MONO_INST_NEW (cfg, ins, OP_CKFINITE);
8189                         ins->cil_code = ip;
8190                         ins->inst_left = sp [-1];
8191                         temp = mono_compile_create_var (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL);
8192
8193                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
8194                         store->cil_code = ip;
8195                         MONO_ADD_INS (bblock, store);
8196
8197                         NEW_TEMPLOAD (cfg, sp [-1], temp->inst_c0);
8198                        
8199                         ++ip;
8200                         break;
8201                 }
8202                 case CEE_REFANYVAL:
8203                         CHECK_STACK (1);
8204                         MONO_INST_NEW (cfg, ins, *ip);
8205                         --sp;
8206                         CHECK_OPSIZE (5);
8207                         klass = mono_class_get_full (image, read32 (ip + 1), generic_context);
8208                         CHECK_TYPELOAD (klass);
8209                         mono_class_init (klass);
8210                         ins->type = STACK_MP;
8211                         ins->inst_left = *sp;
8212                         ins->klass = klass;
8213                         ins->inst_newa_class = klass;
8214                         ins->cil_code = ip;
8215                         ip += 5;
8216                         *sp++ = ins;
8217                         break;
8218                 case CEE_MKREFANY: {
8219                         MonoInst *loc, *klassconst;
8220
8221                         CHECK_STACK (1);
8222                         MONO_INST_NEW (cfg, ins, *ip);
8223                         --sp;
8224                         CHECK_OPSIZE (5);
8225                         klass = mono_class_get_full (image, read32 (ip + 1), generic_context);
8226                         CHECK_TYPELOAD (klass);
8227                         mono_class_init (klass);
8228                         ins->cil_code = ip;
8229
8230                         if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
8231                                 GENERIC_SHARING_FAILURE (CEE_MKREFANY);
8232
8233                         loc = mono_compile_create_var (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL);
8234                         NEW_TEMPLOADA (cfg, ins->inst_right, loc->inst_c0);
8235
8236                         NEW_PCONST (cfg, klassconst, klass);
8237                         NEW_GROUP (cfg, ins->inst_left, *sp, klassconst);
8238                         
8239                         MONO_ADD_INS (bblock, ins);
8240
8241                         NEW_TEMPLOAD (cfg, *sp, loc->inst_c0);
8242                         ++sp;
8243                         ip += 5;
8244                         break;
8245                 }
8246                 case CEE_LDTOKEN: {
8247                         gpointer handle;
8248                         MonoClass *handle_class;
8249                         int context_used = 0;
8250
8251                         CHECK_STACK_OVF (1);
8252
8253                         CHECK_OPSIZE (5);
8254                         n = read32 (ip + 1);
8255
8256                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8257                                 handle = mono_method_get_wrapper_data (method, n);
8258                                 handle_class = mono_method_get_wrapper_data (method, n + 1);
8259                                 if (handle_class == mono_defaults.typehandle_class)
8260                                         handle = &((MonoClass*)handle)->byval_arg;
8261                         }
8262                         else {
8263                                 handle = mono_ldtoken (image, n, &handle_class, generic_context);
8264                         }
8265                         if (!handle)
8266                                 goto load_error;
8267                         mono_class_init (handle_class);
8268
8269                         if (cfg->generic_sharing_context) {
8270                                 if (handle_class == mono_defaults.typehandle_class) {
8271                                         /* If we get a MONO_TYPE_CLASS
8272                                            then we need to provide the
8273                                            open type, not an
8274                                            instantiation of it. */
8275                                         if (mono_type_get_type (handle) == MONO_TYPE_CLASS)
8276                                                 context_used = 0;
8277                                         else
8278                                                 context_used = mono_class_check_context_used (mono_class_from_mono_type (handle));
8279                                 } else if (handle_class == mono_defaults.fieldhandle_class)
8280                                         context_used = mono_class_check_context_used (((MonoClassField*)handle)->parent);
8281                                 else if (handle_class == mono_defaults.methodhandle_class)
8282                                         context_used = mono_method_check_context_used (handle);
8283                                 else
8284                                         g_assert_not_reached ();
8285
8286                                 if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD)
8287                                         GENERIC_SHARING_FAILURE (CEE_LDTOKEN);
8288                         }
8289
8290                         if (cfg->opt & MONO_OPT_SHARED) {
8291                                 int temp;
8292                                 MonoInst *res, *store, *addr, *vtvar, *iargs [3];
8293
8294                                 GENERIC_SHARING_FAILURE (CEE_LDTOKEN);
8295
8296                                 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL); 
8297
8298                                 NEW_IMAGECONST (cfg, iargs [0], image);
8299                                 NEW_ICONST (cfg, iargs [1], n);
8300                                 NEW_PCONST (cfg, iargs [2], generic_context);
8301                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldtoken_wrapper, iargs, ip);
8302                                 NEW_TEMPLOAD (cfg, res, temp);
8303                                 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
8304                                 NEW_INDSTORE (cfg, store, addr, res, &mono_defaults.int_class->byval_arg);
8305                                 MONO_ADD_INS (bblock, store);
8306                                 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
8307                         } else {
8308                                 if ((ip + 10 < end) && ip_in_bb (cfg, bblock, ip + 5) &&
8309                                         handle_class == mono_defaults.typehandle_class &&
8310                                         ((ip [5] == CEE_CALL) || (ip [5] == CEE_CALLVIRT)) && 
8311                                         (cmethod = mini_get_method (method, read32 (ip + 6), NULL, generic_context)) &&
8312                                         (cmethod->klass == mono_defaults.monotype_class->parent) &&
8313                                         (strcmp (cmethod->name, "GetTypeFromHandle") == 0)) {
8314                                         MonoClass *tclass = mono_class_from_mono_type (handle);
8315                                         mono_class_init (tclass);
8316                                         if (context_used) {
8317                                                 MonoInst *this, *rgctx;
8318
8319                                                 g_assert (!cfg->compile_aot);
8320                                                 if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
8321                                                         NEW_ARGLOAD (cfg, this, 0);
8322                                                 rgctx = get_runtime_generic_context (cfg, method, this, ip);
8323                                                 ins = get_runtime_generic_context_ptr (cfg, method, bblock, tclass,
8324                                                         token, MINI_TOKEN_SOURCE_CLASS, generic_context,
8325                                                         rgctx, MONO_RGCTX_INFO_REFLECTION_TYPE, ip);
8326                                         } else if (cfg->compile_aot) {
8327                                                 NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, image, n);
8328                                         } else {
8329                                                 NEW_PCONST (cfg, ins, mono_type_get_object (cfg->domain, handle));
8330                                         }
8331                                         ins->type = STACK_OBJ;
8332                                         ins->klass = cmethod->klass;
8333                                         ip += 5;
8334                                 } else {
8335                                         MonoInst *store, *addr, *vtvar;
8336
8337                                         GENERIC_SHARING_FAILURE (CEE_LDTOKEN);
8338
8339                                         if (cfg->compile_aot)
8340                                                 NEW_LDTOKENCONST (cfg, ins, image, n);
8341                                         else
8342                                                 NEW_PCONST (cfg, ins, handle);
8343                                         vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL);
8344                                         NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
8345                                         NEW_INDSTORE (cfg, store, addr, ins, &mono_defaults.int_class->byval_arg);
8346                                         MONO_ADD_INS (bblock, store);
8347                                         NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
8348                                 }
8349                         }
8350
8351                         *sp++ = ins;
8352                         ip += 5;
8353                         break;
8354                 }
8355                 case CEE_CONV_U2:
8356                 case CEE_CONV_U1:
8357                 case CEE_CONV_I:
8358                         CHECK_STACK (1);
8359                         ADD_UNOP (*ip);
8360                         ip++;
8361                         break;
8362                 case CEE_ADD_OVF:
8363                 case CEE_ADD_OVF_UN:
8364                 case CEE_MUL_OVF:
8365                 case CEE_MUL_OVF_UN:
8366                 case CEE_SUB_OVF:
8367                 case CEE_SUB_OVF_UN:
8368                         CHECK_STACK (2);
8369                         ADD_BINOP (*ip);
8370                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
8371                                 --sp;
8372                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
8373                         }
8374                         ip++;
8375                         break;
8376                 case CEE_ENDFINALLY:
8377                         MONO_INST_NEW (cfg, ins, OP_ENDFINALLY);
8378                         MONO_ADD_INS (bblock, ins);
8379                         ins->cil_code = ip++;
8380                         start_new_bblock = 1;
8381
8382                         /*
8383                          * Control will leave the method so empty the stack, otherwise
8384                          * the next basic block will start with a nonempty stack.
8385                          */
8386                         while (sp != stack_start) {
8387                                 MONO_INST_NEW (cfg, ins, CEE_POP);
8388                                 ins->cil_code = ip;
8389                                 sp--;
8390                                 ins->inst_i0 = *sp;
8391                                 MONO_ADD_INS (bblock, ins);
8392                         }
8393                         break;
8394                 case CEE_LEAVE:
8395                 case CEE_LEAVE_S: {
8396                         GList *handlers;
8397
8398                         if (*ip == CEE_LEAVE) {
8399                                 CHECK_OPSIZE (5);
8400                                 target = ip + 5 + (gint32)read32(ip + 1);
8401                         } else {
8402                                 CHECK_OPSIZE (2);
8403                                 target = ip + 2 + (signed char)(ip [1]);
8404                         }
8405
8406                         /* empty the stack */
8407                         while (sp != stack_start) {
8408                                 MONO_INST_NEW (cfg, ins, CEE_POP);
8409                                 ins->cil_code = ip;
8410                                 sp--;
8411                                 ins->inst_i0 = *sp;
8412                                 MONO_ADD_INS (bblock, ins);
8413                         }
8414
8415                         /* 
8416                          * If this leave statement is in a catch block, check for a
8417                          * pending exception, and rethrow it if necessary.
8418                          */
8419                         for (i = 0; i < header->num_clauses; ++i) {
8420                                 MonoExceptionClause *clause = &header->clauses [i];
8421
8422                                 /* 
8423                                  * Use <= in the final comparison to handle clauses with multiple
8424                                  * leave statements, like in bug #78024.
8425                                  * The ordering of the exception clauses guarantees that we find the
8426                                  * innermost clause.
8427                                  */
8428                                 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)) {
8429                                         int temp;
8430                                         MonoInst *load;
8431
8432                                         NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, clause->handler_offset)->inst_c0);
8433                                         load->cil_code = ip;
8434
8435                                         temp = mono_emit_jit_icall (cfg, bblock, mono_thread_get_undeniable_exception, NULL, ip);
8436                                         NEW_TEMPLOAD (cfg, *sp, temp);
8437                                 
8438                                         MONO_INST_NEW (cfg, ins, OP_THROW_OR_NULL);
8439                                         ins->inst_left = *sp;
8440                                         ins->inst_right = load;
8441                                         ins->cil_code = ip;
8442                                         MONO_ADD_INS (bblock, ins);
8443                                 }
8444                         }
8445
8446                         if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
8447                                 GList *tmp;
8448                                 for (tmp = handlers; tmp; tmp = tmp->next) {
8449                                         tblock = tmp->data;
8450                                         link_bblock (cfg, bblock, tblock);
8451                                         MONO_INST_NEW (cfg, ins, OP_CALL_HANDLER);
8452                                         ins->cil_code = ip;
8453                                         ins->inst_target_bb = tblock;
8454                                         MONO_ADD_INS (bblock, ins);
8455                                 }
8456                                 g_list_free (handlers);
8457                         } 
8458
8459                         MONO_INST_NEW (cfg, ins, OP_BR);
8460                         ins->cil_code = ip;
8461                         MONO_ADD_INS (bblock, ins);
8462                         GET_BBLOCK (cfg, tblock, target);
8463                         link_bblock (cfg, bblock, tblock);
8464                         CHECK_BBLOCK (target, ip, tblock);
8465                         ins->inst_target_bb = tblock;
8466                         start_new_bblock = 1;
8467
8468                         if (*ip == CEE_LEAVE)
8469                                 ip += 5;
8470                         else
8471                                 ip += 2;
8472
8473                         break;
8474                 }
8475                 case CEE_STIND_I:
8476                         CHECK_STACK (2);
8477                         MONO_INST_NEW (cfg, ins, *ip);
8478                         sp -= 2;
8479                         handle_loaded_temps (cfg, bblock, stack_start, sp);
8480                         MONO_ADD_INS (bblock, ins);
8481                         ins->cil_code = ip++;
8482                         ins->inst_i0 = sp [0];
8483                         ins->inst_i1 = sp [1];
8484                         inline_costs += 1;
8485                         break;
8486                 case CEE_CONV_U:
8487                         CHECK_STACK (1);
8488                         ADD_UNOP (*ip);
8489                         ip++;
8490                         break;
8491                 /* trampoline mono specific opcodes */
8492                 case MONO_CUSTOM_PREFIX: {
8493
8494                         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
8495
8496                         CHECK_OPSIZE (2);
8497                         switch (ip [1]) {
8498
8499                         case CEE_MONO_ICALL: {
8500                                 int temp;
8501                                 gpointer func;
8502                                 MonoJitICallInfo *info;
8503
8504                                 token = read32 (ip + 2);
8505                                 func = mono_method_get_wrapper_data (method, token);
8506                                 info = mono_find_jit_icall_by_addr (func);
8507                                 if (info == NULL){
8508                                         g_error ("An attempt has been made to perform an icall to address %p, "
8509                                                  "but the address has not been registered as an icall\n", info);
8510                                         g_assert_not_reached ();
8511                                 }
8512
8513                                 CHECK_STACK (info->sig->param_count);
8514                                 sp -= info->sig->param_count;
8515
8516                                 temp = mono_emit_jit_icall (cfg, bblock, info->func, sp, ip);
8517                                 if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
8518                                         NEW_TEMPLOAD (cfg, *sp, temp);
8519                                         sp++;
8520                                 }
8521
8522                                 ip += 6;
8523                                 inline_costs += 10 * num_calls++;
8524
8525                                 break;
8526                         }
8527                         case CEE_MONO_LDPTR: {
8528                                 gpointer ptr;
8529
8530                                 CHECK_STACK_OVF (1);
8531                                 CHECK_OPSIZE (6);
8532                                 token = read32 (ip + 2);
8533
8534                                 ptr = mono_method_get_wrapper_data (method, token);
8535                                 if (cfg->compile_aot && cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
8536                                         MonoMethod *wrapped = mono_marshal_method_from_wrapper (cfg->method);
8537
8538                                         if (wrapped && ptr != NULL && mono_lookup_internal_call (wrapped) == ptr) {
8539                                                 NEW_AOTCONST (cfg, ins, MONO_PATCH_INFO_ICALL_ADDR, wrapped);
8540                                                 ins->cil_code = ip;
8541                                                 *sp++ = ins;
8542                                                 ip += 6;
8543                                                 break;
8544                                         }
8545                                 }
8546                                 NEW_PCONST (cfg, ins, ptr);
8547                                 ins->cil_code = ip;
8548                                 *sp++ = ins;
8549                                 ip += 6;
8550                                 inline_costs += 10 * num_calls++;
8551                                 /* Can't embed random pointers into AOT code */
8552                                 cfg->disable_aot = 1;
8553                                 break;
8554                         }
8555                         case CEE_MONO_VTADDR:
8556                                 CHECK_STACK (1);
8557                                 --sp;
8558                                 MONO_INST_NEW (cfg, ins, OP_VTADDR);
8559                                 ins->cil_code = ip;
8560                                 ins->type = STACK_MP;
8561                                 ins->inst_left = *sp;
8562                                 *sp++ = ins;
8563                                 ip += 2;
8564                                 break;
8565                         case CEE_MONO_NEWOBJ: {
8566                                 MonoInst *iargs [2];
8567                                 int temp;
8568                                 CHECK_STACK_OVF (1);
8569                                 CHECK_OPSIZE (6);
8570                                 token = read32 (ip + 2);
8571                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
8572                                 mono_class_init (klass);
8573                                 NEW_DOMAINCONST (cfg, iargs [0]);
8574                                 NEW_CLASSCONST (cfg, iargs [1], klass);
8575                                 temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
8576                                 NEW_TEMPLOAD (cfg, *sp, temp);
8577                                 sp++;
8578                                 ip += 6;
8579                                 inline_costs += 10 * num_calls++;
8580                                 break;
8581                         }
8582                         case CEE_MONO_OBJADDR:
8583                                 CHECK_STACK (1);
8584                                 --sp;
8585                                 MONO_INST_NEW (cfg, ins, OP_OBJADDR);
8586                                 ins->cil_code = ip;
8587                                 ins->type = STACK_MP;
8588                                 ins->inst_left = *sp;
8589                                 *sp++ = ins;
8590                                 ip += 2;
8591                                 break;
8592                         case CEE_MONO_LDNATIVEOBJ:
8593                                 CHECK_STACK (1);
8594                                 CHECK_OPSIZE (6);
8595                                 token = read32 (ip + 2);
8596                                 klass = mono_method_get_wrapper_data (method, token);
8597                                 g_assert (klass->valuetype);
8598                                 mono_class_init (klass);
8599                                 NEW_INDLOAD (cfg, ins, sp [-1], &klass->byval_arg);
8600                                 sp [-1] = ins;
8601                                 ip += 6;
8602                                 break;
8603                         case CEE_MONO_RETOBJ:
8604                                 g_assert (cfg->ret);
8605                                 g_assert (mono_method_signature (method)->pinvoke); 
8606                                 CHECK_STACK (1);
8607                                 --sp;
8608                                 
8609                                 CHECK_OPSIZE (6);
8610                                 token = read32 (ip + 2);    
8611                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
8612
8613                                 NEW_RETLOADA (cfg, ins);
8614                                 handle_stobj (cfg, bblock, ins, *sp, ip, klass, FALSE, TRUE, FALSE);
8615                                 
8616                                 if (sp != stack_start)
8617                                         UNVERIFIED;
8618                                 
8619                                 MONO_INST_NEW (cfg, ins, OP_BR);
8620                                 ins->cil_code = ip;
8621                                 ins->inst_target_bb = end_bblock;
8622                                 MONO_ADD_INS (bblock, ins);
8623                                 link_bblock (cfg, bblock, end_bblock);
8624                                 start_new_bblock = 1;
8625                                 ip += 6;
8626                                 break;
8627                         case CEE_MONO_CISINST:
8628                         case CEE_MONO_CCASTCLASS: {
8629                                 int token;
8630                                 CHECK_STACK (1);
8631                                 --sp;
8632                                 CHECK_OPSIZE (6);
8633                                 token = read32 (ip + 2);
8634                                 /* Needed by the code generated in inssel.brg */
8635                                 mono_get_got_var (cfg);
8636                 
8637                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
8638                                 MONO_INST_NEW (cfg, ins, (ip [1] == CEE_MONO_CISINST) ? OP_CISINST : OP_CCASTCLASS);
8639                                 ins->type = STACK_I4;
8640                                 ins->inst_left = *sp;
8641                                 ins->inst_newa_class = klass;
8642                                 ins->cil_code = ip;
8643                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 6);
8644                                 ip += 6;
8645                                 break;
8646                         }
8647                         case CEE_MONO_SAVE_LMF:
8648                         case CEE_MONO_RESTORE_LMF:
8649 #ifdef MONO_ARCH_HAVE_LMF_OPS
8650                                 MONO_INST_NEW (cfg, ins, (ip [1] == CEE_MONO_SAVE_LMF) ? OP_SAVE_LMF : OP_RESTORE_LMF);
8651                                 MONO_ADD_INS (bblock, ins);
8652                                 cfg->need_lmf_area = TRUE;
8653 #endif
8654                                 ip += 2;
8655                                 break;
8656                         case CEE_MONO_CLASSCONST:
8657                                 CHECK_STACK_OVF (1);
8658                                 CHECK_OPSIZE (6);
8659                                 token = read32 (ip + 2);
8660                                 NEW_CLASSCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
8661                                 ins->cil_code = ip;
8662                                 *sp++ = ins;
8663                                 ip += 6;
8664                                 inline_costs += 10 * num_calls++;
8665                                 break;
8666                         case CEE_MONO_NOT_TAKEN:
8667                                 bblock->out_of_line = TRUE;
8668                                 ip += 2;
8669                                 break;
8670                         case CEE_MONO_TLS:
8671                                 CHECK_STACK_OVF (1);
8672                                 CHECK_OPSIZE (6);
8673                                 MONO_INST_NEW (cfg, ins, OP_TLS_GET);
8674                                 ins->inst_offset = (gint32)read32 (ip + 2);
8675                                 ins->cil_code = ip;
8676                                 ins->type = STACK_PTR;
8677                                 *sp++ = ins;
8678                                 ip += 6;
8679                                 break;
8680                         default:
8681                                 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
8682                                 break;
8683                         }
8684                         break;
8685                 }
8686                 case CEE_PREFIX1: {
8687                         CHECK_OPSIZE (2);
8688                         switch (ip [1]) {
8689                         case CEE_ARGLIST: {
8690                                 /* somewhat similar to LDTOKEN */
8691                                 MonoInst *addr, *vtvar;
8692                                 CHECK_STACK_OVF (1);
8693                                 vtvar = mono_compile_create_var (cfg, &mono_defaults.argumenthandle_class->byval_arg, OP_LOCAL); 
8694
8695                                 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
8696                                 addr->cil_code = ip;
8697                                 MONO_INST_NEW (cfg, ins, OP_ARGLIST);
8698                                 ins->cil_code = ip;
8699                                 ins->inst_left = addr;
8700                                 MONO_ADD_INS (bblock, ins);
8701                                 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
8702                                 ins->cil_code = ip;
8703                                 *sp++ = ins;
8704                                 ip += 2;
8705                                 break;
8706                         }
8707                         case CEE_CEQ:
8708                         case CEE_CGT:
8709                         case CEE_CGT_UN:
8710                         case CEE_CLT:
8711                         case CEE_CLT_UN: {
8712                                 MonoInst *cmp;
8713                                 CHECK_STACK (2);
8714                                 /*
8715                                  * The following transforms:
8716                                  *    CEE_CEQ    into OP_CEQ
8717                                  *    CEE_CGT    into OP_CGT
8718                                  *    CEE_CGT_UN into OP_CGT_UN
8719                                  *    CEE_CLT    into OP_CLT
8720                                  *    CEE_CLT_UN into OP_CLT_UN
8721                                  */
8722                                 MONO_INST_NEW (cfg, cmp, (OP_CEQ - CEE_CEQ) + ip [1]);
8723                                 
8724                                 MONO_INST_NEW (cfg, ins, cmp->opcode);
8725                                 sp -= 2;
8726                                 cmp->inst_i0 = sp [0];
8727                                 cmp->inst_i1 = sp [1];
8728                                 cmp->cil_code = ip;
8729                                 type_from_op (cmp);
8730                                 CHECK_TYPE (cmp);
8731                                 ins->cil_code = ip;
8732                                 ins->type = STACK_I4;
8733                                 ins->inst_i0 = cmp;
8734 #if MONO_ARCH_SOFT_FLOAT
8735                                 if (sp [0]->type == STACK_R8) {
8736                                         cmp->type = STACK_I4;
8737                                         *sp++ = emit_tree (cfg, bblock, cmp, ip + 2);
8738                                         ip += 2;
8739                                         break;
8740                                 }
8741 #endif
8742                                 if ((sp [0]->type == STACK_I8) || ((sizeof (gpointer) == 8) && ((sp [0]->type == STACK_PTR) || (sp [0]->type == STACK_OBJ) || (sp [0]->type == STACK_MP))))
8743                                         cmp->opcode = OP_LCOMPARE;
8744                                 else
8745                                         cmp->opcode = OP_COMPARE;
8746                                 *sp++ = ins;
8747                                 /* spill it to reduce the expression complexity
8748                                  * and workaround bug 54209 
8749                                  */
8750                                 if (cmp->inst_left->type == STACK_I8) {
8751                                         --sp;
8752                                         *sp++ = emit_tree (cfg, bblock, ins, ip + 2);
8753                                 }
8754                                 ip += 2;
8755                                 break;
8756                         }
8757                         case CEE_LDFTN: {
8758                                 MonoInst *argconst;
8759                                 MonoMethod *cil_method, *ctor_method;
8760                                 int temp;
8761                                 gboolean is_shared;
8762
8763                                 CHECK_STACK_OVF (1);
8764                                 CHECK_OPSIZE (6);
8765                                 n = read32 (ip + 2);
8766                                 cmethod = mini_get_method (method, n, NULL, generic_context);
8767                                 if (!cmethod)
8768                                         goto load_error;
8769                                 mono_class_init (cmethod->klass);
8770
8771                                 if (cfg->generic_sharing_context && mono_method_check_context_used (cmethod))
8772                                         GENERIC_SHARING_FAILURE (CEE_LDFTN);
8773
8774                                 is_shared = (cmethod->flags & METHOD_ATTRIBUTE_STATIC) &&
8775                                         (cmethod->klass->generic_class || cmethod->klass->generic_container) &&
8776                                         mono_class_generic_sharing_enabled (cmethod->klass);
8777
8778                                 cil_method = cmethod;
8779                                 if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_method (method, cmethod))
8780                                         METHOD_ACCESS_FAILURE;
8781                                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
8782                                         if (check_linkdemand (cfg, method, cmethod, bblock, ip))
8783                                                 INLINE_FAILURE;
8784                                         CHECK_CFG_EXCEPTION;
8785                                 } else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
8786                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod, bblock, ip);
8787                                 }
8788
8789                                 /* 
8790                                  * Optimize the common case of ldftn+delegate creation
8791                                  */
8792 #if defined(MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE) && !defined(HAVE_WRITE_BARRIERS)
8793                                 /* FIXME: SGEN support */
8794                                 /* FIXME: handle shared static generic methods */
8795                                 if (!is_shared && (sp > stack_start) && (ip + 6 + 5 < end) && ip_in_bb (cfg, bblock, ip + 6) && (ip [6] == CEE_NEWOBJ) && (ctor_method = mini_get_method (method, read32 (ip + 7), NULL, generic_context)) && (ctor_method->klass->parent == mono_defaults.multicastdelegate_class)) {
8796                                         MonoInst *target_ins;
8797
8798                                         ip += 6;
8799                                         if (cfg->verbose_level > 3)
8800                                                 g_print ("converting (in B%d: stack: %d) %s", bblock->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
8801                                         target_ins = sp [-1];
8802                                         sp --;
8803                                         *sp = handle_delegate_ctor (cfg, bblock, ctor_method->klass, target_ins, cmethod, ip);
8804                                         ip += 5;                                        
8805                                         sp ++;
8806                                         break;
8807                                 }
8808 #endif
8809
8810                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
8811
8812                                 if (is_shared)
8813                                         NEW_METHODCONST (cfg, argconst, mono_marshal_get_static_rgctx_invoke (cmethod));
8814                                 else
8815                                         NEW_METHODCONST (cfg, argconst, cmethod);
8816                                 if (method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED)
8817                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn, &argconst, ip);
8818                                 else
8819                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn_nosync, &argconst, ip);
8820                                 NEW_TEMPLOAD (cfg, *sp, temp);
8821                                 sp ++;
8822                                 
8823                                 ip += 6;
8824                                 inline_costs += 10 * num_calls++;
8825                                 break;
8826                         }
8827                         case CEE_LDVIRTFTN: {
8828                                 MonoInst *args [2];
8829                                 int temp;
8830
8831                                 CHECK_STACK (1);
8832                                 CHECK_OPSIZE (6);
8833                                 n = read32 (ip + 2);
8834                                 cmethod = mini_get_method (method, n, NULL, generic_context);
8835                                 if (!cmethod)
8836                                         goto load_error;
8837                                 mono_class_init (cmethod->klass);
8838
8839                                 if (cfg->generic_sharing_context && mono_method_check_context_used (cmethod))
8840                                         GENERIC_SHARING_FAILURE (CEE_LDVIRTFTN);
8841
8842                                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
8843                                         if (check_linkdemand (cfg, method, cmethod, bblock, ip))
8844                                                 INLINE_FAILURE;
8845                                         CHECK_CFG_EXCEPTION;
8846                                 } else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
8847                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod, bblock, ip);
8848                                 }
8849
8850                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
8851
8852                                 --sp;
8853                                 args [0] = *sp;
8854                                 NEW_METHODCONST (cfg, args [1], cmethod);
8855                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldvirtfn, args, ip);
8856                                 NEW_TEMPLOAD (cfg, *sp, temp);
8857                                 sp ++;
8858
8859                                 ip += 6;
8860                                 inline_costs += 10 * num_calls++;
8861                                 break;
8862                         }
8863                         case CEE_LDARG:
8864                                 CHECK_STACK_OVF (1);
8865                                 CHECK_OPSIZE (4);
8866                                 n = read16 (ip + 2);
8867                                 CHECK_ARG (n);
8868                                 NEW_ARGLOAD (cfg, ins, n);
8869                                 LDARG_SOFT_FLOAT (cfg, ins, n, ip);
8870                                 ins->cil_code = ip;
8871                                 *sp++ = ins;
8872                                 ip += 4;
8873                                 break;
8874                         case CEE_LDARGA:
8875                                 CHECK_STACK_OVF (1);
8876                                 CHECK_OPSIZE (4);
8877                                 n = read16 (ip + 2);
8878                                 CHECK_ARG (n);
8879                                 NEW_ARGLOADA (cfg, ins, n);
8880                                 ins->cil_code = ip;
8881                                 *sp++ = ins;
8882                                 ip += 4;
8883                                 break;
8884                         case CEE_STARG:
8885                                 CHECK_STACK (1);
8886                                 --sp;
8887                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
8888                                 CHECK_OPSIZE (4);
8889                                 n = read16 (ip + 2);
8890                                 CHECK_ARG (n);
8891                                 NEW_ARGSTORE (cfg, ins, n, *sp);
8892                                 ins->cil_code = ip;
8893                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [n], *sp))
8894                                         UNVERIFIED;
8895                                 STARG_SOFT_FLOAT (cfg, ins, n, ip);
8896                                 if (ins->opcode == CEE_STOBJ) {
8897                                         NEW_ARGLOADA (cfg, ins, n);
8898                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
8899                                 } else
8900                                         MONO_ADD_INS (bblock, ins);
8901                                 ip += 4;
8902                                 break;
8903                         case CEE_LDLOC:
8904                                 CHECK_STACK_OVF (1);
8905                                 CHECK_OPSIZE (4);
8906                                 n = read16 (ip + 2);
8907                                 CHECK_LOCAL (n);
8908                                 NEW_LOCLOAD (cfg, ins, n);
8909                                 LDLOC_SOFT_FLOAT (cfg, ins, n, ip);
8910                                 ins->cil_code = ip;
8911                                 *sp++ = ins;
8912                                 ip += 4;
8913                                 break;
8914                         case CEE_LDLOCA:
8915                                 CHECK_STACK_OVF (1);
8916                                 CHECK_OPSIZE (4);
8917                                 n = read16 (ip + 2);
8918                                 CHECK_LOCAL (n);
8919                                 NEW_LOCLOADA (cfg, ins, n);
8920                                 ins->cil_code = ip;
8921                                 *sp++ = ins;
8922                                 ip += 4;
8923                                 break;
8924                         case CEE_STLOC:
8925                                 CHECK_STACK (1);
8926                                 --sp;
8927                                 CHECK_OPSIZE (4);
8928                                 n = read16 (ip + 2);
8929                                 CHECK_LOCAL (n);
8930                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
8931                                 NEW_LOCSTORE (cfg, ins, n, *sp);
8932                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
8933                                         UNVERIFIED;
8934                                 ins->cil_code = ip;
8935                                 STLOC_SOFT_FLOAT (cfg, ins, n, ip);
8936                                 if (ins->opcode == CEE_STOBJ) {
8937                                         NEW_LOCLOADA (cfg, ins, n);
8938                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
8939                                 } else
8940                                         MONO_ADD_INS (bblock, ins);
8941                                 ip += 4;
8942                                 inline_costs += 1;
8943                                 break;
8944                         case CEE_LOCALLOC:
8945                                 CHECK_STACK (1);
8946                                 --sp;
8947                                 if (sp != stack_start) 
8948                                         UNVERIFIED;
8949                                 if (cfg->method != method) 
8950                                         /* 
8951                                          * Inlining this into a loop in a parent could lead to 
8952                                          * stack overflows which is different behavior than the
8953                                          * non-inlined case, thus disable inlining in this case.
8954                                          */
8955                                         goto inline_failure;
8956                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
8957                                 ins->inst_left = *sp;
8958                                 ins->cil_code = ip;
8959                                 ins->type = STACK_PTR;
8960
8961                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
8962                                 if (header->init_locals)
8963                                         ins->flags |= MONO_INST_INIT;
8964
8965                                 *sp++ = ins;
8966                                 ip += 2;
8967                                 /* FIXME: set init flag if locals init is set in this method */
8968                                 break;
8969                         case CEE_ENDFILTER: {
8970                                 MonoExceptionClause *clause, *nearest;
8971                                 int cc, nearest_num;
8972
8973                                 CHECK_STACK (1);
8974                                 --sp;
8975                                 if ((sp != stack_start) || (sp [0]->type != STACK_I4)) 
8976                                         UNVERIFIED;
8977                                 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
8978                                 ins->inst_left = *sp;
8979                                 ins->cil_code = ip;
8980                                 MONO_ADD_INS (bblock, ins);
8981                                 start_new_bblock = 1;
8982                                 ip += 2;
8983
8984                                 nearest = NULL;
8985                                 nearest_num = 0;
8986                                 for (cc = 0; cc < header->num_clauses; ++cc) {
8987                                         clause = &header->clauses [cc];
8988                                         if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
8989                                                 ((ip - header->code) > clause->data.filter_offset && (ip - header->code) <= clause->handler_offset) &&
8990                                             (!nearest || (clause->data.filter_offset < nearest->data.filter_offset))) {
8991                                                 nearest = clause;
8992                                                 nearest_num = cc;
8993                                         }
8994                                 }
8995                                 g_assert (nearest);
8996                                 if ((ip - header->code) != nearest->handler_offset)
8997                                         UNVERIFIED;
8998
8999                                 break;
9000                         }
9001                         case CEE_UNALIGNED_:
9002                                 ins_flag |= MONO_INST_UNALIGNED;
9003                                 /* FIXME: record alignment? we can assume 1 for now */
9004                                 CHECK_OPSIZE (3);
9005                                 ip += 3;
9006                                 break;
9007                         case CEE_VOLATILE_:
9008                                 ins_flag |= MONO_INST_VOLATILE;
9009                                 ip += 2;
9010                                 break;
9011                         case CEE_TAIL_:
9012                                 ins_flag   |= MONO_INST_TAILCALL;
9013                                 cfg->flags |= MONO_CFG_HAS_TAIL;
9014                                 /* Can't inline tail calls at this time */
9015                                 inline_costs += 100000;
9016                                 ip += 2;
9017                                 break;
9018                         case CEE_INITOBJ: {
9019                                 gboolean generic_shared = FALSE;
9020
9021                                 CHECK_STACK (1);
9022                                 --sp;
9023                                 CHECK_OPSIZE (6);
9024                                 token = read32 (ip + 2);
9025                                 klass = mini_get_class (method, token, generic_context);
9026                                 CHECK_TYPELOAD (klass);
9027
9028                                 if (cfg->generic_sharing_context && mono_class_check_context_used (klass)) {
9029                                         if (generic_class_is_reference_type (cfg, klass))
9030                                                 generic_shared = TRUE;
9031                                         else
9032                                                 GENERIC_SHARING_FAILURE (CEE_INITOBJ);
9033                                 }
9034
9035                                 if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg) || generic_shared) {
9036                                         MonoInst *store, *load;
9037                                         NEW_PCONST (cfg, load, NULL);
9038                                         load->cil_code = ip;
9039                                         load->type = STACK_OBJ;
9040                                         load->klass = klass;
9041                                         MONO_INST_NEW (cfg, store, CEE_STIND_REF);
9042                                         store->cil_code = ip;
9043                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
9044                                         MONO_ADD_INS (bblock, store);
9045                                         store->inst_i0 = sp [0];
9046                                         store->inst_i1 = load;
9047                                 } else {
9048                                         handle_initobj (cfg, bblock, *sp, NULL, klass, stack_start, sp);
9049                                 }
9050                                 ip += 6;
9051                                 inline_costs += 1;
9052                                 break;
9053                         }
9054                         case CEE_CONSTRAINED_:
9055                                 /* FIXME: implement */
9056                                 CHECK_OPSIZE (6);
9057                                 token = read32 (ip + 2);
9058                                 constrained_call = mono_class_get_full (image, token, generic_context);
9059                                 CHECK_TYPELOAD (constrained_call);
9060                                 ip += 6;
9061                                 break;
9062                         case CEE_CPBLK:
9063                         case CEE_INITBLK: {
9064                                 MonoInst *iargs [3];
9065                                 CHECK_STACK (3);
9066                                 sp -= 3;
9067                                 if ((cfg->opt & MONO_OPT_INTRINS) && (ip [1] == CEE_CPBLK) && (sp [2]->opcode == OP_ICONST) && ((n = sp [2]->inst_c0) <= sizeof (gpointer) * 5)) {
9068                                         MonoInst *copy;
9069                                         NEW_MEMCPY (cfg, copy, sp [0], sp [1], n, 0);
9070                                         MONO_ADD_INS (bblock, copy);
9071                                         ip += 2;
9072                                         break;
9073                                 }
9074                                 iargs [0] = sp [0];
9075                                 iargs [1] = sp [1];
9076                                 iargs [2] = sp [2];
9077                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
9078                                 if (ip [1] == CEE_CPBLK) {
9079                                         MonoMethod *memcpy_method = get_memcpy_method ();
9080                                         mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
9081                                 } else {
9082                                         MonoMethod *memset_method = get_memset_method ();
9083                                         mono_emit_method_call_spilled (cfg, bblock, memset_method, memset_method->signature, iargs, ip, NULL);
9084                                 }
9085                                 ip += 2;
9086                                 inline_costs += 1;
9087                                 break;
9088                         }
9089                         case CEE_NO_:
9090                                 CHECK_OPSIZE (3);
9091                                 if (ip [2] & 0x1)
9092                                         ins_flag |= MONO_INST_NOTYPECHECK;
9093                                 if (ip [2] & 0x2)
9094                                         ins_flag |= MONO_INST_NORANGECHECK;
9095                                 /* we ignore the no-nullcheck for now since we
9096                                  * really do it explicitly only when doing callvirt->call
9097                                  */
9098                                 ip += 3;
9099                                 break;
9100                         case CEE_RETHROW: {
9101                                 MonoInst *load;
9102                                 int handler_offset = -1;
9103
9104                                 for (i = 0; i < header->num_clauses; ++i) {
9105                                         MonoExceptionClause *clause = &header->clauses [i];
9106                                         if (MONO_OFFSET_IN_HANDLER (clause, ip - header->code) && !(clause->flags & MONO_EXCEPTION_CLAUSE_FINALLY))
9107                                                 handler_offset = clause->handler_offset;
9108                                 }
9109
9110                                 bblock->flags |= BB_EXCEPTION_UNSAFE;
9111
9112                                 g_assert (handler_offset != -1);
9113
9114                                 NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, handler_offset)->inst_c0);
9115                                 load->cil_code = ip;
9116                                 MONO_INST_NEW (cfg, ins, OP_RETHROW);
9117                                 ins->inst_left = load;
9118                                 ins->cil_code = ip;
9119                                 MONO_ADD_INS (bblock, ins);
9120                                 sp = stack_start;
9121                                 link_bblock (cfg, bblock, end_bblock);
9122                                 start_new_bblock = 1;
9123                                 ip += 2;
9124                                 break;
9125                         }
9126                         case CEE_SIZEOF:
9127                                 GENERIC_SHARING_FAILURE (CEE_SIZEOF);
9128
9129                                 CHECK_STACK_OVF (1);
9130                                 CHECK_OPSIZE (6);
9131                                 token = read32 (ip + 2);
9132                                 /* FIXXME: handle generics. */
9133                                 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC) {
9134                                         MonoType *type = mono_type_create_from_typespec (image, token);
9135                                         token = mono_type_size (type, &ialign);
9136                                 } else {
9137                                         MonoClass *klass = mono_class_get_full (image, token, generic_context);
9138                                         CHECK_TYPELOAD (klass);
9139                                         mono_class_init (klass);
9140                                         token = mono_class_value_size (klass, &align);
9141                                 }
9142                                 NEW_ICONST (cfg, ins, token);
9143                                 ins->cil_code = ip;
9144                                 *sp++= ins;
9145                                 ip += 6;
9146                                 break;
9147                         case CEE_REFANYTYPE:
9148                                 CHECK_STACK (1);
9149                                 MONO_INST_NEW (cfg, ins, OP_REFANYTYPE);
9150                                 --sp;
9151                                 ins->type = STACK_MP;
9152                                 ins->inst_left = *sp;
9153                                 ins->type = STACK_VTYPE;
9154                                 ins->klass = mono_defaults.typehandle_class;
9155                                 ins->cil_code = ip;
9156                                 ip += 2;
9157                                 *sp++ = ins;
9158                                 break;
9159                         case CEE_READONLY_:
9160                                 ip += 2;
9161                                 break;
9162                         default:
9163                                 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
9164                         }
9165                         break;
9166                 }
9167                 default:
9168                         g_error ("opcode 0x%02x not handled", *ip);
9169                 }
9170         }
9171         if (start_new_bblock != 1)
9172                 UNVERIFIED;
9173
9174         bblock->cil_length = ip - bblock->cil_code;
9175         bblock->next_bb = end_bblock;
9176
9177         if (cfg->method == method && cfg->domainvar) {
9178                 MonoInst *store;
9179                 MonoInst *get_domain;
9180                 
9181                 if (! (get_domain = mono_arch_get_domain_intrinsic (cfg))) {
9182                         MonoCallInst *call;
9183                         
9184                         MONO_INST_NEW_CALL (cfg, call, OP_CALL);
9185                         call->signature = helper_sig_domain_get;
9186                         call->inst.type = STACK_PTR;
9187                         call->fptr = mono_domain_get;
9188                         get_domain = (MonoInst*)call;
9189                 }
9190                 
9191                 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, get_domain);
9192                 MONO_ADD_INS (init_localsbb, store);
9193         }
9194
9195         if (cfg->method == method && cfg->got_var)
9196                 mono_emit_load_got_addr (cfg);
9197
9198         if (header->init_locals) {
9199                 MonoInst *store;
9200                 for (i = 0; i < header->num_locals; ++i) {
9201                         MonoType *ptype = header->locals [i];
9202                         int t = ptype->type;
9203                         if (t == MONO_TYPE_VALUETYPE && ptype->data.klass->enumtype)
9204                                 t = ptype->data.klass->enum_basetype->type;
9205                         if (ptype->byref) {
9206                                 NEW_PCONST (cfg, ins, NULL);
9207                                 NEW_LOCSTORE (cfg, store, i, ins);
9208                                 MONO_ADD_INS (init_localsbb, store);
9209                         } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
9210                                 NEW_ICONST (cfg, ins, 0);
9211                                 NEW_LOCSTORE (cfg, store, i, ins);
9212                                 MONO_ADD_INS (init_localsbb, store);
9213                         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
9214                                 MONO_INST_NEW (cfg, ins, OP_I8CONST);
9215                                 ins->type = STACK_I8;
9216                                 ins->inst_l = 0;
9217                                 NEW_LOCSTORE (cfg, store, i, ins);
9218                                 MONO_ADD_INS (init_localsbb, store);
9219                         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
9220 #ifdef MONO_ARCH_SOFT_FLOAT
9221                                 /* FIXME: handle init of R4 */
9222 #else
9223                                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
9224                                 ins->type = STACK_R8;
9225                                 ins->inst_p0 = (void*)&r8_0;
9226                                 NEW_LOCSTORE (cfg, store, i, ins);
9227                                 MONO_ADD_INS (init_localsbb, store);
9228 #endif
9229                         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
9230                                    ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (ptype))) {
9231                                 NEW_LOCLOADA (cfg, ins, i);
9232                                 handle_initobj (cfg, init_localsbb, ins, NULL, mono_class_from_mono_type (ptype), NULL, NULL);
9233                         } else {
9234                                 NEW_PCONST (cfg, ins, NULL);
9235                                 NEW_LOCSTORE (cfg, store, i, ins);
9236                                 MONO_ADD_INS (init_localsbb, store);
9237                         }
9238                 }
9239         }
9240
9241         /* resolve backward branches in the middle of an existing basic block */
9242         for (tmp = bb_recheck; tmp; tmp = tmp->next) {
9243                 bblock = tmp->data;
9244                 /*g_print ("need recheck in %s at IL_%04x\n", method->name, bblock->cil_code - header->code);*/
9245                 tblock = find_previous (cfg->cil_offset_to_bb, header->code_size, start_bblock, bblock->cil_code);
9246                 if (tblock != start_bblock) {
9247                         int l;
9248                         split_bblock (cfg, tblock, bblock);
9249                         l = bblock->cil_code - header->code;
9250                         bblock->cil_length = tblock->cil_length - l;
9251                         tblock->cil_length = l;
9252                 } else {
9253                         g_print ("recheck failed.\n");
9254                 }
9255         }
9256
9257         if (cfg->method == method) {
9258                 MonoBasicBlock *bb;
9259                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
9260                         bb->region = mono_find_block_region (cfg, bb->real_offset);
9261                         if (cfg->spvars)
9262                                 mono_create_spvar_for_region (cfg, bb->region);
9263                         if (cfg->verbose_level > 2)
9264                                 g_print ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
9265                 }
9266         }
9267
9268         g_slist_free (class_inits);
9269         dont_inline = g_list_remove (dont_inline, method);
9270
9271         if (inline_costs < 0) {
9272                 char *mname;
9273
9274                 /* Method is too large */
9275                 mname = mono_method_full_name (method, TRUE);
9276                 cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
9277                 cfg->exception_message = g_strdup_printf ("Method %s is too complex.", mname);
9278                 g_free (mname);
9279                 return -1;
9280         }
9281
9282         return inline_costs;
9283
9284  exception_exit:
9285         g_assert (cfg->exception_type != MONO_EXCEPTION_NONE);
9286         g_slist_free (class_inits);
9287         dont_inline = g_list_remove (dont_inline, method);
9288         return -1;
9289
9290  inline_failure:
9291         g_slist_free (class_inits);
9292         dont_inline = g_list_remove (dont_inline, method);
9293         return -1;
9294
9295  load_error:
9296         g_slist_free (class_inits);
9297         dont_inline = g_list_remove (dont_inline, method);
9298         cfg->exception_type = MONO_EXCEPTION_TYPE_LOAD;
9299         return -1;
9300
9301  unverified:
9302         g_slist_free (class_inits);
9303         dont_inline = g_list_remove (dont_inline, method);
9304         set_exception_type_from_invalid_il (cfg, method, ip);
9305         return -1;
9306 }
9307
9308 void
9309 mono_print_tree (MonoInst *tree) {
9310         int arity;
9311
9312         if (!tree)
9313                 return;
9314
9315         arity = mono_burg_arity [tree->opcode];
9316
9317         printf (" %s%s", arity?"(":"",  mono_inst_name (tree->opcode));
9318
9319         switch (tree->opcode) {
9320         case OP_ICONST:
9321                 printf ("[%d]", (int)tree->inst_c0);
9322                 break;
9323         case OP_I8CONST:
9324                 printf ("[%lld]", (long long)tree->inst_l);
9325                 break;
9326         case OP_R8CONST:
9327                 printf ("[%f]", *(double*)tree->inst_p0);
9328                 break;
9329         case OP_R4CONST:
9330                 printf ("[%f]", *(float*)tree->inst_p0);
9331                 break;
9332         case OP_ARG:
9333         case OP_LOCAL:
9334                 printf ("[%d]", (int)tree->inst_c0);
9335                 break;
9336         case OP_REGOFFSET:
9337                 if (tree->inst_offset < 0)
9338                         printf ("[-0x%x(%s)]", (int)(-tree->inst_offset), mono_arch_regname (tree->inst_basereg));
9339                 else
9340                         printf ("[0x%x(%s)]", (int)(tree->inst_offset), mono_arch_regname (tree->inst_basereg));
9341                 break;
9342         case OP_REGVAR:
9343                 printf ("[%s]", mono_arch_regname (tree->dreg));
9344                 break;
9345         case CEE_NEWARR:
9346                 printf ("[%s]",  tree->inst_newa_class->name);
9347                 mono_print_tree (tree->inst_newa_len);
9348                 break;
9349         case OP_CALL:
9350         case OP_CALLVIRT:
9351         case OP_FCALL:
9352         case OP_FCALLVIRT:
9353         case OP_LCALL:
9354         case OP_LCALLVIRT:
9355         case OP_VCALL:
9356         case OP_VCALLVIRT:
9357         case OP_VOIDCALL:
9358         case OP_VOIDCALLVIRT:
9359         case OP_TRAMPCALL_VTABLE: {
9360                 MonoCallInst *call = (MonoCallInst*)tree;
9361                 if (call->method)
9362                         printf ("[%s]", call->method->name);
9363                 else if (call->fptr) {
9364                         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (call->fptr);
9365                         if (info)
9366                                 printf ("[%s]", info->name);
9367                 }
9368                 break;
9369         }
9370         case OP_PHI: {
9371                 int i;
9372                 printf ("[%d (", (int)tree->inst_c0);
9373                 for (i = 0; i < tree->inst_phi_args [0]; i++) {
9374                         if (i)
9375                                 printf (", ");
9376                         printf ("%d", tree->inst_phi_args [i + 1]);
9377                 }
9378                 printf (")]");
9379                 break;
9380         }
9381         case OP_RENAME:
9382         case OP_RETARG:
9383         case OP_NOP:
9384         case OP_JMP:
9385         case OP_BREAK:
9386                 break;
9387         case OP_LOAD_MEMBASE:
9388         case OP_LOADI4_MEMBASE:
9389         case OP_LOADU4_MEMBASE:
9390         case OP_LOADU1_MEMBASE:
9391         case OP_LOADI1_MEMBASE:
9392         case OP_LOADU2_MEMBASE:
9393         case OP_LOADI2_MEMBASE:
9394                 printf ("[%s] <- [%s + 0x%x]", mono_arch_regname (tree->dreg), mono_arch_regname (tree->inst_basereg), (int)tree->inst_offset);
9395                 break;
9396         case OP_BR:
9397         case OP_CALL_HANDLER:
9398                 printf ("[B%d]", tree->inst_target_bb->block_num);
9399                 break;
9400         case OP_SWITCH:
9401         case CEE_ISINST:
9402         case CEE_CASTCLASS:
9403         case OP_OUTARG:
9404         case OP_CALL_REG:
9405         case OP_FCALL_REG:
9406         case OP_LCALL_REG:
9407         case OP_VCALL_REG:
9408         case OP_VOIDCALL_REG:
9409                 mono_print_tree (tree->inst_left);
9410                 break;
9411         case CEE_BNE_UN:
9412         case CEE_BEQ:
9413         case CEE_BLT:
9414         case CEE_BLT_UN:
9415         case CEE_BGT:
9416         case CEE_BGT_UN:
9417         case CEE_BGE:
9418         case CEE_BGE_UN:
9419         case CEE_BLE:
9420         case CEE_BLE_UN:
9421                 printf ("[B%dB%d]", tree->inst_true_bb->block_num, tree->inst_false_bb->block_num);
9422                 mono_print_tree (tree->inst_left);
9423                 break;
9424         default:
9425                 if (!mono_arch_print_tree(tree, arity)) {
9426                         if (arity) {
9427                                 mono_print_tree (tree->inst_left);
9428                                 if (arity > 1)
9429                                         mono_print_tree (tree->inst_right);
9430                         }
9431                 }
9432                 break;
9433         }
9434
9435         if (arity)
9436                 printf (")");
9437 }
9438
9439 void
9440 mono_print_tree_nl (MonoInst *tree)
9441 {
9442         mono_print_tree (tree);
9443         printf ("\n");
9444 }
9445
9446 static void
9447 create_helper_signature (void)
9448 {
9449         helper_sig_domain_get = mono_create_icall_signature ("ptr");
9450         helper_sig_class_init_trampoline = mono_create_icall_signature ("void");
9451         helper_sig_generic_class_init_trampoline = mono_create_icall_signature ("void");
9452         helper_sig_rgctx_lazy_fetch_trampoline = mono_create_icall_signature ("ptr ptr");
9453 }
9454
9455 gconstpointer
9456 mono_icall_get_wrapper (MonoJitICallInfo* callinfo)
9457 {
9458         char *name;
9459         MonoMethod *wrapper;
9460         gconstpointer trampoline;
9461         MonoDomain *domain = mono_get_root_domain ();
9462         
9463         if (callinfo->wrapper) {
9464                 return callinfo->wrapper;
9465         }
9466
9467         if (callinfo->trampoline)
9468                 return callinfo->trampoline;
9469
9470         /* 
9471          * We use the lock on the root domain instead of the JIT lock to protect 
9472          * callinfo->trampoline, since we do a lot of stuff inside the critical section.
9473          */
9474         mono_domain_lock (domain);
9475
9476         if (callinfo->trampoline) {
9477                 mono_domain_unlock (domain);
9478                 return callinfo->trampoline;
9479         }
9480
9481         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
9482         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
9483         g_free (name);
9484
9485         trampoline = mono_create_ftnptr (domain, mono_create_jit_trampoline_in_domain (domain, wrapper));
9486         mono_register_jit_icall_wrapper (callinfo, trampoline);
9487
9488         callinfo->trampoline = trampoline;
9489
9490         mono_domain_unlock (domain);
9491         
9492         return callinfo->trampoline;
9493 }
9494
9495 static void
9496 mono_dynamic_code_hash_insert (MonoDomain *domain, MonoMethod *method, MonoJitDynamicMethodInfo *ji)
9497 {
9498         if (!domain->dynamic_code_hash)
9499                 domain->dynamic_code_hash = g_hash_table_new (NULL, NULL);
9500         g_hash_table_insert (domain->dynamic_code_hash, method, ji);
9501 }
9502
9503 static MonoJitDynamicMethodInfo*
9504 mono_dynamic_code_hash_lookup (MonoDomain *domain, MonoMethod *method)
9505 {
9506         MonoJitDynamicMethodInfo *res;
9507
9508         if (domain->dynamic_code_hash)
9509                 res = g_hash_table_lookup (domain->dynamic_code_hash, method);
9510         else
9511                 res = NULL;
9512         return res;
9513 }
9514
9515 typedef struct {
9516         MonoClass *vtype;
9517         GList *active;
9518         GSList *slots;
9519 } StackSlotInfo;
9520
9521 static inline GSList*
9522 g_slist_prepend_mempool (MonoMemPool *mp, GSList   *list,
9523                                                  gpointer  data)
9524 {
9525   GSList *new_list;
9526
9527   new_list = mono_mempool_alloc (mp, sizeof (GSList));
9528   new_list->data = data;
9529   new_list->next = list;
9530
9531   return new_list;
9532 }
9533
9534 /*
9535  *  mono_allocate_stack_slots_full:
9536  *
9537  *  Allocate stack slots for all non register allocated variables using a
9538  * linear scan algorithm.
9539  * Returns: an array of stack offsets.
9540  * STACK_SIZE is set to the amount of stack space needed.
9541  * STACK_ALIGN is set to the alignment needed by the locals area.
9542  */
9543 gint32*
9544 mono_allocate_stack_slots_full (MonoCompile *m, gboolean backward, guint32 *stack_size, guint32 *stack_align)
9545 {
9546         int i, slot, offset, size;
9547         guint32 align;
9548         MonoMethodVar *vmv;
9549         MonoInst *inst;
9550         gint32 *offsets;
9551         GList *vars = NULL, *l;
9552         StackSlotInfo *scalar_stack_slots, *vtype_stack_slots, *slot_info;
9553         MonoType *t;
9554         int nvtypes;
9555
9556         scalar_stack_slots = mono_mempool_alloc0 (m->mempool, sizeof (StackSlotInfo) * MONO_TYPE_PINNED);
9557         vtype_stack_slots = NULL;
9558         nvtypes = 0;
9559
9560         offsets = mono_mempool_alloc (m->mempool, sizeof (gint32) * m->num_varinfo);
9561         for (i = 0; i < m->num_varinfo; ++i)
9562                 offsets [i] = -1;
9563
9564         for (i = m->locals_start; i < m->num_varinfo; i++) {
9565                 inst = m->varinfo [i];
9566                 vmv = MONO_VARINFO (m, i);
9567
9568                 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR || inst->opcode == OP_REGOFFSET)
9569                         continue;
9570
9571                 vars = g_list_prepend (vars, vmv);
9572         }
9573
9574         vars = mono_varlist_sort (m, vars, 0);
9575         offset = 0;
9576         *stack_align = 0;
9577         for (l = vars; l; l = l->next) {
9578                 vmv = l->data;
9579                 inst = m->varinfo [vmv->idx];
9580
9581                 /* inst->backend.is_pinvoke indicates native sized value types, this is used by the
9582                 * pinvoke wrappers when they call functions returning structures */
9583                 if (inst->backend.is_pinvoke && MONO_TYPE_ISSTRUCT (inst->inst_vtype) && inst->inst_vtype->type != MONO_TYPE_TYPEDBYREF)
9584                         size = mono_class_native_size (inst->inst_vtype->data.klass, &align);
9585                 else {
9586                         int ialign;
9587
9588                         size = mono_type_size (inst->inst_vtype, &ialign);
9589                         align = ialign;
9590                 }
9591
9592                 t = mono_type_get_underlying_type (inst->inst_vtype);
9593                 if (t->byref) {
9594                         slot_info = &scalar_stack_slots [MONO_TYPE_I];
9595                 } else {
9596                         switch (t->type) {
9597                         case MONO_TYPE_GENERICINST:
9598                                 if (!mono_type_generic_inst_is_valuetype (t)) {
9599                                         slot_info = &scalar_stack_slots [t->type];
9600                                         break;
9601                                 }
9602                                 /* Fall through */
9603                         case MONO_TYPE_VALUETYPE:
9604                                 if (!vtype_stack_slots)
9605                                         vtype_stack_slots = mono_mempool_alloc0 (m->mempool, sizeof (StackSlotInfo) * 256);
9606                                 for (i = 0; i < nvtypes; ++i)
9607                                         if (t->data.klass == vtype_stack_slots [i].vtype)
9608                                                 break;
9609                                 if (i < nvtypes)
9610                                         slot_info = &vtype_stack_slots [i];
9611                                 else {
9612                                         g_assert (nvtypes < 256);
9613                                         vtype_stack_slots [nvtypes].vtype = t->data.klass;
9614                                         slot_info = &vtype_stack_slots [nvtypes];
9615                                         nvtypes ++;
9616                                 }
9617                                 break;
9618                         case MONO_TYPE_CLASS:
9619                         case MONO_TYPE_OBJECT:
9620                         case MONO_TYPE_ARRAY:
9621                         case MONO_TYPE_SZARRAY:
9622                         case MONO_TYPE_STRING:
9623                         case MONO_TYPE_PTR:
9624                         case MONO_TYPE_I:
9625                         case MONO_TYPE_U:
9626 #if SIZEOF_VOID_P == 4
9627                         case MONO_TYPE_I4:
9628 #else
9629                         case MONO_TYPE_I8:
9630 #endif
9631                                 /* Share non-float stack slots of the same size */
9632                                 slot_info = &scalar_stack_slots [MONO_TYPE_CLASS];
9633                                 break;
9634                         default:
9635                                 slot_info = &scalar_stack_slots [t->type];
9636                         }
9637                 }
9638
9639                 slot = 0xffffff;
9640                 if (m->comp_done & MONO_COMP_LIVENESS) {
9641                         //printf ("START  %2d %08x %08x\n",  vmv->idx, vmv->range.first_use.abs_pos, vmv->range.last_use.abs_pos);
9642                         
9643                         /* expire old intervals in active */
9644                         while (slot_info->active) {
9645                                 MonoMethodVar *amv = (MonoMethodVar *)slot_info->active->data;
9646
9647                                 if (amv->range.last_use.abs_pos > vmv->range.first_use.abs_pos)
9648                                         break;
9649
9650                                 //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);
9651
9652                                 slot_info->active = g_list_delete_link (slot_info->active, slot_info->active);
9653                                 slot_info->slots = g_slist_prepend_mempool (m->mempool, slot_info->slots, GINT_TO_POINTER (offsets [amv->idx]));
9654                         }
9655
9656                         /* 
9657                          * This also handles the case when the variable is used in an
9658                          * exception region, as liveness info is not computed there.
9659                          */
9660                         /* 
9661                          * FIXME: All valuetypes are marked as INDIRECT because of LDADDR
9662                          * opcodes.
9663                          */
9664                         if (! (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
9665                                 if (slot_info->slots) {
9666                                         slot = GPOINTER_TO_INT (slot_info->slots->data);
9667
9668                                         slot_info->slots = slot_info->slots->next;
9669                                 }
9670
9671                                 slot_info->active = mono_varlist_insert_sorted (m, slot_info->active, vmv, TRUE);
9672                         }
9673                 }
9674
9675                 {
9676                         static int count = 0;
9677                         count ++;
9678
9679                         /*
9680                         if (count == atoi (getenv ("COUNT")))
9681                                 printf ("LAST: %s\n", mono_method_full_name (m->method, TRUE));
9682                         if (count > atoi (getenv ("COUNT")))
9683                                 slot = 0xffffff;
9684                         else {
9685                                 mono_print_tree_nl (inst);
9686                                 }
9687                         */
9688                 }
9689                 if (slot == 0xffffff) {
9690                         /*
9691                          * Allways allocate valuetypes to sizeof (gpointer) to allow more
9692                          * efficient copying (and to work around the fact that OP_MEMCPY
9693                          * and OP_MEMSET ignores alignment).
9694                          */
9695                         if (MONO_TYPE_ISSTRUCT (t))
9696                                 align = sizeof (gpointer);
9697
9698                         if (backward) {
9699                                 offset += size;
9700                                 offset += align - 1;
9701                                 offset &= ~(align - 1);
9702                                 slot = offset;
9703                         }
9704                         else {
9705                                 offset += align - 1;
9706                                 offset &= ~(align - 1);
9707                                 slot = offset;
9708                                 offset += size;
9709                         }
9710
9711                         if (*stack_align == 0)
9712                                 *stack_align = align;
9713                 }
9714
9715                 offsets [vmv->idx] = slot;
9716         }
9717         g_list_free (vars);
9718         for (i = 0; i < MONO_TYPE_PINNED; ++i) {
9719                 if (scalar_stack_slots [i].active)
9720                         g_list_free (scalar_stack_slots [i].active);
9721         }
9722         for (i = 0; i < nvtypes; ++i) {
9723                 if (vtype_stack_slots [i].active)
9724                         g_list_free (vtype_stack_slots [i].active);
9725         }
9726
9727         mono_jit_stats.locals_stack_size += offset;
9728
9729         *stack_size = offset;
9730         return offsets;
9731 }
9732
9733 gint32*
9734 mono_allocate_stack_slots (MonoCompile *m, guint32 *stack_size, guint32 *stack_align)
9735 {
9736         return mono_allocate_stack_slots_full (m, TRUE, stack_size, stack_align);
9737 }
9738
9739 void
9740 mono_register_opcode_emulation (int opcode, const char *name, const char *sigstr, gpointer func, gboolean no_throw)
9741 {
9742         MonoJitICallInfo *info;
9743         MonoMethodSignature *sig = mono_create_icall_signature (sigstr);
9744
9745         if (!emul_opcode_map)
9746                 emul_opcode_map = g_new0 (MonoJitICallInfo*, OP_LAST + 1);
9747
9748         g_assert (!sig->hasthis);
9749         g_assert (sig->param_count < 3);
9750
9751         info = mono_register_jit_icall (func, name, sig, no_throw);
9752
9753         emul_opcode_map [opcode] = info;
9754 }
9755
9756 static void
9757 register_icall (gpointer func, const char *name, const char *sigstr, gboolean save)
9758 {
9759         MonoMethodSignature *sig;
9760
9761         if (sigstr)
9762                 sig = mono_create_icall_signature (sigstr);
9763         else
9764                 sig = NULL;
9765
9766         mono_register_jit_icall (func, name, sig, save);
9767 }
9768
9769 static void
9770 decompose_foreach (MonoInst *tree, gpointer data) 
9771 {
9772         static MonoJitICallInfo *newarr_info = NULL;
9773         static MonoJitICallInfo *newarr_specific_info = NULL;
9774         MonoJitICallInfo *info;
9775         int i;
9776
9777         switch (tree->opcode) {
9778         case CEE_NEWARR: {
9779                 MonoCompile *cfg = data;
9780                 MonoInst *iargs [3];
9781
9782                 if (!newarr_info) {
9783                         newarr_info = mono_find_jit_icall_by_addr (mono_array_new);
9784                         g_assert (newarr_info);
9785                         newarr_specific_info = mono_find_jit_icall_by_addr (mono_array_new_specific);
9786                         g_assert (newarr_specific_info);
9787                 }
9788
9789                 if (cfg->opt & MONO_OPT_SHARED) {
9790                         NEW_DOMAINCONST (cfg, iargs [0]);
9791                         NEW_CLASSCONST (cfg, iargs [1], tree->inst_newa_class);
9792                         iargs [2] = tree->inst_newa_len;
9793
9794                         info = newarr_info;
9795                 }
9796                 else {
9797                         MonoVTable *vtable = mono_class_vtable (cfg->domain, mono_array_class_get (tree->inst_newa_class, 1));
9798
9799                         NEW_VTABLECONST (cfg, iargs [0], vtable);
9800                         iargs [1] = tree->inst_newa_len;
9801
9802                         info = newarr_specific_info;
9803                 }
9804
9805                 mono_emulate_opcode (cfg, tree, iargs, info);
9806
9807                 /* Need to decompose arguments after the the opcode is decomposed */
9808                 for (i = 0; i < info->sig->param_count; ++i)
9809                         dec_foreach (iargs [i], cfg);
9810                 break;
9811         }
9812 #ifdef MONO_ARCH_SOFT_FLOAT
9813         case OP_FBEQ:
9814         case OP_FBGE:
9815         case OP_FBGT:
9816         case OP_FBLE:
9817         case OP_FBLT:
9818         case OP_FBNE_UN:
9819         case OP_FBGE_UN:
9820         case OP_FBGT_UN:
9821         case OP_FBLE_UN:
9822         case OP_FBLT_UN: {
9823                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
9824                         MonoCompile *cfg = data;
9825                         MonoInst *iargs [2];
9826                 
9827                         iargs [0] = tree->inst_i0;
9828                         iargs [1] = tree->inst_i1;
9829                 
9830                         mono_emulate_opcode (cfg, tree, iargs, info);
9831
9832                         dec_foreach (iargs [0], cfg);
9833                         dec_foreach (iargs [1], cfg);
9834                         break;
9835                 } else {
9836                         g_assert_not_reached ();
9837                 }
9838                 break;
9839         }
9840         case OP_FCEQ:
9841         case OP_FCGT:
9842         case OP_FCGT_UN:
9843         case OP_FCLT:
9844         case OP_FCLT_UN: {
9845                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
9846                         MonoCompile *cfg = data;
9847                         MonoInst *iargs [2];
9848
9849                         /* the args are in the compare opcode ... */
9850                         iargs [0] = tree->inst_i0;
9851                         iargs [1] = tree->inst_i1;
9852                 
9853                         mono_emulate_opcode (cfg, tree, iargs, info);
9854
9855                         dec_foreach (iargs [0], cfg);
9856                         dec_foreach (iargs [1], cfg);
9857                         break;
9858                 } else {
9859                         g_assert_not_reached ();
9860                 }
9861                 break;
9862         }
9863 #endif
9864
9865         default:
9866                 break;
9867         }
9868 }
9869
9870 void
9871 mono_inst_foreach (MonoInst *tree, MonoInstFunc func, gpointer data) {
9872
9873         switch (mono_burg_arity [tree->opcode]) {
9874         case 0: break;
9875         case 1: 
9876                 mono_inst_foreach (tree->inst_left, func, data);
9877                 break;
9878         case 2: 
9879                 mono_inst_foreach (tree->inst_left, func, data);
9880                 mono_inst_foreach (tree->inst_right, func, data);
9881                 break;
9882         default:
9883                 g_assert_not_reached ();
9884         }
9885         func (tree, data);
9886 }
9887
9888 G_GNUC_UNUSED
9889 static void
9890 mono_print_bb_code (MonoBasicBlock *bb)
9891 {
9892         MonoInst *c;
9893
9894         MONO_BB_FOR_EACH_INS (bb, c) {
9895                 mono_print_tree (c);
9896                 g_print ("\n");
9897         }
9898 }
9899
9900 static void
9901 print_dfn (MonoCompile *cfg) {
9902         int i, j;
9903         char *code;
9904         MonoBasicBlock *bb;
9905
9906         g_print ("IR code for method %s\n", mono_method_full_name (cfg->method, TRUE));
9907
9908         for (i = 0; i < cfg->num_bblocks; ++i) {
9909                 MonoInst *c;
9910
9911                 bb = cfg->bblocks [i];
9912                 /*if (bb->cil_code) {
9913                         char* code1, *code2;
9914                         code1 = mono_disasm_code_one (NULL, cfg->method, bb->cil_code, NULL);
9915                         if (bb->last_ins->cil_code)
9916                                 code2 = mono_disasm_code_one (NULL, cfg->method, bb->last_ins->cil_code, NULL);
9917                         else
9918                                 code2 = g_strdup ("");
9919
9920                         code1 [strlen (code1) - 1] = 0;
9921                         code = g_strdup_printf ("%s -> %s", code1, code2);
9922                         g_free (code1);
9923                         g_free (code2);
9924                 } else*/
9925                         code = g_strdup ("\n");
9926                 g_print ("\nBB%d DFN%d (len: %d): %s", bb->block_num, i, bb->cil_length, code);
9927                 MONO_BB_FOR_EACH_INS (bb, c) {
9928                         mono_print_tree (c);
9929                         g_print ("\n");
9930                 }
9931
9932                 g_print ("\tprev:");
9933                 for (j = 0; j < bb->in_count; ++j) {
9934                         g_print (" BB%d", bb->in_bb [j]->block_num);
9935                 }
9936                 g_print ("\t\tsucc:");
9937                 for (j = 0; j < bb->out_count; ++j) {
9938                         g_print (" BB%d", bb->out_bb [j]->block_num);
9939                 }
9940                 g_print ("\n\tidom: BB%d\n", bb->idom? bb->idom->block_num: -1);
9941
9942                 if (bb->idom)
9943                         g_assert (mono_bitset_test_fast (bb->dominators, bb->idom->dfn));
9944
9945                 if (bb->dominators)
9946                         mono_blockset_print (cfg, bb->dominators, "\tdominators", bb->idom? bb->idom->dfn: -1);
9947                 if (bb->dfrontier)
9948                         mono_blockset_print (cfg, bb->dfrontier, "\tdfrontier", -1);
9949                 g_free (code);
9950         }
9951
9952         g_print ("\n");
9953 }
9954
9955 void
9956 mono_bblock_add_inst (MonoBasicBlock *bb, MonoInst *inst)
9957 {
9958         MONO_INST_LIST_ADD_TAIL (&inst->node, &bb->ins_list);
9959 }
9960
9961 void
9962 mono_destroy_compile (MonoCompile *cfg)
9963 {
9964         //mono_mempool_stats (cfg->mempool);
9965         mono_free_loop_info (cfg);
9966         if (cfg->rs)
9967                 mono_regstate_free (cfg->rs);
9968         if (cfg->spvars)
9969                 g_hash_table_destroy (cfg->spvars);
9970         if (cfg->exvars)
9971                 g_hash_table_destroy (cfg->exvars);
9972         mono_mempool_destroy (cfg->mempool);
9973         g_list_free (cfg->ldstr_list);
9974         g_hash_table_destroy (cfg->token_info_hash);
9975
9976         g_free (cfg->varinfo);
9977         g_free (cfg->vars);
9978         g_free (cfg->exception_message);
9979         g_free (cfg);
9980 }
9981
9982 #ifdef HAVE_KW_THREAD
9983 static __thread gpointer mono_lmf_addr MONO_TLS_FAST;
9984 #ifdef MONO_ARCH_ENABLE_MONO_LMF_VAR
9985 /* 
9986  * When this is defined, the current lmf is stored in this tls variable instead of in 
9987  * jit_tls->lmf.
9988  */
9989 static __thread gpointer mono_lmf MONO_TLS_FAST;
9990 #endif
9991 #endif
9992
9993 guint32
9994 mono_get_jit_tls_key (void)
9995 {
9996         return mono_jit_tls_id;
9997 }
9998
9999 gint32
10000 mono_get_lmf_tls_offset (void)
10001 {
10002 #if defined(HAVE_KW_THREAD) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
10003         int offset;
10004         MONO_THREAD_VAR_OFFSET(mono_lmf,offset);
10005         return offset;
10006 #else
10007         return -1;
10008 #endif
10009 }
10010
10011 gint32
10012 mono_get_lmf_addr_tls_offset (void)
10013 {
10014         int offset;
10015         MONO_THREAD_VAR_OFFSET(mono_lmf_addr,offset);
10016         return offset;
10017 }
10018
10019 MonoLMF *
10020 mono_get_lmf (void)
10021 {
10022 #if defined(HAVE_KW_THREAD) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
10023         return mono_lmf;
10024 #else
10025         MonoJitTlsData *jit_tls;
10026
10027         if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
10028                 return jit_tls->lmf;
10029
10030         g_assert_not_reached ();
10031         return NULL;
10032 #endif
10033 }
10034
10035 MonoLMF **
10036 mono_get_lmf_addr (void)
10037 {
10038 #ifdef HAVE_KW_THREAD
10039         return mono_lmf_addr;
10040 #else
10041         MonoJitTlsData *jit_tls;
10042
10043         if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
10044                 return &jit_tls->lmf;
10045
10046         g_assert_not_reached ();
10047         return NULL;
10048 #endif
10049 }
10050
10051 /* Called by native->managed wrappers */
10052 void
10053 mono_jit_thread_attach (MonoDomain *domain)
10054 {
10055 #ifdef HAVE_KW_THREAD
10056         if (!mono_lmf_addr) {
10057                 mono_thread_attach (domain);
10058         }
10059 #else
10060         if (!TlsGetValue (mono_jit_tls_id))
10061                 mono_thread_attach (domain);
10062 #endif
10063         if (mono_domain_get () != domain)
10064                 mono_domain_set (domain, TRUE);
10065 }       
10066
10067 /**
10068  * mono_thread_abort:
10069  * @obj: exception object
10070  *
10071  * abort the thread, print exception information and stack trace
10072  */
10073 static void
10074 mono_thread_abort (MonoObject *obj)
10075 {
10076         /* MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id); */
10077         
10078         /* handle_remove should be eventually called for this thread, too
10079         g_free (jit_tls);*/
10080
10081         if ((mono_runtime_unhandled_exception_policy_get () == MONO_UNHANLED_POLICY_LEGACY) ||
10082                         (obj->vtable->klass == mono_defaults.threadabortexception_class)) {
10083                 mono_thread_exit ();
10084         } else {
10085                 exit (mono_environment_exitcode_get ());
10086         }
10087 }
10088
10089 static void*
10090 setup_jit_tls_data (gpointer stack_start, gpointer abort_func)
10091 {
10092         MonoJitTlsData *jit_tls;
10093         MonoLMF *lmf;
10094
10095         jit_tls = TlsGetValue (mono_jit_tls_id);
10096         if (jit_tls)
10097                 return jit_tls;
10098
10099         jit_tls = g_new0 (MonoJitTlsData, 1);
10100
10101         TlsSetValue (mono_jit_tls_id, jit_tls);
10102
10103         jit_tls->abort_func = abort_func;
10104         jit_tls->end_of_stack = stack_start;
10105
10106         lmf = g_new0 (MonoLMF, 1);
10107 #ifdef MONO_ARCH_INIT_TOP_LMF_ENTRY
10108         MONO_ARCH_INIT_TOP_LMF_ENTRY (lmf);
10109 #else
10110         lmf->ebp = -1;
10111 #endif
10112
10113         jit_tls->first_lmf = lmf;
10114
10115 #if defined(HAVE_KW_THREAD) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
10116         /* jit_tls->lmf is unused */
10117         mono_lmf = lmf;
10118         mono_lmf_addr = &mono_lmf;
10119 #else
10120 #if defined(HAVE_KW_THREAD)
10121         mono_lmf_addr = &jit_tls->lmf;  
10122 #endif
10123
10124         jit_tls->lmf = lmf;
10125 #endif
10126
10127         mono_arch_setup_jit_tls_data (jit_tls);
10128         mono_setup_altstack (jit_tls);
10129
10130         return jit_tls;
10131 }
10132
10133 static void
10134 mono_thread_start_cb (gsize tid, gpointer stack_start, gpointer func)
10135 {
10136         MonoThread *thread;
10137         void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort);
10138         thread = mono_thread_current ();
10139         mono_debugger_thread_created (tid, thread, jit_tls);
10140         if (thread)
10141                 thread->jit_data = jit_tls;
10142 }
10143
10144 void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
10145
10146 static void
10147 mono_thread_abort_dummy (MonoObject *obj)
10148 {
10149   if (mono_thread_attach_aborted_cb)
10150     mono_thread_attach_aborted_cb (obj);
10151   else
10152     mono_thread_abort (obj);
10153 }
10154
10155 static void
10156 mono_thread_attach_cb (gsize tid, gpointer stack_start)
10157 {
10158         MonoThread *thread;
10159         void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort_dummy);
10160         thread = mono_thread_current ();
10161         mono_debugger_thread_created (tid, thread, (MonoJitTlsData *) jit_tls);
10162         if (thread)
10163                 thread->jit_data = jit_tls;
10164         if (mono_profiler_get_events () & MONO_PROFILE_STATISTICAL)
10165                 setup_stat_profiler ();
10166 }
10167
10168 static void
10169 mini_thread_cleanup (MonoThread *thread)
10170 {
10171         MonoJitTlsData *jit_tls = thread->jit_data;
10172
10173         if (jit_tls) {
10174                 mono_debugger_thread_cleanup (jit_tls);
10175                 mono_arch_free_jit_tls_data (jit_tls);
10176
10177                 mono_free_altstack (jit_tls);
10178                 g_free (jit_tls->first_lmf);
10179                 g_free (jit_tls);
10180                 thread->jit_data = NULL;
10181                 TlsSetValue (mono_jit_tls_id, NULL);
10182         }
10183 }
10184
10185 void
10186 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
10187 {
10188         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
10189
10190         ji->ip.i = ip;
10191         ji->type = type;
10192         ji->data.target = target;
10193         ji->next = cfg->patch_info;
10194
10195         cfg->patch_info = ji;
10196 }
10197
10198 void
10199 mono_remove_patch_info (MonoCompile *cfg, int ip)
10200 {
10201         MonoJumpInfo **ji = &cfg->patch_info;
10202
10203         while (*ji) {
10204                 if ((*ji)->ip.i == ip)
10205                         *ji = (*ji)->next;
10206                 else
10207                         ji = &((*ji)->next);
10208         }
10209 }
10210
10211 /**
10212  * mono_patch_info_dup_mp:
10213  *
10214  * Make a copy of PATCH_INFO, allocating memory from the mempool MP.
10215  */
10216 MonoJumpInfo*
10217 mono_patch_info_dup_mp (MonoMemPool *mp, MonoJumpInfo *patch_info)
10218 {
10219         MonoJumpInfo *res = mono_mempool_alloc (mp, sizeof (MonoJumpInfo));
10220         memcpy (res, patch_info, sizeof (MonoJumpInfo));
10221
10222         switch (patch_info->type) {
10223         case MONO_PATCH_INFO_RVA:
10224         case MONO_PATCH_INFO_LDSTR:
10225         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
10226         case MONO_PATCH_INFO_LDTOKEN:
10227         case MONO_PATCH_INFO_DECLSEC:
10228                 res->data.token = mono_mempool_alloc (mp, sizeof (MonoJumpInfoToken));
10229                 memcpy (res->data.token, patch_info->data.token, sizeof (MonoJumpInfoToken));
10230                 break;
10231         case MONO_PATCH_INFO_SWITCH:
10232                 res->data.table = mono_mempool_alloc (mp, sizeof (MonoJumpInfoBBTable));
10233                 memcpy (res->data.table, patch_info->data.table, sizeof (MonoJumpInfoBBTable));
10234                 break;
10235         default:
10236                 break;
10237         }
10238
10239         return res;
10240 }
10241
10242 guint
10243 mono_patch_info_hash (gconstpointer data)
10244 {
10245         const MonoJumpInfo *ji = (MonoJumpInfo*)data;
10246
10247         switch (ji->type) {
10248         case MONO_PATCH_INFO_RVA:
10249         case MONO_PATCH_INFO_LDSTR:
10250         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
10251         case MONO_PATCH_INFO_LDTOKEN:
10252         case MONO_PATCH_INFO_DECLSEC:
10253                 return (ji->type << 8) | ji->data.token->token;
10254         case MONO_PATCH_INFO_VTABLE:
10255         case MONO_PATCH_INFO_CLASS:
10256         case MONO_PATCH_INFO_IID:
10257         case MONO_PATCH_INFO_ADJUSTED_IID:
10258                 return (ji->type << 8) | (gssize)ji->data.klass;
10259         case MONO_PATCH_INFO_FIELD:
10260         case MONO_PATCH_INFO_SFLDA:
10261                 return (ji->type << 8) | (gssize)ji->data.field;
10262         case MONO_PATCH_INFO_METHODCONST:
10263         case MONO_PATCH_INFO_METHOD:
10264         case MONO_PATCH_INFO_METHOD_JUMP:
10265                 return (ji->type << 8) | (gssize)ji->data.method;
10266         case MONO_PATCH_INFO_IMAGE:
10267                 return (ji->type << 8) | (gssize)ji->data.image;                
10268         default:
10269                 return (ji->type << 8);
10270         }
10271 }
10272
10273 /* 
10274  * mono_patch_info_equal:
10275  * 
10276  * This might fail to recognize equivalent patches, i.e. floats, so its only
10277  * usable in those cases where this is not a problem, i.e. sharing GOT slots
10278  * in AOT.
10279  */
10280 gint
10281 mono_patch_info_equal (gconstpointer ka, gconstpointer kb)
10282 {
10283         const MonoJumpInfo *ji1 = (MonoJumpInfo*)ka;
10284         const MonoJumpInfo *ji2 = (MonoJumpInfo*)kb;
10285
10286         if (ji1->type != ji2->type)
10287                 return 0;
10288
10289         switch (ji1->type) {
10290         case MONO_PATCH_INFO_RVA:
10291         case MONO_PATCH_INFO_LDSTR:
10292         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
10293         case MONO_PATCH_INFO_LDTOKEN:
10294         case MONO_PATCH_INFO_DECLSEC:
10295                 if ((ji1->data.token->image != ji2->data.token->image) ||
10296                         (ji1->data.token->token != ji2->data.token->token))
10297                         return 0;
10298                 break;
10299         default:
10300                 if (ji1->data.name != ji2->data.name)
10301                         return 0;
10302                 break;
10303         }
10304
10305         return 1;
10306 }
10307
10308 gpointer
10309 mono_resolve_patch_target (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors)
10310 {
10311         unsigned char *ip = patch_info->ip.i + code;
10312         gconstpointer target = NULL;
10313
10314         switch (patch_info->type) {
10315         case MONO_PATCH_INFO_BB:
10316                 target = patch_info->data.bb->native_offset + code;
10317                 break;
10318         case MONO_PATCH_INFO_ABS:
10319                 target = patch_info->data.target;
10320                 break;
10321         case MONO_PATCH_INFO_LABEL:
10322                 target = patch_info->data.inst->inst_c0 + code;
10323                 break;
10324         case MONO_PATCH_INFO_IP:
10325                 target = ip;
10326                 break;
10327         case MONO_PATCH_INFO_METHOD_REL:
10328                 target = code + patch_info->data.offset;
10329                 break;
10330         case MONO_PATCH_INFO_INTERNAL_METHOD: {
10331                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
10332                 if (!mi) {
10333                         g_warning ("unknown MONO_PATCH_INFO_INTERNAL_METHOD %s", patch_info->data.name);
10334                         g_assert_not_reached ();
10335                 }
10336                 target = mono_icall_get_wrapper (mi);
10337                 break;
10338         }
10339         case MONO_PATCH_INFO_METHOD_JUMP: {
10340                 GSList *list;
10341
10342                 /* get the trampoline to the method from the domain */
10343                 target = mono_create_jump_trampoline (domain, patch_info->data.method, TRUE);
10344                 if (!domain->jump_target_hash)
10345                         domain->jump_target_hash = g_hash_table_new (NULL, NULL);
10346                 list = g_hash_table_lookup (domain->jump_target_hash, patch_info->data.method);
10347                 list = g_slist_prepend (list, ip);
10348                 g_hash_table_insert (domain->jump_target_hash, patch_info->data.method, list);
10349                 break;
10350         }
10351         case MONO_PATCH_INFO_METHOD:
10352                 if (patch_info->data.method == method) {
10353                         target = code;
10354                 } else {
10355                         /* get the trampoline to the method from the domain */
10356                         if (method->wrapper_type == MONO_WRAPPER_STATIC_RGCTX_INVOKE)
10357                                 target = mono_ldftn_nosync (patch_info->data.method);
10358                         else
10359                                 target = mono_create_jit_trampoline (patch_info->data.method);
10360                 }
10361                 break;
10362         case MONO_PATCH_INFO_SWITCH: {
10363                 gpointer *jump_table;
10364                 int i;
10365
10366                 if (method && method->dynamic) {
10367                         jump_table = mono_code_manager_reserve (mono_dynamic_code_hash_lookup (domain, method)->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
10368                 } else {
10369                         mono_domain_lock (domain);
10370                         jump_table = mono_code_manager_reserve (domain->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
10371                         mono_domain_unlock (domain);
10372                 }
10373
10374                 for (i = 0; i < patch_info->data.table->table_size; i++) {
10375                         jump_table [i] = code + GPOINTER_TO_INT (patch_info->data.table->table [i]);
10376                 }
10377                 target = jump_table;
10378                 break;
10379         }
10380         case MONO_PATCH_INFO_METHODCONST:
10381         case MONO_PATCH_INFO_CLASS:
10382         case MONO_PATCH_INFO_IMAGE:
10383         case MONO_PATCH_INFO_FIELD:
10384                 target = patch_info->data.target;
10385                 break;
10386         case MONO_PATCH_INFO_IID:
10387                 mono_class_init (patch_info->data.klass);
10388                 target = GINT_TO_POINTER ((int)patch_info->data.klass->interface_id);
10389                 break;
10390         case MONO_PATCH_INFO_ADJUSTED_IID:
10391                 mono_class_init (patch_info->data.klass);
10392                 target = GINT_TO_POINTER ((int)(-((patch_info->data.klass->interface_id + 1) * SIZEOF_VOID_P)));
10393                 break;
10394         case MONO_PATCH_INFO_VTABLE:
10395                 target = mono_class_vtable (domain, patch_info->data.klass);
10396                 break;
10397         case MONO_PATCH_INFO_CLASS_INIT:
10398                 target = mono_create_class_init_trampoline (mono_class_vtable (domain, patch_info->data.klass));
10399                 break;
10400         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
10401                 target = mono_create_delegate_trampoline (patch_info->data.klass);
10402                 break;
10403         case MONO_PATCH_INFO_SFLDA: {
10404                 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.field->parent);
10405                 if (!vtable->initialized && !(vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) && (method && mono_class_needs_cctor_run (vtable->klass, method)))
10406                         /* Done by the generated code */
10407                         ;
10408                 else {
10409                         if (run_cctors)
10410                                 mono_runtime_class_init (vtable);
10411                 }
10412                 target = (char*)vtable->data + patch_info->data.field->offset;
10413                 break;
10414         }
10415         case MONO_PATCH_INFO_RVA:
10416                 target = mono_image_rva_map (patch_info->data.token->image, patch_info->data.token->token);
10417                 break;
10418         case MONO_PATCH_INFO_R4:
10419         case MONO_PATCH_INFO_R8:
10420                 target = patch_info->data.target;
10421                 break;
10422         case MONO_PATCH_INFO_EXC_NAME:
10423                 target = patch_info->data.name;
10424                 break;
10425         case MONO_PATCH_INFO_LDSTR:
10426                 target =
10427                         mono_ldstr (domain, patch_info->data.token->image, 
10428                                                 mono_metadata_token_index (patch_info->data.token->token));
10429                 break;
10430         case MONO_PATCH_INFO_TYPE_FROM_HANDLE: {
10431                 gpointer handle;
10432                 MonoClass *handle_class;
10433
10434                 handle = mono_ldtoken (patch_info->data.token->image, 
10435                                        patch_info->data.token->token, &handle_class, NULL);
10436                 mono_class_init (handle_class);
10437                 mono_class_init (mono_class_from_mono_type (handle));
10438
10439                 target =
10440                         mono_type_get_object (domain, handle);
10441                 break;
10442         }
10443         case MONO_PATCH_INFO_LDTOKEN: {
10444                 gpointer handle;
10445                 MonoClass *handle_class;
10446                 
10447                 handle = mono_ldtoken (patch_info->data.token->image,
10448                                        patch_info->data.token->token, &handle_class, NULL);
10449                 mono_class_init (handle_class);
10450                 
10451                 target = handle;
10452                 break;
10453         }
10454         case MONO_PATCH_INFO_DECLSEC:
10455                 target = (mono_metadata_blob_heap (patch_info->data.token->image, patch_info->data.token->token) + 2);
10456                 break;
10457         case MONO_PATCH_INFO_ICALL_ADDR:
10458                 target = mono_lookup_internal_call (patch_info->data.method);
10459                 break;
10460         case MONO_PATCH_INFO_BB_OVF:
10461         case MONO_PATCH_INFO_EXC_OVF:
10462         case MONO_PATCH_INFO_GOT_OFFSET:
10463         case MONO_PATCH_INFO_NONE:
10464                 break;
10465         default:
10466                 g_assert_not_reached ();
10467         }
10468
10469         return (gpointer)target;
10470 }
10471
10472 static void
10473 dec_foreach (MonoInst *tree, MonoCompile *cfg) {
10474         MonoJitICallInfo *info;
10475
10476         decompose_foreach (tree, cfg);
10477
10478         switch (mono_burg_arity [tree->opcode]) {
10479         case 0: break;
10480         case 1: 
10481                 dec_foreach (tree->inst_left, cfg);
10482
10483                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
10484                         MonoInst *iargs [2];
10485                 
10486                         iargs [0] = tree->inst_left;
10487
10488                         mono_emulate_opcode (cfg, tree, iargs, info);
10489                         return;
10490                 }
10491
10492                 break;
10493         case 2:
10494 #ifdef MONO_ARCH_BIGMUL_INTRINS
10495                 if (tree->opcode == OP_LMUL
10496                                 && (cfg->opt & MONO_OPT_INTRINS)
10497                                 && (tree->inst_left->opcode == CEE_CONV_I8 
10498                                         || tree->inst_left->opcode == CEE_CONV_U8)
10499                                 && tree->inst_left->inst_left->type == STACK_I4
10500                                 && (tree->inst_right->opcode == CEE_CONV_I8 
10501                                         || tree->inst_right->opcode == CEE_CONV_U8)
10502                                 && tree->inst_right->inst_left->type == STACK_I4
10503                                 && tree->inst_left->opcode == tree->inst_right->opcode) {
10504                         tree->opcode = (tree->inst_left->opcode == CEE_CONV_I8 ? OP_BIGMUL: OP_BIGMUL_UN);
10505                         tree->inst_left = tree->inst_left->inst_left;
10506                         tree->inst_right = tree->inst_right->inst_left;
10507                         dec_foreach (tree, cfg);
10508                 } else 
10509 #endif
10510                         if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
10511                         MonoInst *iargs [2];
10512                 
10513                         iargs [0] = tree->inst_i0;
10514                         iargs [1] = tree->inst_i1;
10515                 
10516                         mono_emulate_opcode (cfg, tree, iargs, info);
10517
10518                         dec_foreach (iargs [0], cfg);
10519                         dec_foreach (iargs [1], cfg);
10520                         return;
10521                 } else {
10522                         dec_foreach (tree->inst_left, cfg);
10523                         dec_foreach (tree->inst_right, cfg);
10524                 }
10525                 break;
10526         default:
10527                 g_assert_not_reached ();
10528         }
10529 }
10530
10531 static void
10532 decompose_pass (MonoCompile *cfg) {
10533         MonoBasicBlock *bb;
10534
10535         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
10536                 MonoInst *tree;
10537                 cfg->cbb = bb;
10538                 cfg->prev_ins = NULL;
10539                 MONO_BB_FOR_EACH_INS (cfg->cbb, tree) {
10540                         dec_foreach (tree, cfg);
10541                         cfg->prev_ins = tree;
10542                 }
10543         }
10544 }
10545
10546 static void
10547 nullify_basic_block (MonoBasicBlock *bb) 
10548 {
10549         bb->in_count = 0;
10550         bb->out_count = 0;
10551         bb->in_bb = NULL;
10552         bb->out_bb = NULL;
10553         bb->next_bb = NULL;
10554         MONO_INST_LIST_INIT (&bb->ins_list);
10555         bb->cil_code = NULL;
10556 }
10557
10558 static void 
10559 replace_out_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
10560 {
10561         int i;
10562
10563         for (i = 0; i < bb->out_count; i++) {
10564                 MonoBasicBlock *ob = bb->out_bb [i];
10565                 if (ob == orig) {
10566                         if (!repl) {
10567                                 if (bb->out_count > 1) {
10568                                         bb->out_bb [i] = bb->out_bb [bb->out_count - 1];
10569                                 }
10570                                 bb->out_count--;
10571                         } else {
10572                                 bb->out_bb [i] = repl;
10573                         }
10574                 }
10575         }
10576 }
10577
10578 static void 
10579 replace_in_block (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl)
10580 {
10581         int i;
10582
10583         for (i = 0; i < bb->in_count; i++) {
10584                 MonoBasicBlock *ib = bb->in_bb [i];
10585                 if (ib == orig) {
10586                         if (!repl) {
10587                                 if (bb->in_count > 1) {
10588                                         bb->in_bb [i] = bb->in_bb [bb->in_count - 1];
10589                                 }
10590                                 bb->in_count--;
10591                         } else {
10592                                 bb->in_bb [i] = repl;
10593                         }
10594                 }
10595         }
10596 }
10597
10598 static void
10599 replace_out_block_in_code (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl) {
10600         MonoInst *inst;
10601         
10602         MONO_BB_FOR_EACH_INS (bb, inst) {
10603                 if (inst->opcode == OP_CALL_HANDLER) {
10604                         if (inst->inst_target_bb == orig)
10605                                 inst->inst_target_bb = repl;
10606                 }
10607         }
10608
10609         inst = mono_inst_list_last (&bb->ins_list);
10610         if (!inst)
10611                 return;
10612
10613         switch (inst->opcode) {
10614         case OP_BR:
10615                 if (inst->inst_target_bb == orig)
10616                         inst->inst_target_bb = repl;
10617                 break;
10618         case OP_SWITCH: {
10619                 int i;
10620                 int n = GPOINTER_TO_INT (inst->klass);
10621                 for (i = 0; i < n; i++ ) {
10622                         if (inst->inst_many_bb [i] == orig)
10623                                 inst->inst_many_bb [i] = repl;
10624                 }
10625                 break;
10626         }
10627         case CEE_BNE_UN:
10628         case CEE_BEQ:
10629         case CEE_BLT:
10630         case CEE_BLT_UN:
10631         case CEE_BGT:
10632         case CEE_BGT_UN:
10633         case CEE_BGE:
10634         case CEE_BGE_UN:
10635         case CEE_BLE:
10636         case CEE_BLE_UN:
10637                 if (inst->inst_true_bb == orig)
10638                         inst->inst_true_bb = repl;
10639                 if (inst->inst_false_bb == orig)
10640                         inst->inst_false_bb = repl;
10641                 break;
10642         default:
10643                 break;
10644         }
10645 }
10646
10647 static void 
10648 replace_basic_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
10649 {
10650         int i, j;
10651
10652         for (i = 0; i < bb->out_count; i++) {
10653                 MonoBasicBlock *ob = bb->out_bb [i];
10654                 for (j = 0; j < ob->in_count; j++) {
10655                         if (ob->in_bb [j] == orig) {
10656                                 ob->in_bb [j] = repl;
10657                         }
10658                 }
10659         }
10660
10661 }
10662
10663 /**
10664   * Check if a bb is useless (is just made of NOPs and ends with an
10665   * unconditional branch, or nothing).
10666   * If it is so, unlink it from the CFG and nullify it, and return TRUE.
10667   * Otherwise, return FALSE;
10668   */
10669 static gboolean
10670 remove_block_if_useless (MonoCompile *cfg, MonoBasicBlock *bb, MonoBasicBlock *previous_bb) {
10671         MonoBasicBlock *target_bb = NULL;
10672         MonoInst *inst;
10673         
10674         /* Do not touch handlers */
10675         if (bb->region != -1) {
10676                 bb->not_useless = TRUE;
10677                 return FALSE;
10678         }
10679         
10680         MONO_BB_FOR_EACH_INS (bb, inst) {
10681                 switch (inst->opcode) {
10682                 case OP_NOP:
10683                         break;
10684                 case OP_BR:
10685                         target_bb = inst->inst_target_bb;
10686                         break;
10687                 default:
10688                         bb->not_useless = TRUE;
10689                         return FALSE;
10690                 }
10691         }
10692         
10693         if (target_bb == NULL) {
10694                 if ((bb->out_count == 1) && (bb->out_bb [0] == bb->next_bb)) {
10695                         target_bb = bb->next_bb;
10696                 } else {
10697                         /* Do not touch empty BBs that do not "fall through" to their next BB (like the exit BB) */
10698                         return FALSE;
10699                 }
10700         }
10701         
10702         /* Do not touch BBs following a switch (they are the "default" branch) */
10703         inst = mono_inst_list_last (&previous_bb->ins_list);
10704         if (inst && inst->opcode == OP_SWITCH)
10705                 return FALSE;
10706         
10707         /* Do not touch BBs following the entry BB and jumping to something that is not */
10708         /* thiry "next" bb (the entry BB cannot contain the branch) */
10709         if ((previous_bb == cfg->bb_entry) && (bb->next_bb != target_bb)) {
10710                 return FALSE;
10711         }
10712
10713         /* 
10714          * Do not touch BBs following a try block as the code in 
10715          * mini_method_compile needs them to compute the length of the try block.
10716          */
10717         if (MONO_BBLOCK_IS_IN_REGION (previous_bb, MONO_REGION_TRY))
10718                 return FALSE;
10719         
10720         /* Check that there is a target BB, and that bb is not an empty loop (Bug 75061) */
10721         if ((target_bb != NULL) && (target_bb != bb)) {
10722                 MonoInst *last_ins;
10723                 int i;
10724
10725                 if (cfg->verbose_level > 1) {
10726                         printf ("remove_block_if_useless %s, removed BB%d\n", mono_method_full_name (cfg->method, TRUE), bb->block_num);
10727                 }
10728                 
10729                 /* unlink_bblock () modifies the bb->in_bb array so can't use a for loop here */
10730                 while (bb->in_count) {
10731                         MonoBasicBlock *in_bb = bb->in_bb [0];
10732                         mono_unlink_bblock (cfg, in_bb, bb);
10733                         link_bblock (cfg, in_bb, target_bb);
10734                         replace_out_block_in_code (in_bb, bb, target_bb);
10735                 }
10736                 
10737                 mono_unlink_bblock (cfg, bb, target_bb);
10738                 
10739                 last_ins = mono_inst_list_last (&previous_bb->ins_list);
10740
10741                 if ((previous_bb != cfg->bb_entry) &&
10742                                 (previous_bb->region == bb->region) &&
10743                                 ((last_ins == NULL) ||
10744                                 ((last_ins->opcode != OP_BR) &&
10745                                 (!(MONO_IS_COND_BRANCH_OP (last_ins))) &&
10746                                 (last_ins->opcode != OP_SWITCH)))) {
10747                         for (i = 0; i < previous_bb->out_count; i++) {
10748                                 if (previous_bb->out_bb [i] == target_bb) {
10749                                         MonoInst *jump;
10750                                         MONO_INST_NEW (cfg, jump, OP_BR);
10751                                         MONO_ADD_INS (previous_bb, jump);
10752                                         jump->cil_code = previous_bb->cil_code;
10753                                         jump->inst_target_bb = target_bb;
10754                                         break;
10755                                 }
10756                         }
10757                 }
10758                 
10759                 previous_bb->next_bb = bb->next_bb;
10760                 nullify_basic_block (bb);
10761                 
10762                 return TRUE;
10763         } else {
10764                 return FALSE;
10765         }
10766 }
10767
10768 static void
10769 merge_basic_blocks (MonoBasicBlock *bb, MonoBasicBlock *bbn) 
10770 {
10771         MonoInst *last_ins;
10772
10773         bb->out_count = bbn->out_count;
10774         bb->out_bb = bbn->out_bb;
10775
10776         replace_basic_block (bb, bbn, bb);
10777
10778         last_ins = mono_inst_list_last (&bb->ins_list);
10779
10780         /* Nullify branch at the end of bb */
10781         if (last_ins && MONO_IS_BRANCH_OP (last_ins))
10782                 last_ins->opcode = OP_NOP;
10783
10784         MONO_INST_LIST_SPLICE_TAIL_INIT (&bbn->ins_list, &bb->ins_list);
10785
10786         bb->next_bb = bbn->next_bb;
10787         nullify_basic_block (bbn);
10788 }
10789
10790 static void
10791 move_basic_block_to_end (MonoCompile *cfg, MonoBasicBlock *bb)
10792 {
10793         MonoBasicBlock *bbn, *next;
10794         MonoInst *last_ins;
10795
10796         next = bb->next_bb;
10797
10798         /* Find the previous */
10799         for (bbn = cfg->bb_entry; bbn->next_bb && bbn->next_bb != bb; bbn = bbn->next_bb)
10800                 ;
10801         if (bbn->next_bb) {
10802                 bbn->next_bb = bb->next_bb;
10803         }
10804
10805         /* Find the last */
10806         for (bbn = cfg->bb_entry; bbn->next_bb; bbn = bbn->next_bb)
10807                 ;
10808         bbn->next_bb = bb;
10809         bb->next_bb = NULL;
10810
10811         last_ins = mono_inst_list_last (&bb->ins_list);
10812
10813         /* Add a branch */
10814         if (next && (!last_ins || (last_ins->opcode != OP_NOT_REACHED))) {
10815                 MonoInst *ins;
10816
10817                 MONO_INST_NEW (cfg, ins, OP_BR);
10818                 MONO_ADD_INS (bb, ins);
10819                 link_bblock (cfg, bb, next);
10820                 ins->inst_target_bb = next;
10821         }               
10822 }
10823
10824 /* checks that a and b represent the same instructions, conservatively,
10825  * it can return FALSE also for two trees that are equal.
10826  * FIXME: also make sure there are no side effects.
10827  */
10828 static int
10829 same_trees (MonoInst *a, MonoInst *b)
10830 {
10831         int arity;
10832         if (a->opcode != b->opcode)
10833                 return FALSE;
10834         arity = mono_burg_arity [a->opcode];
10835         if (arity == 1) {
10836                 if (a->ssa_op == b->ssa_op && a->ssa_op == MONO_SSA_LOAD && a->inst_i0 == b->inst_i0)
10837                         return TRUE;
10838                 return same_trees (a->inst_left, b->inst_left);
10839         } else if (arity == 2) {
10840                 return same_trees (a->inst_left, b->inst_left) && same_trees (a->inst_right, b->inst_right);
10841         } else if (arity == 0) {
10842                 switch (a->opcode) {
10843                 case OP_ICONST:
10844                         return a->inst_c0 == b->inst_c0;
10845                 default:
10846                         return FALSE;
10847                 }
10848         }
10849         return FALSE;
10850 }
10851
10852 static int
10853 get_unsigned_condbranch (int opcode)
10854 {
10855         switch (opcode) {
10856         case CEE_BLE: return CEE_BLE_UN;
10857         case CEE_BLT: return CEE_BLT_UN;
10858         case CEE_BGE: return CEE_BGE_UN;
10859         case CEE_BGT: return CEE_BGT_UN;
10860         }
10861         g_assert_not_reached ();
10862         return 0;
10863 }
10864
10865 static int
10866 tree_is_unsigned (MonoInst* ins) {
10867         switch (ins->opcode) {
10868         case OP_ICONST:
10869                 return (int)ins->inst_c0 >= 0;
10870         /* array lengths are positive as are string sizes */
10871         case CEE_LDLEN:
10872         case OP_STRLEN:
10873                 return TRUE;
10874         case CEE_CONV_U1:
10875         case CEE_CONV_U2:
10876         case CEE_CONV_U4:
10877         case CEE_CONV_OVF_U1:
10878         case CEE_CONV_OVF_U2:
10879         case CEE_CONV_OVF_U4:
10880                 return TRUE;
10881         case CEE_LDIND_U1:
10882         case CEE_LDIND_U2:
10883         case CEE_LDIND_U4:
10884                 return TRUE;
10885         default:
10886                 return FALSE;
10887         }
10888 }
10889
10890 /* check if an unsigned compare can be used instead of two signed compares
10891  * for (val < 0 || val > limit) conditionals.
10892  * Returns TRUE if the optimization has been applied.
10893  * Note that this can't be applied if the second arg is not positive...
10894  */
10895 static int
10896 try_unsigned_compare (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *bb_last)
10897 {
10898         MonoBasicBlock *truet, *falset;
10899         MonoInst *cmp_inst = bb_last->inst_left;
10900         MonoInst *condb;
10901         if (!cmp_inst->inst_right->inst_c0 == 0)
10902                 return FALSE;
10903         truet = bb_last->inst_true_bb;
10904         falset = bb_last->inst_false_bb;
10905         if (falset->in_count != 1)
10906                 return FALSE;
10907         condb = mono_inst_list_last (&falset->ins_list);
10908         /* target bb must have one instruction */
10909         if (!condb || (condb->node.next != &falset->ins_list))
10910                 return FALSE;
10911         if ((((condb->opcode == CEE_BLE || condb->opcode == CEE_BLT) && (condb->inst_false_bb == truet))
10912                         || ((condb->opcode == CEE_BGE || condb->opcode == CEE_BGT) && (condb->inst_true_bb == truet)))
10913                         && same_trees (cmp_inst->inst_left, condb->inst_left->inst_left)) {
10914                 if (!tree_is_unsigned (condb->inst_left->inst_right))
10915                         return FALSE;
10916                 condb->opcode = get_unsigned_condbranch (condb->opcode);
10917                 /* change the original condbranch to just point to the new unsigned check */
10918                 bb_last->opcode = OP_BR;
10919                 bb_last->inst_target_bb = falset;
10920                 replace_out_block (bb, truet, NULL);
10921                 replace_in_block (truet, bb, NULL);
10922                 return TRUE;
10923         }
10924         return FALSE;
10925 }
10926
10927 /*
10928  * Optimizes the branches on the Control Flow Graph
10929  *
10930  */
10931 static void
10932 optimize_branches (MonoCompile *cfg)
10933 {
10934         int i, changed = FALSE;
10935         MonoBasicBlock *bb, *bbn;
10936         guint32 niterations;
10937
10938         /*
10939          * Some crazy loops could cause the code below to go into an infinite
10940          * loop, see bug #53003 for an example. To prevent this, we put an upper
10941          * bound on the number of iterations.
10942          */
10943         if (cfg->num_bblocks > 1000)
10944                 niterations = cfg->num_bblocks * 2;
10945         else
10946                 niterations = 1000;
10947
10948         do {
10949                 MonoBasicBlock *previous_bb;
10950                 changed = FALSE;
10951                 niterations --;
10952
10953                 /* we skip the entry block (exit is handled specially instead ) */
10954                 for (previous_bb = cfg->bb_entry, bb = cfg->bb_entry->next_bb; bb; previous_bb = bb, bb = bb->next_bb) {
10955                         MonoInst *last_ins;
10956
10957                         /* dont touch code inside exception clauses */
10958                         if (bb->region != -1)
10959                                 continue;
10960
10961                         if (!bb->not_useless && remove_block_if_useless (cfg, bb, previous_bb)) {
10962                                 changed = TRUE;
10963                                 continue;
10964                         }
10965
10966                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
10967                                 if (cfg->verbose_level > 2)
10968                                         g_print ("nullify block triggered %d\n", bbn->block_num);
10969
10970                                 bb->next_bb = bbn->next_bb;
10971
10972                                 for (i = 0; i < bbn->out_count; i++)
10973                                         replace_in_block (bbn->out_bb [i], bbn, NULL);
10974
10975                                 nullify_basic_block (bbn);                      
10976                                 changed = TRUE;
10977                         }
10978
10979                         last_ins = mono_inst_list_last (&bb->ins_list);
10980                         if (bb->out_count == 1) {
10981                                 bbn = bb->out_bb [0];
10982
10983                                 /* conditional branches where true and false targets are the same can be also replaced with OP_BR */
10984                                 if (last_ins && MONO_IS_COND_BRANCH_OP (last_ins)) {
10985                                         MonoInst *pop;
10986                                         MONO_INST_NEW (cfg, pop, CEE_POP);
10987                                         pop->inst_left = last_ins->inst_left->inst_left;
10988                                         mono_add_ins_to_end (bb, pop);
10989                                         MONO_INST_NEW (cfg, pop, CEE_POP);
10990                                         pop->inst_left = last_ins->inst_left->inst_right;
10991                                         mono_add_ins_to_end (bb, pop);
10992                                         last_ins->opcode = OP_BR;
10993                                         last_ins->inst_target_bb = last_ins->inst_true_bb;
10994                                         changed = TRUE;
10995                                         if (cfg->verbose_level > 2)
10996                                                 g_print ("cond branch removal triggered in %d %d\n", bb->block_num, bb->out_count);
10997                                 }
10998
10999                                 if (bb->region == bbn->region && bb->next_bb == bbn) {
11000                                         /* the block are in sequence anyway ... */
11001
11002                                         /* branches to the following block can be removed */
11003                                         if (last_ins && last_ins->opcode == OP_BR) {
11004                                                 last_ins->opcode = OP_NOP;
11005                                                 changed = TRUE;
11006                                                 if (cfg->verbose_level > 2)
11007                                                         g_print ("br removal triggered %d -> %d\n", bb->block_num, bbn->block_num);
11008                                         }
11009
11010                                         if (bbn->in_count == 1) {
11011
11012                                                 if (bbn != cfg->bb_exit) {
11013                                                         if (cfg->verbose_level > 2)
11014                                                                 g_print ("block merge triggered %d -> %d\n", bb->block_num, bbn->block_num);
11015                                                         merge_basic_blocks (bb, bbn);
11016                                                         changed = TRUE;
11017                                                         continue;
11018                                                 }
11019
11020                                                 //mono_print_bb_code (bb);
11021                                         }
11022                                 }
11023                         }
11024                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
11025                                 if (cfg->verbose_level > 2) {
11026                                         g_print ("nullify block triggered %d\n", bbn->block_num);
11027                                 }
11028                                 bb->next_bb = bbn->next_bb;
11029
11030                                 for (i = 0; i < bbn->out_count; i++)
11031                                         replace_in_block (bbn->out_bb [i], bbn, NULL);
11032
11033                                 nullify_basic_block (bbn);                      
11034                                 changed = TRUE;
11035                                 continue;
11036                         }
11037
11038                         if (bb->out_count == 1) {
11039                                 bbn = bb->out_bb [0];
11040
11041                                 if (last_ins && last_ins->opcode == OP_BR) {
11042                                         MonoInst *bbn_code;
11043
11044                                         bbn = last_ins->inst_target_bb;
11045                                         bbn_code = mono_inst_list_first (&bbn->ins_list);
11046                                         if (bb->region == bbn->region && bbn_code &&
11047                                                         bbn_code->opcode == OP_BR &&
11048                                                         bbn_code->inst_target_bb->region == bb->region) {
11049                                                 if (cfg->verbose_level > 2)
11050                                                         g_print ("in %s branch to branch triggered %d -> %d -> %d\n", cfg->method->name, 
11051                                                                  bb->block_num, bbn->block_num, bbn_code->inst_target_bb->block_num);
11052
11053                                                 replace_in_block (bbn, bb, NULL);
11054                                                 replace_out_block (bb, bbn, bbn_code->inst_target_bb);
11055                                                 link_bblock (cfg, bb, bbn_code->inst_target_bb);
11056                                                 last_ins->inst_target_bb = bbn_code->inst_target_bb;
11057                                                 changed = TRUE;
11058                                                 continue;
11059                                         }
11060                                 }
11061                         } else if (bb->out_count == 2) {
11062                                 if (last_ins && MONO_IS_COND_BRANCH_NOFP (last_ins)) {
11063                                         int branch_result = mono_eval_cond_branch (last_ins);
11064                                         MonoBasicBlock *taken_branch_target = NULL, *untaken_branch_target = NULL;
11065                                         MonoInst *bbn_code;
11066
11067                                         if (branch_result == BRANCH_TAKEN) {
11068                                                 taken_branch_target = last_ins->inst_true_bb;
11069                                                 untaken_branch_target = last_ins->inst_false_bb;
11070                                         } else if (branch_result == BRANCH_NOT_TAKEN) {
11071                                                 taken_branch_target = last_ins->inst_false_bb;
11072                                                 untaken_branch_target = last_ins->inst_true_bb;
11073                                         }
11074                                         if (taken_branch_target) {
11075                                                 /* if mono_eval_cond_branch () is ever taken to handle 
11076                                                  * non-constant values to compare, issue a pop here.
11077                                                  */
11078                                                 last_ins->opcode = OP_BR;
11079                                                 last_ins->inst_target_bb = taken_branch_target;
11080                                                 mono_unlink_bblock (cfg, bb, untaken_branch_target);
11081                                                 changed = TRUE;
11082                                                 continue;
11083                                         }
11084                                         bbn = last_ins->inst_true_bb;
11085                                         bbn_code = mono_inst_list_first (&bbn->ins_list);
11086                                         if (bb->region == bbn->region && bbn_code && bbn_code->opcode == OP_BR &&
11087                                                         bbn_code->inst_target_bb->region == bb->region) {
11088                                                 if (cfg->verbose_level > 2)             
11089                                                         g_print ("cbranch1 to branch triggered %d -> (%d) %d (0x%02x)\n", 
11090                                                                  bb->block_num, bbn->block_num, bbn_code->inst_target_bb->block_num, 
11091                                                                  bbn_code->opcode);
11092
11093                                                 /* 
11094                                                  * Unlink, then relink bblocks to avoid various
11095                                                  * tricky situations when the two targets of the branch
11096                                                  * are equal, or will become equal after the change.
11097                                                  */
11098                                                 mono_unlink_bblock (cfg, bb, last_ins->inst_true_bb);
11099                                                 mono_unlink_bblock (cfg, bb, last_ins->inst_false_bb);
11100
11101                                                 last_ins->inst_true_bb = bbn_code->inst_target_bb;
11102
11103                                                 link_bblock (cfg, bb, last_ins->inst_true_bb);
11104                                                 link_bblock (cfg, bb, last_ins->inst_false_bb);
11105
11106                                                 changed = TRUE;
11107                                                 continue;
11108                                         }
11109
11110                                         bbn = last_ins->inst_false_bb;
11111                                         bbn_code = mono_inst_list_first (&bbn->ins_list);
11112                                         if (bb->region == bbn->region && bbn_code && bbn_code->opcode == OP_BR &&
11113                                                         bbn_code->inst_target_bb->region == bb->region) {
11114                                                 if (cfg->verbose_level > 2)
11115                                                         g_print ("cbranch2 to branch triggered %d -> (%d) %d (0x%02x)\n", 
11116                                                                  bb->block_num, bbn->block_num, bbn_code->inst_target_bb->block_num, 
11117                                                                  bbn_code->opcode);
11118
11119                                                 mono_unlink_bblock (cfg, bb, last_ins->inst_true_bb);
11120                                                 mono_unlink_bblock (cfg, bb, last_ins->inst_false_bb);
11121
11122                                                 last_ins->inst_false_bb = bbn_code->inst_target_bb;
11123
11124                                                 link_bblock (cfg, bb, last_ins->inst_true_bb);
11125                                                 link_bblock (cfg, bb, last_ins->inst_false_bb);
11126
11127                                                 changed = TRUE;
11128                                                 continue;
11129                                         }
11130                                 }
11131
11132                                 /* detect and optimize to unsigned compares checks like: if (v < 0 || v > limit */
11133                                 if (last_ins && last_ins->opcode == CEE_BLT && last_ins->inst_left->inst_right->opcode == OP_ICONST) {
11134                                         if (try_unsigned_compare (cfg, bb, last_ins)) {
11135                                                 /*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));*/
11136                                                 changed = TRUE;
11137                                                 continue;
11138                                         }
11139                                 }
11140
11141                                 if (last_ins && MONO_IS_COND_BRANCH_NOFP (last_ins)) {
11142                                         if (last_ins->inst_false_bb->out_of_line && (bb->region == last_ins->inst_false_bb->region)) {
11143                                                 /* Reverse the branch */
11144                                                 last_ins->opcode = reverse_branch_op (last_ins->opcode);
11145                                                 bbn = last_ins->inst_false_bb;
11146                                                 last_ins->inst_false_bb = last_ins->inst_true_bb;
11147                                                 last_ins->inst_true_bb = bbn;
11148
11149                                                 move_basic_block_to_end (cfg, last_ins->inst_true_bb);
11150                                                 if (cfg->verbose_level > 2)
11151                                                         g_print ("cbranch to throw block triggered %d.\n", 
11152                                                                          bb->block_num);
11153                                         }
11154                                 }
11155                         }
11156                 }
11157         } while (changed && (niterations > 0));
11158
11159 }
11160
11161 static void
11162 mono_compile_create_vars (MonoCompile *cfg)
11163 {
11164         MonoMethodSignature *sig;
11165         MonoMethodHeader *header;
11166         int i;
11167
11168         header = mono_method_get_header (cfg->method);
11169
11170         sig = mono_method_signature (cfg->method);
11171         
11172         if (!MONO_TYPE_IS_VOID (sig->ret)) {
11173                 cfg->ret = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
11174                 cfg->ret->opcode = OP_RETARG;
11175                 cfg->ret->inst_vtype = sig->ret;
11176                 cfg->ret->klass = mono_class_from_mono_type (sig->ret);
11177         }
11178         if (cfg->verbose_level > 2)
11179                 g_print ("creating vars\n");
11180
11181         cfg->args = mono_mempool_alloc0 (cfg->mempool, (sig->param_count + sig->hasthis) * sizeof (MonoInst*));
11182
11183         if (sig->hasthis)
11184                 cfg->args [0] = mono_compile_create_var (cfg, &cfg->method->klass->this_arg, OP_ARG);
11185
11186         for (i = 0; i < sig->param_count; ++i) {
11187                 cfg->args [i + sig->hasthis] = mono_compile_create_var (cfg, sig->params [i], OP_ARG);
11188                 if (sig->params [i]->byref) {
11189                         cfg->disable_ssa = TRUE;
11190                 }
11191         }
11192
11193         cfg->locals_start = cfg->num_varinfo;
11194
11195         if (cfg->verbose_level > 2)
11196                 g_print ("creating locals\n");
11197
11198         for (i = 0; i < header->num_locals; ++i)
11199                 mono_compile_create_var (cfg, header->locals [i], OP_LOCAL);
11200         if (cfg->verbose_level > 2)
11201                 g_print ("locals done\n");
11202
11203         mono_arch_create_vars (cfg);
11204 }
11205
11206 void
11207 mono_print_code (MonoCompile *cfg)
11208 {
11209         MonoBasicBlock *bb;
11210         
11211         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11212                 MonoInst *tree;
11213
11214                 if (!MONO_INST_LIST_EMPTY (&bb->ins_list))
11215                         g_print ("CODE BLOCK %d (nesting %d):\n",
11216                                  bb->block_num, bb->nesting);
11217
11218                 MONO_BB_FOR_EACH_INS (bb, tree) {
11219                         mono_print_tree (tree);
11220                         g_print ("\n");
11221                 }
11222         }
11223 }
11224
11225 extern const char * const mono_burg_rule_string [];
11226
11227 static void
11228 emit_state (MonoCompile *cfg, MBState *state, int goal)
11229 {
11230         MBState *kids [10];
11231         int ern = mono_burg_rule (state, goal);
11232         const guint16 *nts = mono_burg_nts_data + mono_burg_nts [ern];
11233
11234         //g_print ("rule: %s\n", mono_burg_rule_string [ern]);
11235         switch (goal) {
11236         case MB_NTERM_reg:
11237                 //if (state->reg2)
11238                 //      state->reg1 = state->reg2; /* chain rule */
11239                 //else
11240 #ifdef MONO_ARCH_ENABLE_EMIT_STATE_OPT
11241                 if (!state->reg1)
11242 #endif
11243                         state->reg1 = mono_regstate_next_int (cfg->rs);
11244                 //g_print ("alloc symbolic R%d (reg2: R%d) in block %d\n", state->reg1, state->reg2, cfg->cbb->block_num);
11245                 break;
11246         case MB_NTERM_lreg:
11247                 state->reg1 = mono_regstate_next_int (cfg->rs);
11248                 state->reg2 = mono_regstate_next_int (cfg->rs);
11249                 break;
11250         case MB_NTERM_freg:
11251 #ifdef MONO_ARCH_SOFT_FLOAT
11252                 state->reg1 = mono_regstate_next_int (cfg->rs);
11253                 state->reg2 = mono_regstate_next_int (cfg->rs);
11254 #else
11255                 state->reg1 = mono_regstate_next_float (cfg->rs);
11256 #endif
11257                 break;
11258         default:
11259 #ifdef MONO_ARCH_ENABLE_EMIT_STATE_OPT
11260                 /*
11261                  * Enabling this might cause bugs to surface in the local register
11262                  * allocators on some architectures like x86.
11263                  */
11264                 if ((state->tree->ssa_op == MONO_SSA_STORE) && (state->left->tree->opcode == OP_REGVAR)) {
11265                         /* Do not optimize away reg-reg moves */
11266                         if (! ((state->right->tree->ssa_op == MONO_SSA_LOAD) && (state->right->left->tree->opcode == OP_REGVAR))) {
11267                                 state->right->reg1 = state->left->tree->dreg;
11268                         }
11269                 }
11270 #endif
11271
11272                 /* do nothing */
11273                 break;
11274         }
11275         if (nts [0]) {
11276                 mono_burg_kids (state, ern, kids);
11277
11278                 emit_state (cfg, kids [0], nts [0]);
11279                 if (nts [1]) {
11280                         emit_state (cfg, kids [1], nts [1]);
11281                         if (nts [2]) {
11282                                 g_assert (!nts [3]);
11283                                 emit_state (cfg, kids [2], nts [2]);
11284                         }
11285                 }
11286         }
11287
11288 //      g_print ("emit: %s (%p)\n", mono_burg_rule_string [ern], state);
11289         mono_burg_emit (ern, state, state->tree, cfg);
11290 }
11291
11292 #define DEBUG_SELECTION
11293
11294 static void 
11295 mini_select_instructions (MonoCompile *cfg)
11296 {
11297         MonoBasicBlock *bb;
11298         
11299         cfg->state_pool = mono_mempool_new ();
11300         cfg->rs = mono_regstate_new ();
11301
11302         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11303                 MonoInst *last_ins = mono_inst_list_last (&bb->ins_list);
11304
11305                 if (last_ins && MONO_IS_COND_BRANCH_OP (last_ins) &&
11306                                 bb->next_bb != last_ins->inst_false_bb) {
11307
11308                         /* we are careful when inverting, since bugs like #59580
11309                          * could show up when dealing with NaNs.
11310                          */
11311                         if (MONO_IS_COND_BRANCH_NOFP(last_ins) && bb->next_bb == last_ins->inst_true_bb) {
11312                                 MonoBasicBlock *tmp =  last_ins->inst_true_bb;
11313                                 last_ins->inst_true_bb = last_ins->inst_false_bb;
11314                                 last_ins->inst_false_bb = tmp;
11315
11316                                 last_ins->opcode = reverse_branch_op (last_ins->opcode);
11317                         } else {                        
11318                                 MonoInst *inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
11319                                 inst->opcode = OP_BR;
11320                                 inst->inst_target_bb = last_ins->inst_false_bb;
11321                                 mono_bblock_add_inst (bb, inst);
11322                         }
11323                 }
11324         }
11325
11326 #ifdef DEBUG_SELECTION
11327         if (cfg->verbose_level >= 4) {
11328         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11329                 MonoInst *tree; 
11330                 g_print ("DUMP BLOCK %d:\n", bb->block_num);
11331
11332                 MONO_BB_FOR_EACH_INS (bb, tree) {
11333                         mono_print_tree (tree);
11334                         g_print ("\n");
11335                 }
11336         }
11337         }
11338 #endif
11339
11340         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11341                 MonoInst *tree, *n;     
11342                 MonoInstList head;
11343                 MBState *mbstate;
11344
11345                 MONO_INST_LIST_INIT (&head);
11346                 if (MONO_INST_LIST_EMPTY (&bb->ins_list))
11347                         continue;
11348                 MONO_INST_LIST_SPLICE_INIT (&bb->ins_list, &head);
11349                 
11350                 cfg->cbb = bb;
11351                 mono_regstate_reset (cfg->rs);
11352
11353 #ifdef DEBUG_SELECTION
11354                 if (cfg->verbose_level >= 3)
11355                         g_print ("LABEL BLOCK %d:\n", bb->block_num);
11356 #endif
11357                 MONO_INST_LIST_FOR_EACH_ENTRY_SAFE (tree, n, &head, node) {
11358 #ifdef DEBUG_SELECTION
11359                         if (cfg->verbose_level >= 3) {
11360                                 mono_print_tree (tree);
11361                                 g_print ("\n");
11362                         }
11363 #endif
11364
11365                         if (!(mbstate = mono_burg_label (tree, cfg))) {
11366                                 g_warning ("unable to label tree %p", tree);
11367                                 mono_print_tree (tree);
11368                                 g_print ("\n");                         
11369                                 g_assert_not_reached ();
11370                         }
11371                         emit_state (cfg, mbstate, MB_NTERM_stmt);
11372                 }
11373                 bb->max_vreg = cfg->rs->next_vreg;
11374
11375                 mono_mempool_empty (cfg->state_pool); 
11376         }
11377         mono_mempool_destroy (cfg->state_pool); 
11378 }
11379
11380 /*
11381  * mono_normalize_opcodes:
11382  *
11383  *   Replace CEE_ and OP_ opcodes with the corresponding OP_I or OP_L opcodes.
11384  */
11385
11386 static gint16 *remap_table;
11387
11388 #if SIZEOF_VOID_P == 8
11389 #define REMAP_OPCODE(opcode) OP_L ## opcode
11390 #else
11391 #define REMAP_OPCODE(opcode) OP_I ## opcode
11392 #endif
11393
11394 static G_GNUC_UNUSED void
11395 mono_normalize_opcodes (MonoCompile *cfg, MonoBasicBlock *bb)
11396 {
11397         MonoInst *ins;
11398
11399         if (!remap_table) {
11400                 remap_table = g_new0 (gint16, OP_LAST);
11401
11402 #if SIZEOF_VOID_P == 8
11403                 remap_table [CEE_CONV_U8] = OP_ZEXT_I4;
11404                 remap_table [CEE_CONV_U] = OP_ZEXT_I4;
11405                 remap_table [CEE_CONV_I8] = OP_SEXT_I4;
11406                 remap_table [CEE_CONV_I] = OP_SEXT_I4;
11407                 remap_table [CEE_CONV_OVF_U4] = OP_LCONV_TO_OVF_U4;
11408                 remap_table [CEE_CONV_OVF_I4_UN] = OP_LCONV_TO_OVF_I4_UN;
11409 #else
11410 #endif
11411                 remap_table [CEE_CONV_R4] = OP_ICONV_TO_R4;
11412                 remap_table [CEE_CONV_R8] = OP_ICONV_TO_R8;
11413                 remap_table [CEE_CONV_I4] = OP_MOVE;
11414                 remap_table [CEE_CONV_U4] = OP_MOVE;
11415                 remap_table [CEE_CONV_I1] = REMAP_OPCODE (CONV_TO_I1);
11416                 remap_table [CEE_CONV_I2] = REMAP_OPCODE (CONV_TO_I2);
11417                 remap_table [CEE_CONV_U1] = REMAP_OPCODE (CONV_TO_U1);
11418                 remap_table [CEE_CONV_U2] = REMAP_OPCODE (CONV_TO_U2);
11419                 remap_table [CEE_CONV_R_UN] = REMAP_OPCODE (CONV_TO_R_UN);
11420                 remap_table [CEE_ADD] = REMAP_OPCODE (ADD);
11421                 remap_table [CEE_SUB] = REMAP_OPCODE (SUB);
11422                 remap_table [CEE_MUL] = REMAP_OPCODE (MUL);
11423                 remap_table [CEE_DIV] = REMAP_OPCODE (DIV);
11424                 remap_table [CEE_REM] = REMAP_OPCODE (REM);
11425                 remap_table [CEE_DIV_UN] = REMAP_OPCODE (DIV_UN);
11426                 remap_table [CEE_REM_UN] = REMAP_OPCODE (REM_UN);
11427                 remap_table [CEE_AND] = REMAP_OPCODE (AND);
11428                 remap_table [CEE_OR] = REMAP_OPCODE (OR);
11429                 remap_table [CEE_XOR] = REMAP_OPCODE (XOR);
11430                 remap_table [CEE_SHL] = REMAP_OPCODE (SHL);
11431                 remap_table [CEE_SHR] = REMAP_OPCODE (SHR);
11432                 remap_table [CEE_SHR_UN] = REMAP_OPCODE (SHR_UN);
11433                 remap_table [CEE_NOT] = REMAP_OPCODE (NOT);
11434                 remap_table [CEE_NEG] = REMAP_OPCODE (NEG);
11435                 remap_table [CEE_CALL] = OP_CALL;
11436                 remap_table [CEE_BEQ] = REMAP_OPCODE (BEQ);
11437                 remap_table [CEE_BNE_UN] = REMAP_OPCODE (BNE_UN);
11438                 remap_table [CEE_BLT] = REMAP_OPCODE (BLT);
11439                 remap_table [CEE_BLT_UN] = REMAP_OPCODE (BLT_UN);
11440                 remap_table [CEE_BGT] = REMAP_OPCODE (BGT);
11441                 remap_table [CEE_BGT_UN] = REMAP_OPCODE (BGT_UN);
11442                 remap_table [CEE_BGE] = REMAP_OPCODE (BGE);
11443                 remap_table [CEE_BGE_UN] = REMAP_OPCODE (BGE_UN);
11444                 remap_table [CEE_BLE] = REMAP_OPCODE (BLE);
11445                 remap_table [CEE_BLE_UN] = REMAP_OPCODE (BLE_UN);
11446                 remap_table [CEE_ADD_OVF] = REMAP_OPCODE (ADD_OVF);
11447                 remap_table [CEE_ADD_OVF_UN] = REMAP_OPCODE (ADD_OVF_UN);
11448                 remap_table [CEE_SUB_OVF] = REMAP_OPCODE (SUB_OVF);
11449                 remap_table [CEE_SUB_OVF_UN] = REMAP_OPCODE (SUB_OVF_UN);
11450                 remap_table [CEE_MUL_OVF] = REMAP_OPCODE (MUL_OVF);
11451                 remap_table [CEE_MUL_OVF_UN] = REMAP_OPCODE (MUL_OVF_UN);
11452         }
11453
11454         MONO_BB_FOR_EACH_INS (bb, ins) {
11455                 int remapped = remap_table [ins->opcode];
11456                 if (remapped)
11457                         ins->opcode = remapped;
11458         }
11459 }
11460
11461 void
11462 mono_codegen (MonoCompile *cfg)
11463 {
11464         MonoJumpInfo *patch_info;
11465         MonoBasicBlock *bb;
11466         int i, max_epilog_size;
11467         guint8 *code;
11468
11469         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11470                 cfg->spill_count = 0;
11471                 /* we reuse dfn here */
11472                 /* bb->dfn = bb_count++; */
11473 #ifdef MONO_ARCH_ENABLE_NORMALIZE_OPCODES
11474                 mono_normalize_opcodes (cfg, bb);
11475 #endif
11476
11477                 mono_arch_lowering_pass (cfg, bb);
11478
11479                 if (cfg->opt & MONO_OPT_PEEPHOLE)
11480                         mono_arch_peephole_pass_1 (cfg, bb);
11481
11482                 mono_local_regalloc (cfg, bb);
11483
11484                 if (cfg->opt & MONO_OPT_PEEPHOLE)
11485                         mono_arch_peephole_pass_2 (cfg, bb);
11486         }
11487
11488         if (cfg->prof_options & MONO_PROFILE_COVERAGE)
11489                 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, cfg->num_bblocks);
11490
11491         code = mono_arch_emit_prolog (cfg);
11492
11493         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
11494                 code = mono_arch_instrument_prolog (cfg, mono_profiler_method_enter, code, FALSE);
11495
11496         cfg->code_len = code - cfg->native_code;
11497         cfg->prolog_end = cfg->code_len;
11498
11499         mono_debug_open_method (cfg);
11500
11501         /* emit code all basic blocks */
11502         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11503                 bb->native_offset = cfg->code_len;
11504                 mono_arch_output_basic_block (cfg, bb);
11505
11506                 if (bb == cfg->bb_exit) {
11507                         cfg->epilog_begin = cfg->code_len;
11508
11509                         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE) {
11510                                 code = cfg->native_code + cfg->code_len;
11511                                 code = mono_arch_instrument_epilog (cfg, mono_profiler_method_leave, code, FALSE);
11512                                 cfg->code_len = code - cfg->native_code;
11513                                 g_assert (cfg->code_len < cfg->code_size);
11514                         }
11515
11516                         mono_arch_emit_epilog (cfg);
11517                 }
11518         }
11519
11520         mono_arch_emit_exceptions (cfg);
11521
11522         max_epilog_size = 0;
11523
11524         code = cfg->native_code + cfg->code_len;
11525
11526         /* we always allocate code in cfg->domain->code_mp to increase locality */
11527         cfg->code_size = cfg->code_len + max_epilog_size;
11528         /* fixme: align to MONO_ARCH_CODE_ALIGNMENT */
11529
11530         if (cfg->method->dynamic) {
11531                 /* Allocate the code into a separate memory pool so it can be freed */
11532                 cfg->dynamic_info = g_new0 (MonoJitDynamicMethodInfo, 1);
11533                 cfg->dynamic_info->code_mp = mono_code_manager_new_dynamic ();
11534                 mono_domain_lock (cfg->domain);
11535                 mono_dynamic_code_hash_insert (cfg->domain, cfg->method, cfg->dynamic_info);
11536                 mono_domain_unlock (cfg->domain);
11537
11538                 code = mono_code_manager_reserve (cfg->dynamic_info->code_mp, cfg->code_size);
11539         } else {
11540                 mono_domain_lock (cfg->domain);
11541                 code = mono_code_manager_reserve (cfg->domain->code_mp, cfg->code_size);
11542                 mono_domain_unlock (cfg->domain);
11543         }
11544
11545         memcpy (code, cfg->native_code, cfg->code_len);
11546         g_free (cfg->native_code);
11547         cfg->native_code = code;
11548         code = cfg->native_code + cfg->code_len;
11549   
11550         /* g_assert (((int)cfg->native_code & (MONO_ARCH_CODE_ALIGNMENT - 1)) == 0); */
11551         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
11552                 switch (patch_info->type) {
11553                 case MONO_PATCH_INFO_ABS: {
11554                         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (patch_info->data.target);
11555                         if (info) {
11556                                 //printf ("TEST %s %p\n", info->name, patch_info->data.target);
11557                                 if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && 
11558                                         strstr (cfg->method->name, info->name))
11559                                         /*
11560                                          * This is an icall wrapper, and this is a call to the
11561                                          * wrapped function.
11562                                          */
11563                                         ;
11564                                 else {
11565                                         /* for these array methods we currently register the same function pointer
11566                                          * since it's a vararg function. But this means that mono_find_jit_icall_by_addr ()
11567                                          * will return the incorrect one depending on the order they are registered.
11568                                          * See tests/test-arr.cs
11569                                          */
11570                                         if (strstr (info->name, "ves_array_new_va_") == NULL && strstr (info->name, "ves_array_element_address_") == NULL) {
11571                                                 patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
11572                                                 patch_info->data.name = info->name;
11573                                         }
11574                                 }
11575                         }
11576                         else {
11577                                 MonoVTable *vtable = mono_find_class_init_trampoline_by_addr (patch_info->data.target);
11578                                 if (vtable) {
11579                                         patch_info->type = MONO_PATCH_INFO_CLASS_INIT;
11580                                         patch_info->data.klass = vtable->klass;
11581                                 } else {
11582                                         MonoClass *klass = mono_find_delegate_trampoline_by_addr (patch_info->data.target);
11583                                         if (klass) {
11584                                                 patch_info->type = MONO_PATCH_INFO_DELEGATE_TRAMPOLINE;
11585                                                 patch_info->data.klass = klass;
11586                                         }
11587                                 }
11588                         }
11589                         break;
11590                 }
11591                 case MONO_PATCH_INFO_SWITCH: {
11592                         gpointer *table;
11593                         if (cfg->method->dynamic) {
11594                                 table = mono_code_manager_reserve (cfg->dynamic_info->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
11595                         } else {
11596                                 mono_domain_lock (cfg->domain);
11597                                 table = mono_code_manager_reserve (cfg->domain->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
11598                                 mono_domain_unlock (cfg->domain);
11599                         }
11600
11601                         if (!cfg->compile_aot)
11602                                 /* In the aot case, the patch already points to the correct location */
11603                                 patch_info->ip.i = patch_info->ip.label->inst_c0;
11604                         for (i = 0; i < patch_info->data.table->table_size; i++) {
11605                                 table [i] = GINT_TO_POINTER (patch_info->data.table->table [i]->native_offset);
11606                         }
11607                         patch_info->data.table->table = (MonoBasicBlock**)table;
11608                         break;
11609                 }
11610                 default:
11611                         /* do nothing */
11612                         break;
11613                 }
11614         }
11615
11616 #ifdef VALGRIND_JIT_REGISTER_MAP
11617 if (valgrind_register){
11618                 char* nm = mono_method_full_name (cfg->method, TRUE);
11619                 VALGRIND_JIT_REGISTER_MAP (nm, cfg->native_code, cfg->native_code + cfg->code_len);
11620                 g_free (nm);
11621         }
11622 #endif
11623  
11624         if (cfg->verbose_level > 0) {
11625                 char* nm = mono_method_full_name (cfg->method, TRUE);
11626                 g_print ("Method %s emitted at %p to %p (code length %d) [%s]\n", 
11627                                  nm, 
11628                                  cfg->native_code, cfg->native_code + cfg->code_len, cfg->code_len, cfg->domain->friendly_name);
11629                 g_free (nm);
11630         }
11631
11632 #ifdef MONO_ARCH_HAVE_SAVE_UNWIND_INFO
11633         mono_arch_save_unwind_info (cfg);
11634 #endif
11635         
11636         mono_arch_patch_code (cfg->method, cfg->domain, cfg->native_code, cfg->patch_info, cfg->run_cctors);
11637
11638         if (cfg->method->dynamic) {
11639                 mono_code_manager_commit (cfg->dynamic_info->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
11640         } else {
11641                 mono_domain_lock (cfg->domain);
11642                 mono_code_manager_commit (cfg->domain->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
11643                 mono_domain_unlock (cfg->domain);
11644         }
11645         
11646         mono_arch_flush_icache (cfg->native_code, cfg->code_len);
11647
11648         mono_debug_close_method (cfg);
11649 }
11650
11651
11652
11653 static void
11654 remove_critical_edges (MonoCompile *cfg) {
11655         MonoBasicBlock *bb;
11656         MonoBasicBlock *previous_bb;
11657         
11658         if (cfg->verbose_level > 3) {
11659                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11660                         MonoInst *last_ins;
11661                         int i;
11662                         printf ("remove_critical_edges %s, BEFORE BB%d (in:", mono_method_full_name (cfg->method, TRUE), bb->block_num);
11663                         for (i = 0; i < bb->in_count; i++) {
11664                                 printf (" %d", bb->in_bb [i]->block_num);
11665                         }
11666                         printf (") (out:");
11667                         for (i = 0; i < bb->out_count; i++) {
11668                                 printf (" %d", bb->out_bb [i]->block_num);
11669                         }
11670                         printf (")");
11671                         last_ins = mono_inst_list_last (&bb->ins_list);
11672                         if (last_ins) {
11673                                 printf (" ");
11674                                 mono_print_tree (last_ins);
11675                         }
11676                         printf ("\n");
11677                 }
11678         }
11679         
11680         for (previous_bb = cfg->bb_entry, bb = previous_bb->next_bb; bb != NULL; previous_bb = previous_bb->next_bb, bb = bb->next_bb) {
11681                 if (bb->in_count > 1) {
11682                         int in_bb_index;
11683                         for (in_bb_index = 0; in_bb_index < bb->in_count; in_bb_index++) {
11684                                 MonoBasicBlock *in_bb = bb->in_bb [in_bb_index];
11685                                 if (in_bb->out_count > 1) {
11686                                         MonoBasicBlock *new_bb = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock));
11687                                         MONO_INST_LIST_INIT (&new_bb->ins_list);
11688                                         new_bb->block_num = cfg->num_bblocks++;
11689 //                                      new_bb->real_offset = bb->real_offset;
11690                                         new_bb->region = bb->region;
11691                                         
11692                                         /* Do not alter the CFG while altering the BB list */
11693                                         if (previous_bb->region == bb->region) {
11694                                                 if (previous_bb != cfg->bb_entry) {
11695                                                         MonoInst *last_ins;
11696                                                         /* If previous_bb "followed through" to bb, */
11697                                                         /* keep it linked with a OP_BR */
11698                                                         last_ins = mono_inst_list_last (&previous_bb->ins_list);
11699                                                         if ((last_ins == NULL) ||
11700                                                                         ((last_ins->opcode != OP_BR) &&
11701                                                                         (!(MONO_IS_COND_BRANCH_OP (last_ins))) &&
11702                                                                         (last_ins->opcode != OP_SWITCH))) {
11703                                                                 int i;
11704                                                                 /* Make sure previous_bb really falls through bb */
11705                                                                 for (i = 0; i < previous_bb->out_count; i++) {
11706                                                                         if (previous_bb->out_bb [i] == bb) {
11707                                                                                 MonoInst *jump;
11708                                                                                 MONO_INST_NEW (cfg, jump, OP_BR);
11709                                                                                 MONO_ADD_INS (previous_bb, jump);
11710                                                                                 jump->cil_code = previous_bb->cil_code;
11711                                                                                 jump->inst_target_bb = bb;
11712                                                                                 break;
11713                                                                         }
11714                                                                 }
11715                                                         }
11716                                                 } else {
11717                                                         /* We cannot add any inst to the entry BB, so we must */
11718                                                         /* put a new BB in the middle to hold the OP_BR */
11719                                                         MonoInst *jump;
11720                                                         MonoBasicBlock *new_bb_after_entry = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock));
11721                                                         MONO_INST_LIST_INIT (&new_bb_after_entry->ins_list);
11722                                                         new_bb_after_entry->block_num = cfg->num_bblocks++;
11723 //                                                      new_bb_after_entry->real_offset = bb->real_offset;
11724                                                         new_bb_after_entry->region = bb->region;
11725                                                         
11726                                                         MONO_INST_NEW (cfg, jump, OP_BR);
11727                                                         MONO_ADD_INS (new_bb_after_entry, jump);
11728                                                         jump->cil_code = bb->cil_code;
11729                                                         jump->inst_target_bb = bb;
11730                                                         
11731                                                         previous_bb->next_bb = new_bb_after_entry;
11732                                                         previous_bb = new_bb_after_entry;
11733                                                         
11734                                                         if (cfg->verbose_level > 2) {
11735                                                                 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);
11736                                                         }
11737                                                 }
11738                                         }
11739                                         
11740                                         /* Insert new_bb in the BB list */
11741                                         previous_bb->next_bb = new_bb;
11742                                         new_bb->next_bb = bb;
11743                                         previous_bb = new_bb;
11744                                         
11745                                         /* Setup in_bb and out_bb */
11746                                         new_bb->in_bb = mono_mempool_alloc ((cfg)->mempool, sizeof (MonoBasicBlock*));
11747                                         new_bb->in_bb [0] = in_bb;
11748                                         new_bb->in_count = 1;
11749                                         new_bb->out_bb = mono_mempool_alloc ((cfg)->mempool, sizeof (MonoBasicBlock*));
11750                                         new_bb->out_bb [0] = bb;
11751                                         new_bb->out_count = 1;
11752                                         
11753                                         /* Relink in_bb and bb to (from) new_bb */
11754                                         replace_out_block (in_bb, bb, new_bb);
11755                                         replace_out_block_in_code (in_bb, bb, new_bb);
11756                                         replace_in_block (bb, in_bb, new_bb);
11757                                         
11758                                         if (cfg->verbose_level > 2) {
11759                                                 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);
11760                                         }
11761                                 }
11762                         }
11763                 }
11764         }
11765         
11766         if (cfg->verbose_level > 3) {
11767                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11768                         MonoInst *last_ins;
11769                         int i;
11770                         printf ("remove_critical_edges %s, AFTER BB%d (in:", mono_method_full_name (cfg->method, TRUE), bb->block_num);
11771                         for (i = 0; i < bb->in_count; i++) {
11772                                 printf (" %d", bb->in_bb [i]->block_num);
11773                         }
11774                         printf (") (out:");
11775                         for (i = 0; i < bb->out_count; i++) {
11776                                 printf (" %d", bb->out_bb [i]->block_num);
11777                         }
11778                         printf (")");
11779                         last_ins = mono_inst_list_last (&bb->ins_list);
11780                         if (last_ins) {
11781                                 printf (" ");
11782                                 mono_print_tree (last_ins);
11783                         }
11784                         printf ("\n");
11785                 }
11786         }
11787 }
11788
11789 /*
11790  * mini_method_compile:
11791  * @method: the method to compile
11792  * @opts: the optimization flags to use
11793  * @domain: the domain where the method will be compiled in
11794  * @run_cctors: whether we should run type ctors if possible
11795  * @compile_aot: whether this is an AOT compilation
11796  * @parts: debug flag
11797  *
11798  * Returns: a MonoCompile* pointer. Caller must check the exception_type
11799  * field in the returned struct to see if compilation succeded.
11800  */
11801 MonoCompile*
11802 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gboolean run_cctors, gboolean compile_aot, int parts)
11803 {
11804         MonoMethodHeader *header;
11805         guint8 *ip;
11806         MonoCompile *cfg;
11807         MonoJitInfo *jinfo;
11808         int dfn = 0, i, code_size_ratio;
11809         gboolean deadce_has_run = FALSE;
11810         gboolean try_generic_shared;
11811         MonoMethod *method_to_compile;
11812         int generic_info_size;
11813
11814         mono_jit_stats.methods_compiled++;
11815         if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)
11816                 mono_profiler_method_jit (method);
11817  
11818         if (compile_aot)
11819                 /* We are passed the original generic method definition */
11820                 try_generic_shared = mono_class_generic_sharing_enabled (method->klass) &&
11821                         (opts & MONO_OPT_GSHARED) && (method->generic_container || method->klass->generic_container);
11822         else
11823                 try_generic_shared = mono_class_generic_sharing_enabled (method->klass) &&
11824                         (opts & MONO_OPT_GSHARED) && mono_method_is_generic_sharable_impl (method);
11825
11826         if (opts & MONO_OPT_GSHARED) {
11827                 if (try_generic_shared)
11828                         mono_stats.generics_sharable_methods++;
11829                 else if (mono_method_is_generic_impl (method))
11830                         mono_stats.generics_unsharable_methods++;
11831         }
11832
11833  restart_compile:
11834         if (try_generic_shared) {
11835                 MonoMethod *declaring_method;
11836                 MonoGenericContext *shared_context;
11837
11838                 if (compile_aot) {
11839                         declaring_method = method;
11840                 } else {
11841                         declaring_method = mono_method_get_declaring_generic_method (method);
11842                         g_assert (method->klass->generic_class->container_class == declaring_method->klass);
11843                 }
11844
11845                 if (declaring_method->generic_container)
11846                         shared_context = &declaring_method->generic_container->context;
11847                 else
11848                         shared_context = &declaring_method->klass->generic_container->context;
11849
11850                 method_to_compile = mono_class_inflate_generic_method (declaring_method, shared_context);
11851                 g_assert (method_to_compile);
11852         } else {
11853                 method_to_compile = method;
11854         }
11855
11856         cfg = g_new0 (MonoCompile, 1);
11857         cfg->method = method_to_compile;
11858         cfg->mempool = mono_mempool_new ();
11859         cfg->opt = opts;
11860         cfg->prof_options = mono_profiler_get_events ();
11861         cfg->run_cctors = run_cctors;
11862         cfg->domain = domain;
11863         cfg->verbose_level = mini_verbose;
11864         cfg->compile_aot = compile_aot;
11865         cfg->skip_visibility = method->skip_visibility;
11866         if (try_generic_shared)
11867                 cfg->generic_sharing_context = (MonoGenericSharingContext*)&cfg->generic_sharing_context;
11868         cfg->token_info_hash = g_hash_table_new (NULL, NULL);
11869
11870         header = mono_method_get_header (method_to_compile);
11871         if (!header) {
11872                 cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
11873                 cfg->exception_message = g_strdup_printf ("Missing or incorrect header for method %s", cfg->method->name);
11874                 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
11875                         mono_profiler_method_end_jit (method, NULL, MONO_PROFILE_FAILED);
11876                 return cfg;
11877         }
11878
11879         ip = (guint8 *)header->code;
11880
11881         if (cfg->verbose_level > 2)
11882                 g_print ("converting method %s\n", mono_method_full_name (method, TRUE));
11883
11884         /*
11885          * create MonoInst* which represents arguments and local variables
11886          */
11887         mono_compile_create_vars (cfg);
11888
11889         if ((i = mono_method_to_ir (cfg, method_to_compile, NULL, NULL, cfg->locals_start, NULL, NULL, NULL, 0, FALSE)) < 0) {
11890                 if (try_generic_shared && cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
11891                         if (compile_aot)
11892                                 return cfg;
11893                         mono_destroy_compile (cfg);
11894                         try_generic_shared = FALSE;
11895                         goto restart_compile;
11896                 }
11897                 g_assert (cfg->exception_type != MONO_EXCEPTION_GENERIC_SHARING_FAILED);
11898
11899                 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
11900                         mono_profiler_method_end_jit (method, NULL, MONO_PROFILE_FAILED);
11901                 /* cfg contains the details of the failure, so let the caller cleanup */
11902                 return cfg;
11903         }
11904
11905         mono_jit_stats.basic_blocks += cfg->num_bblocks;
11906         mono_jit_stats.max_basic_blocks = MAX (cfg->num_bblocks, mono_jit_stats.max_basic_blocks);
11907
11908         if ((cfg->num_varinfo > 2000) && !cfg->compile_aot) {
11909                 /* 
11910                  * we disable some optimizations if there are too many variables
11911                  * because JIT time may become too expensive. The actual number needs 
11912                  * to be tweaked and eventually the non-linear algorithms should be fixed.
11913                  */
11914                 cfg->opt &= ~ (MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP);
11915                 cfg->disable_ssa = TRUE;
11916         }
11917
11918         /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/
11919
11920         if (cfg->opt & MONO_OPT_BRANCH)
11921                 optimize_branches (cfg);
11922
11923         if (cfg->opt & MONO_OPT_SSAPRE) {
11924                 remove_critical_edges (cfg);
11925         }
11926
11927         /* Depth-first ordering on basic blocks */
11928         cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
11929
11930         df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
11931         if (cfg->num_bblocks != dfn + 1) {
11932                 MonoBasicBlock *bb;
11933
11934                 cfg->num_bblocks = dfn + 1;
11935
11936                 if (!header->clauses) {
11937                         /* remove unreachable code, because the code in them may be 
11938                          * inconsistent  (access to dead variables for example) */
11939                         for (bb = cfg->bb_entry; bb;) {
11940                                 MonoBasicBlock *bbn = bb->next_bb;
11941
11942                                 if (bbn && bbn->region == -1 && !bbn->dfn) {
11943                                         if (cfg->verbose_level > 1)
11944                                                 g_print ("found unreachable code in BB%d\n", bbn->block_num);
11945                                         bb->next_bb = bbn->next_bb;
11946                                         nullify_basic_block (bbn);                      
11947                                 } else {
11948                                         bb = bb->next_bb;
11949                                 }
11950                         }
11951                 }
11952         }
11953
11954         if (cfg->opt & MONO_OPT_LOOP) {
11955                 mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM);
11956                 mono_compute_natural_loops (cfg);
11957         }
11958
11959         /* after method_to_ir */
11960         if (parts == 1)
11961                 return cfg;
11962
11963 //#define DEBUGSSA "logic_run"
11964 #define DEBUGSSA_CLASS "Tests"
11965 #ifdef DEBUGSSA
11966
11967         if (!header->num_clauses && !cfg->disable_ssa) {
11968                 mono_local_cprop (cfg);
11969 #ifndef DISABLE_SSA
11970                 mono_ssa_compute (cfg);
11971 #endif
11972         }
11973 #else 
11974
11975         /* fixme: add all optimizations which requires SSA */
11976         if (cfg->opt & (MONO_OPT_SSA | MONO_OPT_ABCREM | MONO_OPT_SSAPRE)) {
11977                 if (!(cfg->comp_done & MONO_COMP_SSA) && !header->num_clauses && !cfg->disable_ssa) {
11978                         mono_local_cprop (cfg);
11979 #ifndef DISABLE_SSA
11980                         mono_ssa_compute (cfg);
11981 #endif
11982
11983                         if (cfg->verbose_level >= 2) {
11984                                 print_dfn (cfg);
11985                         }
11986                 }
11987         }
11988 #endif
11989
11990         /* after SSA translation */
11991         if (parts == 2)
11992                 return cfg;
11993
11994         if ((cfg->opt & MONO_OPT_CONSPROP) || (cfg->opt & MONO_OPT_COPYPROP)) {
11995                 if (cfg->comp_done & MONO_COMP_SSA) {
11996 #ifndef DISABLE_SSA
11997                         mono_ssa_cprop (cfg);
11998 #endif
11999                 } else {
12000                         mono_local_cprop (cfg);
12001                 }
12002         }
12003
12004 #ifndef DISABLE_SSA
12005         if (cfg->comp_done & MONO_COMP_SSA) {                   
12006                 //mono_ssa_deadce (cfg);
12007
12008                 //mono_ssa_strength_reduction (cfg);
12009
12010                 if (cfg->opt & MONO_OPT_SSAPRE) {
12011                         mono_perform_ssapre (cfg);
12012                         //mono_local_cprop (cfg);
12013                 }
12014                 
12015                 if (cfg->opt & MONO_OPT_DEADCE) {
12016                         mono_ssa_deadce (cfg);
12017                         deadce_has_run = TRUE;
12018                 }
12019                 
12020                 if ((cfg->flags & MONO_CFG_HAS_LDELEMA) && (cfg->opt & MONO_OPT_ABCREM))
12021                         mono_perform_abc_removal (cfg);
12022                 
12023                 mono_ssa_remove (cfg);
12024
12025                 if (cfg->opt & MONO_OPT_BRANCH)
12026                         optimize_branches (cfg);
12027         }
12028 #endif
12029
12030         /* after SSA removal */
12031         if (parts == 3)
12032                 return cfg;
12033
12034         if (cfg->verbose_level > 4) {
12035                 printf ("BEFORE DECOMPSE START\n");
12036                 mono_print_code (cfg);
12037                 printf ("BEFORE DECOMPSE END\n");
12038         }
12039         
12040         decompose_pass (cfg);
12041
12042         if (cfg->got_var) {
12043                 GList *regs;
12044
12045                 g_assert (cfg->got_var_allocated);
12046
12047                 /* 
12048                  * Allways allocate the GOT var to a register, because keeping it
12049                  * in memory will increase the number of live temporaries in some
12050                  * code created by inssel.brg, leading to the well known spills+
12051                  * branches problem. Testcase: mcs crash in 
12052                  * System.MonoCustomAttrs:GetCustomAttributes.
12053                  */
12054                 regs = mono_arch_get_global_int_regs (cfg);
12055                 g_assert (regs);
12056                 cfg->got_var->opcode = OP_REGVAR;
12057                 cfg->got_var->dreg = GPOINTER_TO_INT (regs->data);
12058                 cfg->used_int_regs |= 1LL << cfg->got_var->dreg;
12059                 
12060                 g_list_free (regs);
12061         }
12062
12063         /* todo: remove code when we have verified that the liveness for try/catch blocks
12064          * works perfectly 
12065          */
12066         /* 
12067          * Currently, this can't be commented out since exception blocks are not
12068          * processed during liveness analysis.
12069          */
12070         mono_liveness_handle_exception_clauses (cfg);
12071
12072         if (cfg->opt & MONO_OPT_LINEARS) {
12073                 GList *vars, *regs;
12074                 
12075                 /* For now, compute aliasing info only if needed for deadce... */
12076                 if ((cfg->opt & MONO_OPT_DEADCE) && (! deadce_has_run) && (header->num_clauses == 0)) {
12077                         cfg->aliasing_info = mono_build_aliasing_information (cfg);
12078                 }
12079
12080                 /* fixme: maybe we can avoid to compute livenesss here if already computed ? */
12081                 cfg->comp_done &= ~MONO_COMP_LIVENESS;
12082                 if (!(cfg->comp_done & MONO_COMP_LIVENESS))
12083                         mono_analyze_liveness (cfg);
12084
12085                 if (cfg->aliasing_info != NULL) {
12086                         mono_aliasing_deadce (cfg->aliasing_info);
12087                         deadce_has_run = TRUE;
12088                 }
12089                 
12090                 if ((vars = mono_arch_get_allocatable_int_vars (cfg))) {
12091                         regs = mono_arch_get_global_int_regs (cfg);
12092                         if (cfg->got_var)
12093                                 regs = g_list_delete_link (regs, regs);
12094                         mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs);
12095                 }
12096                 
12097                 if (cfg->aliasing_info != NULL) {
12098                         mono_destroy_aliasing_information (cfg->aliasing_info);
12099                         cfg->aliasing_info = NULL;
12100                 }
12101         }
12102
12103         //mono_print_code (cfg);
12104
12105     //print_dfn (cfg);
12106         
12107         /* variables are allocated after decompose, since decompose could create temps */
12108         mono_arch_allocate_vars (cfg);
12109
12110         if (cfg->opt & MONO_OPT_CFOLD)
12111                 mono_constant_fold (cfg);
12112
12113         mini_select_instructions (cfg);
12114
12115         mono_codegen (cfg);
12116         if (cfg->verbose_level >= 2) {
12117                 char *id =  mono_method_full_name (cfg->method, FALSE);
12118                 mono_disassemble_code (cfg, cfg->native_code, cfg->code_len, id + 3);
12119                 g_free (id);
12120         }
12121
12122         if (cfg->generic_sharing_context)
12123                 generic_info_size = sizeof (MonoGenericJitInfo);
12124         else
12125                 generic_info_size = 0;
12126
12127         if (cfg->method->dynamic) {
12128                 jinfo = g_malloc0 (sizeof (MonoJitInfo) + (header->num_clauses * sizeof (MonoJitExceptionInfo)) +
12129                                 generic_info_size);
12130         } else {
12131                 /* we access cfg->domain->mp */
12132                 mono_domain_lock (cfg->domain);
12133                 jinfo = mono_mempool_alloc0 (cfg->domain->mp, sizeof (MonoJitInfo) +
12134                                 (header->num_clauses * sizeof (MonoJitExceptionInfo)) +
12135                                 generic_info_size);
12136                 mono_domain_unlock (cfg->domain);
12137         }
12138
12139         jinfo->method = method;
12140         jinfo->code_start = cfg->native_code;
12141         jinfo->code_size = cfg->code_len;
12142         jinfo->used_regs = cfg->used_int_regs;
12143         jinfo->domain_neutral = (cfg->opt & MONO_OPT_SHARED) != 0;
12144         jinfo->cas_inited = FALSE; /* initialization delayed at the first stalk walk using this method */
12145         jinfo->num_clauses = header->num_clauses;
12146
12147         /*
12148          * Static methods only get a generic JIT info if they use the
12149          * rgctx variable (which they are forced to if they have any
12150          * open catch clauses).
12151          */
12152         if (cfg->generic_sharing_context &&
12153                         (cfg->rgctx_var || !(method_to_compile->flags & METHOD_ATTRIBUTE_STATIC))) {
12154                 MonoInst *inst;
12155                 MonoGenericJitInfo *gi;
12156
12157                 jinfo->has_generic_jit_info = 1;
12158
12159                 gi = mono_jit_info_get_generic_jit_info (jinfo);
12160                 g_assert (gi);
12161
12162                 gi->generic_sharing_context = cfg->generic_sharing_context;
12163
12164                 if (method_to_compile->flags & METHOD_ATTRIBUTE_STATIC) {
12165                         inst = cfg->rgctx_var;
12166                         g_assert (inst->opcode == OP_REGOFFSET);
12167                 } else {
12168                         inst = cfg->varinfo [0];
12169                 }
12170
12171                 if (inst->opcode == OP_REGVAR) {
12172                         gi->this_in_reg = 1;
12173                         gi->this_reg = inst->dreg;
12174
12175                         //g_print ("this in reg %d\n", inst->dreg);
12176                 } else {
12177                         g_assert (inst->opcode == OP_REGOFFSET);
12178 #ifdef __i386__
12179                         g_assert (inst->inst_basereg == X86_EBP);
12180 #elif defined(__x86_64__)
12181                         g_assert (inst->inst_basereg == X86_EBP || inst->inst_basereg == X86_ESP);
12182 #endif
12183                         g_assert (inst->inst_offset >= G_MININT32 && inst->inst_offset <= G_MAXINT32);
12184
12185                         gi->this_in_reg = 0;
12186                         gi->this_reg = inst->inst_basereg;
12187                         gi->this_offset = inst->inst_offset;
12188
12189                         //g_print ("this at offset %d\n", inst->inst_offset);
12190                 }
12191         }
12192
12193         if (header->num_clauses) {
12194                 int i;
12195
12196                 for (i = 0; i < header->num_clauses; i++) {
12197                         MonoExceptionClause *ec = &header->clauses [i];
12198                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
12199                         MonoBasicBlock *tblock;
12200                         MonoInst *exvar;
12201
12202                         ei->flags = ec->flags;
12203
12204                         exvar = mono_find_exvar_for_offset (cfg, ec->handler_offset);
12205                         ei->exvar_offset = exvar ? exvar->inst_offset : 0;
12206
12207                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
12208                                 tblock = cfg->cil_offset_to_bb [ec->data.filter_offset];
12209                                 g_assert (tblock);
12210                                 ei->data.filter = cfg->native_code + tblock->native_offset;
12211                         } else {
12212                                 ei->data.catch_class = ec->data.catch_class;
12213                         }
12214
12215                         tblock = cfg->cil_offset_to_bb [ec->try_offset];
12216                         g_assert (tblock);
12217                         ei->try_start = cfg->native_code + tblock->native_offset;
12218                         g_assert (tblock->native_offset);
12219                         tblock = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
12220                         g_assert (tblock);
12221                         ei->try_end = cfg->native_code + tblock->native_offset;
12222                         g_assert (tblock->native_offset);
12223                         tblock = cfg->cil_offset_to_bb [ec->handler_offset];
12224                         g_assert (tblock);
12225                         ei->handler_start = cfg->native_code + tblock->native_offset;
12226                 }
12227         }
12228
12229         cfg->jit_info = jinfo;
12230 #if defined(__arm__)
12231         mono_arch_fixup_jinfo (cfg);
12232 #endif
12233
12234         mono_domain_lock (cfg->domain);
12235         mono_jit_info_table_add (cfg->domain, jinfo);
12236
12237         if (cfg->method->dynamic)
12238                 mono_dynamic_code_hash_lookup (cfg->domain, cfg->method)->ji = jinfo;
12239         mono_domain_unlock (cfg->domain);
12240
12241         /* collect statistics */
12242         mono_jit_stats.allocated_code_size += cfg->code_len;
12243         code_size_ratio = cfg->code_len;
12244         if (code_size_ratio > mono_jit_stats.biggest_method_size) {
12245                         mono_jit_stats.biggest_method_size = code_size_ratio;
12246                         mono_jit_stats.biggest_method = method;
12247         }
12248         code_size_ratio = (code_size_ratio * 100) / mono_method_get_header (method)->code_size;
12249         if (code_size_ratio > mono_jit_stats.max_code_size_ratio) {
12250                 mono_jit_stats.max_code_size_ratio = code_size_ratio;
12251                 mono_jit_stats.max_ratio_method = method;
12252         }
12253         mono_jit_stats.native_code_size += cfg->code_len;
12254
12255         if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
12256                 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
12257
12258         return cfg;
12259 }
12260
12261 static MonoJitInfo*
12262 lookup_generic_method (MonoDomain *domain, MonoMethod *method)
12263 {
12264         MonoMethod *open_method;
12265
12266         if (!mono_method_is_generic_sharable_impl (method))
12267                 return NULL;
12268
12269         open_method = mono_method_get_declaring_generic_method (method);
12270
12271         return mono_domain_lookup_shared_generic (domain, open_method);
12272 }
12273
12274 static MonoJitInfo*
12275 lookup_method (MonoDomain *domain, MonoMethod *method)
12276 {
12277         MonoJitInfo *ji = mono_internal_hash_table_lookup (&domain->jit_code_hash, method);
12278
12279         if (ji != NULL)
12280                 return ji;
12281
12282         return lookup_generic_method (domain, method);
12283 }
12284
12285 static gpointer
12286 mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain, int opt)
12287 {
12288         MonoCompile *cfg;
12289         gpointer code = NULL;
12290         MonoJitInfo *info;
12291
12292 #ifdef MONO_USE_AOT_COMPILER
12293         if ((opt & MONO_OPT_AOT) && !(mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)) {
12294                 MonoDomain *domain = mono_domain_get ();
12295
12296                 mono_class_init (method->klass);
12297
12298                 mono_domain_lock (domain);
12299                 if ((code = mono_aot_get_method (domain, method))) {
12300                         mono_domain_unlock (domain);
12301                         mono_runtime_class_init (mono_class_vtable (domain, method->klass));
12302                         return code;
12303                 }
12304
12305                 mono_domain_unlock (domain);
12306         }
12307 #endif
12308
12309         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
12310             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
12311                 MonoMethod *nm;
12312                 MonoMethodPInvoke* piinfo = (MonoMethodPInvoke *) method;
12313
12314                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE && !MONO_CLASS_IS_IMPORT(method->klass))
12315                         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);
12316
12317                 if (!piinfo->addr) {
12318                         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
12319                                 piinfo->addr = mono_lookup_internal_call (method);
12320                         else
12321                                 if (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)
12322                                         mono_lookup_pinvoke_call (method, NULL, NULL);
12323                 }
12324                         nm = mono_marshal_get_native_wrapper (method, check_for_pending_exc);
12325                         return mono_get_addr_from_ftnptr (mono_compile_method (nm));
12326
12327                         //if (mono_debug_format != MONO_DEBUG_FORMAT_NONE) 
12328                         //mono_debug_add_wrapper (method, nm);
12329         } else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
12330                 const char *name = method->name;
12331                 MonoMethod *nm;
12332
12333                 if (method->klass->parent == mono_defaults.multicastdelegate_class) {
12334                         if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
12335                                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name ("mono_delegate_ctor");
12336                                 g_assert (mi);
12337                                 return mono_get_addr_from_ftnptr ((gpointer)mono_icall_get_wrapper (mi));
12338                         } else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
12339 #ifdef MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE
12340                                 return mono_create_delegate_trampoline (method->klass);
12341 #else
12342                                 nm = mono_marshal_get_delegate_invoke (method, NULL);
12343                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
12344 #endif
12345                         } else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
12346                                 nm = mono_marshal_get_delegate_begin_invoke (method);
12347                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
12348                         } else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
12349                                 nm = mono_marshal_get_delegate_end_invoke (method);
12350                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
12351                         }
12352                 }
12353                 return NULL;
12354         }
12355
12356         cfg = mini_method_compile (method, opt, target_domain, TRUE, FALSE, 0);
12357
12358         switch (cfg->exception_type) {
12359         case MONO_EXCEPTION_NONE: break;
12360         case MONO_EXCEPTION_TYPE_LOAD:
12361         case MONO_EXCEPTION_MISSING_FIELD:
12362         case MONO_EXCEPTION_MISSING_METHOD:
12363         case MONO_EXCEPTION_FILE_NOT_FOUND: {
12364                 /* Throw a type load exception if needed */
12365                 MonoLoaderError *error = mono_loader_get_last_error ();
12366                 MonoException *ex;
12367
12368                 if (error) {
12369                         ex = mono_loader_error_prepare_exception (error);
12370                 } else {
12371                         if (cfg->exception_ptr) {
12372                                 ex = mono_class_get_exception_for_failure (cfg->exception_ptr);
12373                         } else {
12374                                 if (cfg->exception_type == MONO_EXCEPTION_MISSING_FIELD)
12375                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingFieldException", cfg->exception_message);
12376                                 else if (cfg->exception_type == MONO_EXCEPTION_MISSING_METHOD)
12377                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingMethodException", cfg->exception_message);
12378                                 else if (cfg->exception_type == MONO_EXCEPTION_TYPE_LOAD)
12379                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "TypeLoadException", cfg->exception_message);
12380                                 else if (cfg->exception_type == MONO_EXCEPTION_FILE_NOT_FOUND)
12381                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "FileNotFoundException", cfg->exception_message);
12382                                 else
12383                                         g_assert_not_reached ();
12384                         }
12385                 }
12386                 mono_destroy_compile (cfg);
12387                 mono_raise_exception (ex);
12388                 break;
12389         }
12390         case MONO_EXCEPTION_INVALID_PROGRAM: {
12391                 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "InvalidProgramException", cfg->exception_message);
12392                 mono_destroy_compile (cfg);
12393                 mono_raise_exception (ex);
12394                 break;
12395         }
12396         case MONO_EXCEPTION_UNVERIFIABLE_IL: {
12397                 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System.Security", "VerificationException", cfg->exception_message);
12398                 mono_destroy_compile (cfg);
12399                 mono_raise_exception (ex);
12400                 break;
12401         }
12402         case MONO_EXCEPTION_METHOD_ACCESS: {
12403                 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MethodAccessException", cfg->exception_message);
12404                 mono_destroy_compile (cfg);
12405                 mono_raise_exception (ex);
12406                 break;
12407         }
12408         case MONO_EXCEPTION_FIELD_ACCESS: {
12409                 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "FieldAccessException", cfg->exception_message);
12410                 mono_destroy_compile (cfg);
12411                 mono_raise_exception (ex);
12412                 break;
12413         }
12414         /* this can only be set if the security manager is active */
12415         case MONO_EXCEPTION_SECURITY_LINKDEMAND: {
12416                 MonoSecurityManager* secman = mono_security_manager_get_methods ();
12417                 MonoObject *exc = NULL;
12418                 gpointer args [2];
12419
12420                 args [0] = &cfg->exception_data;
12421                 args [1] = &method;
12422                 mono_runtime_invoke (secman->linkdemandsecurityexception, NULL, args, &exc);
12423
12424                 mono_destroy_compile (cfg);
12425                 cfg = NULL;
12426
12427                 mono_raise_exception ((MonoException*)exc);
12428         }
12429         default:
12430                 g_assert_not_reached ();
12431         }
12432
12433         mono_domain_lock (target_domain);
12434
12435         /* Check if some other thread already did the job. In this case, we can
12436        discard the code this thread generated. */
12437
12438         if ((info = lookup_method (target_domain, method))) {
12439                 /* We can't use a domain specific method in another domain */
12440                 if ((target_domain == mono_domain_get ()) || info->domain_neutral) {
12441                         code = info->code_start;
12442 //                      printf("Discarding code for method %s\n", method->name);
12443                 }
12444         }
12445         
12446         if (code == NULL) {
12447                 mono_internal_hash_table_insert (&target_domain->jit_code_hash, method, cfg->jit_info);
12448                 code = cfg->native_code;
12449
12450                 if (cfg->generic_sharing_context && mono_method_is_generic_sharable_impl (method)) {
12451                         /* g_print ("inserting method %s.%s.%s\n", method->klass->name_space, method->klass->name, method->name); */
12452                         mono_domain_register_shared_generic (target_domain, 
12453                                 mono_method_get_declaring_generic_method (method), cfg->jit_info);
12454                         mono_stats.generics_shared_methods++;
12455                 }
12456         }
12457
12458         mono_destroy_compile (cfg);
12459
12460         if (target_domain->jump_target_hash) {
12461                 MonoJumpInfo patch_info;
12462                 GSList *list, *tmp;
12463                 list = g_hash_table_lookup (target_domain->jump_target_hash, method);
12464                 if (list) {
12465                         patch_info.next = NULL;
12466                         patch_info.ip.i = 0;
12467                         patch_info.type = MONO_PATCH_INFO_METHOD_JUMP;
12468                         patch_info.data.method = method;
12469                         g_hash_table_remove (target_domain->jump_target_hash, method);
12470                 }
12471                 for (tmp = list; tmp; tmp = tmp->next)
12472                         mono_arch_patch_code (NULL, target_domain, tmp->data, &patch_info, TRUE);
12473                 g_slist_free (list);
12474         }
12475
12476         mono_domain_unlock (target_domain);
12477
12478         mono_runtime_class_init (mono_class_vtable (target_domain, method->klass));
12479         return code;
12480 }
12481
12482 static gpointer
12483 mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt)
12484 {
12485         MonoDomain *target_domain, *domain = mono_domain_get ();
12486         MonoJitInfo *info;
12487         gpointer p;
12488         MonoJitICallInfo *callinfo = NULL;
12489
12490         /*
12491          * ICALL wrappers are handled specially, since there is only one copy of them
12492          * shared by all appdomains.
12493          */
12494         if ((method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && (strstr (method->name, "__icall_wrapper_") == method->name)) {
12495                 const char *icall_name;
12496
12497                 icall_name = method->name + strlen ("__icall_wrapper_");
12498                 g_assert (icall_name);
12499                 callinfo = mono_find_jit_icall_by_name (icall_name);
12500                 g_assert (callinfo);
12501
12502                 /* Must be domain neutral since there is only one copy */
12503                 opt |= MONO_OPT_SHARED;
12504         }
12505
12506         if (opt & MONO_OPT_SHARED)
12507                 target_domain = mono_get_root_domain ();
12508         else 
12509                 target_domain = domain;
12510
12511         mono_domain_lock (target_domain);
12512
12513         if ((info = lookup_method (target_domain, method))) {
12514                 /* We can't use a domain specific method in another domain */
12515                 if (! ((domain != target_domain) && !info->domain_neutral)) {
12516                         mono_domain_unlock (target_domain);
12517                         mono_jit_stats.methods_lookups++;
12518                         mono_runtime_class_init (mono_class_vtable (domain, method->klass));
12519                         return mono_create_ftnptr (target_domain, info->code_start);
12520                 }
12521         }
12522
12523         mono_domain_unlock (target_domain);
12524         p = mono_create_ftnptr (target_domain, mono_jit_compile_method_inner (method, target_domain, opt));
12525
12526         if (callinfo) {
12527                 mono_jit_lock ();
12528                 if (!callinfo->wrapper) {
12529                         callinfo->wrapper = p;
12530                         mono_register_jit_icall_wrapper (callinfo, p);
12531                         mono_debug_add_icall_wrapper (method, callinfo);
12532                 }
12533                 mono_jit_unlock ();
12534         }
12535
12536         return p;
12537 }
12538
12539 static gpointer
12540 mono_jit_compile_method (MonoMethod *method)
12541 {
12542         return mono_jit_compile_method_with_opt (method, default_opt);
12543 }
12544
12545 static void
12546 invalidated_delegate_trampoline (char *desc)
12547 {
12548         g_error ("Unmanaged code called delegate of type %s which was already garbage collected.\n"
12549                  "See http://www.go-mono.com/delegate.html for an explanation and ways to fix this.",
12550                  desc);
12551 }
12552
12553 /*
12554  * mono_jit_free_method:
12555  *
12556  *  Free all memory allocated by the JIT for METHOD.
12557  */
12558 static void
12559 mono_jit_free_method (MonoDomain *domain, MonoMethod *method)
12560 {
12561         MonoJitDynamicMethodInfo *ji;
12562         gboolean destroy = TRUE;
12563
12564         g_assert (method->dynamic);
12565
12566         mono_domain_lock (domain);
12567         ji = mono_dynamic_code_hash_lookup (domain, method);
12568         mono_domain_unlock (domain);
12569
12570         if (!ji)
12571                 return;
12572         mono_domain_lock (domain);
12573         g_hash_table_remove (domain->dynamic_code_hash, method);
12574         mono_internal_hash_table_remove (&domain->jit_code_hash, method);
12575         g_hash_table_remove (domain->jump_trampoline_hash, method);
12576         mono_domain_unlock (domain);
12577
12578 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
12579         if (debug_options.keep_delegates && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
12580                 /*
12581                  * Instead of freeing the code, change it to call an error routine
12582                  * so people can fix their code.
12583                  */
12584                 char *type = mono_type_full_name (&method->klass->byval_arg);
12585                 char *type_and_method = g_strdup_printf ("%s.%s", type, method->name);
12586
12587                 g_free (type);
12588                 mono_arch_invalidate_method (ji->ji, invalidated_delegate_trampoline, type_and_method);
12589                 destroy = FALSE;
12590         }
12591 #endif
12592
12593         /* 
12594          * This needs to be done before freeing code_mp, since the code address is the
12595          * key in the table, so if we free the code_mp first, another thread can grab the
12596          * same code address and replace our entry in the table.
12597          */
12598         mono_jit_info_table_remove (domain, ji->ji);
12599
12600         if (destroy)
12601                 mono_code_manager_destroy (ji->code_mp);
12602         mono_thread_hazardous_free_or_queue (ji->ji, g_free);
12603         g_free (ji);
12604 }
12605
12606 gpointer
12607 mono_jit_find_compiled_method (MonoDomain *domain, MonoMethod *method)
12608 {
12609         MonoDomain *target_domain;
12610         MonoJitInfo *info;
12611
12612         if (default_opt & MONO_OPT_SHARED)
12613                 target_domain = mono_get_root_domain ();
12614         else 
12615                 target_domain = domain;
12616
12617         mono_domain_lock (target_domain);
12618
12619         if ((info = lookup_method (target_domain, method))) {
12620                 /* We can't use a domain specific method in another domain */
12621                 if (! ((domain != target_domain) && !info->domain_neutral)) {
12622                         mono_domain_unlock (target_domain);
12623                         mono_jit_stats.methods_lookups++;
12624                         return info->code_start;
12625                 }
12626         }
12627
12628         mono_domain_unlock (target_domain);
12629
12630         return NULL;
12631 }
12632
12633 /**
12634  * mono_jit_runtime_invoke:
12635  * @method: the method to invoke
12636  * @obj: this pointer
12637  * @params: array of parameter values.
12638  * @exc: used to catch exceptions objects
12639  */
12640 static MonoObject*
12641 mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
12642 {
12643         MonoMethod *to_compile;
12644         MonoMethod *invoke;
12645         MonoObject *(*runtime_invoke) (MonoObject *this, void **params, MonoObject **exc, void* compiled_method);
12646         void* compiled_method;
12647
12648         if (obj == NULL && !(method->flags & METHOD_ATTRIBUTE_STATIC) && !method->string_ctor && (method->wrapper_type == 0)) {
12649                 g_warning ("Ignoring invocation of an instance method on a NULL instance.\n");
12650                 return NULL;
12651         }
12652
12653         if ((method->flags & METHOD_ATTRIBUTE_STATIC) &&
12654                         mono_class_generic_sharing_enabled (method->klass) &&
12655                         mono_method_is_generic_sharable_impl (method)) {
12656                 to_compile = mono_marshal_get_static_rgctx_invoke (method);
12657         } else {
12658                 to_compile = method;
12659         }
12660
12661         invoke = mono_marshal_get_runtime_invoke (method);
12662         runtime_invoke = mono_jit_compile_method (invoke);
12663         
12664         /* We need this here becuase mono_marshal_get_runtime_invoke can be place 
12665          * the helper method in System.Object and not the target class
12666          */
12667         mono_runtime_class_init (mono_class_vtable (mono_domain_get (), method->klass));
12668
12669         if (method->klass->rank && (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
12670                 (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
12671                 /* 
12672                  * Array Get/Set/Address methods. The JIT implements them using inline code 
12673                  * inside the runtime invoke wrappers, so no need to compile them.
12674                  */
12675                 compiled_method = NULL;
12676         } else {
12677                 compiled_method = mono_jit_compile_method (to_compile);
12678         }
12679         return runtime_invoke (obj, params, exc, compiled_method);
12680 }
12681
12682 #ifdef MONO_GET_CONTEXT
12683 #define GET_CONTEXT MONO_GET_CONTEXT
12684 #endif
12685
12686 #ifndef GET_CONTEXT
12687 #ifdef PLATFORM_WIN32
12688 #define GET_CONTEXT \
12689         struct sigcontext *ctx = (struct sigcontext*)_dummy;
12690 #else
12691 #ifdef MONO_ARCH_USE_SIGACTION
12692 #define GET_CONTEXT \
12693     void *ctx = context;
12694 #elif defined(__sparc__)
12695 #define GET_CONTEXT \
12696     void *ctx = sigctx;
12697 #else
12698 #define GET_CONTEXT \
12699         void **_p = (void **)&_dummy; \
12700         struct sigcontext *ctx = (struct sigcontext *)++_p;
12701 #endif
12702 #endif
12703 #endif
12704
12705 #ifdef MONO_ARCH_USE_SIGACTION
12706 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy, siginfo_t *info, void *context)
12707 #elif defined(__sparc__)
12708 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy, void *sigctx)
12709 #else
12710 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy)
12711 #endif
12712
12713 static void
12714 SIG_HANDLER_SIGNATURE (sigfpe_signal_handler)
12715 {
12716         MonoException *exc = NULL;
12717 #ifndef MONO_ARCH_USE_SIGACTION
12718         void *info = NULL;
12719 #endif
12720         GET_CONTEXT;
12721
12722 #if defined(MONO_ARCH_HAVE_IS_INT_OVERFLOW)
12723         if (mono_arch_is_int_overflow (ctx, info))
12724                 exc = mono_get_exception_arithmetic ();
12725         else
12726                 exc = mono_get_exception_divide_by_zero ();
12727 #else
12728         exc = mono_get_exception_divide_by_zero ();
12729 #endif
12730         
12731         mono_arch_handle_exception (ctx, exc, FALSE);
12732 }
12733
12734 static void
12735 SIG_HANDLER_SIGNATURE (sigill_signal_handler)
12736 {
12737         MonoException *exc;
12738         GET_CONTEXT;
12739
12740         exc = mono_get_exception_execution_engine ("SIGILL");
12741         
12742         mono_arch_handle_exception (ctx, exc, FALSE);
12743 }
12744
12745 static void
12746 SIG_HANDLER_SIGNATURE (sigsegv_signal_handler)
12747 {
12748 #ifndef MONO_ARCH_SIGSEGV_ON_ALTSTACK
12749         MonoException *exc = NULL;
12750 #endif
12751         MonoJitInfo *ji;
12752
12753 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
12754         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
12755 #endif
12756         GET_CONTEXT;
12757
12758 #ifdef MONO_ARCH_USE_SIGACTION
12759         if (debug_options.collect_pagefault_stats) {
12760                 if (mono_raw_buffer_is_pagefault (info->si_addr)) {
12761                         mono_raw_buffer_handle_pagefault (info->si_addr);
12762                         return;
12763                 }
12764                 if (mono_aot_is_pagefault (info->si_addr)) {
12765                         mono_aot_handle_pagefault (info->si_addr);
12766                         return;
12767                 }
12768         }
12769 #endif
12770
12771         ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context (ctx));
12772
12773 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
12774         /* we got a stack overflow in the soft-guard pages
12775          * There are two cases:
12776          * 1) managed code caused the overflow: we unprotect the soft-guard page
12777          * and let the arch-specific code trigger the exception handling mechanism
12778          * in the thread stack. The soft-guard pages will be protected again as the stack is unwound.
12779          * 2) unmanaged code caused the overflow: we unprotect the soft-guard page
12780          * and hope we can continue with those enabled, at least until the hard-guard page
12781          * is hit. The alternative to continuing here is to just print a message and abort.
12782          * We may add in the future the code to protect the pages again in the codepath
12783          * when we return from unmanaged to managed code.
12784          */
12785         if (jit_tls->stack_ovf_guard_size && (guint8*)info->si_addr >= (guint8*)jit_tls->stack_ovf_guard_base &&
12786                         (guint8*)info->si_addr < (guint8*)jit_tls->stack_ovf_guard_base + jit_tls->stack_ovf_guard_size) {
12787                 mono_mprotect (jit_tls->stack_ovf_guard_base, jit_tls->stack_ovf_guard_size, MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
12788                 if (ji) {
12789                         mono_arch_handle_altstack_exception (ctx, info->si_addr, TRUE);
12790                 } else {
12791                         /* We print a message: after this even managed stack overflows
12792                          * may crash the runtime
12793                          */
12794                         fprintf (stderr, "Stack overflow in unmanaged: IP: %p, fault addr: %p\n", mono_arch_ip_from_context (ctx), (gpointer)info->si_addr);
12795                 }
12796                 return;
12797         }
12798         /* The hard-guard page has been hit: there is not much we can do anymore
12799          * Print a hopefully clear message and abort.
12800          */
12801         if (jit_tls->stack_size && 
12802                         ABS ((guint8*)info->si_addr - ((guint8*)jit_tls->end_of_stack - jit_tls->stack_size)) < 32768) {
12803                 const char *method;
12804                 /* we don't do much now, but we can warn the user with a useful message */
12805                 fprintf (stderr, "Stack overflow: IP: %p, fault addr: %p\n", mono_arch_ip_from_context (ctx), (gpointer)info->si_addr);
12806                 if (ji && ji->method)
12807                         method = mono_method_full_name (ji->method, TRUE);
12808                 else
12809                         method = "Unmanaged";
12810                 fprintf (stderr, "At %s\n", method);
12811                 abort ();
12812         } else {
12813                 mono_arch_handle_altstack_exception (ctx, info->si_addr, FALSE);
12814         }
12815 #else
12816
12817         if (!ji) {
12818                 mono_handle_native_sigsegv (SIGSEGV, ctx);
12819         }
12820                         
12821         mono_arch_handle_exception (ctx, exc, FALSE);
12822 #endif
12823 }
12824
12825 #ifndef PLATFORM_WIN32
12826
12827 static void
12828 SIG_HANDLER_SIGNATURE (sigabrt_signal_handler)
12829 {
12830         MonoJitInfo *ji;
12831         GET_CONTEXT;
12832
12833         ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
12834         if (!ji) {
12835                 mono_handle_native_sigsegv (SIGABRT, ctx);
12836         }
12837 }
12838
12839 static void
12840 SIG_HANDLER_SIGNATURE (sigusr1_signal_handler)
12841 {
12842         gboolean running_managed;
12843         MonoException *exc;
12844         MonoThread *thread = mono_thread_current ();
12845         void *ji;
12846         
12847         GET_CONTEXT;
12848
12849         if (thread->thread_dump_requested) {
12850                 thread->thread_dump_requested = FALSE;
12851
12852                 mono_print_thread_dump (ctx);
12853         }
12854
12855         /*
12856          * FIXME:
12857          * This is an async signal, so the code below must not call anything which
12858          * is not async safe. That includes the pthread locking functions. If we
12859          * know that we interrupted managed code, then locking is safe.
12860          */
12861         ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
12862         running_managed = ji != NULL;
12863         
12864         exc = mono_thread_request_interruption (running_managed); 
12865         if (!exc) return;
12866
12867         mono_arch_handle_exception (ctx, exc, FALSE);
12868 }
12869
12870 static void
12871 SIG_HANDLER_SIGNATURE (sigprof_signal_handler)
12872 {
12873         GET_CONTEXT;
12874
12875         mono_profiler_stat_hit (mono_arch_ip_from_context (ctx), ctx);
12876 }
12877
12878 static void
12879 SIG_HANDLER_SIGNATURE (sigquit_signal_handler)
12880 {
12881         GET_CONTEXT;
12882
12883         printf ("Full thread dump:\n");
12884
12885         mono_threads_request_thread_dump ();
12886
12887         /*
12888          * print_thread_dump () skips the current thread, since sending a signal
12889          * to it would invoke the signal handler below the sigquit signal handler,
12890          * and signal handlers don't create an lmf, so the stack walk could not
12891          * be performed.
12892          */
12893         mono_print_thread_dump (ctx);
12894 }
12895
12896 static void
12897 SIG_HANDLER_SIGNATURE (sigusr2_signal_handler)
12898 {
12899         gboolean enabled = mono_trace_is_enabled ();
12900
12901         mono_trace_enable (!enabled);
12902 }
12903
12904 #endif
12905
12906 static void
12907 SIG_HANDLER_SIGNATURE (sigint_signal_handler)
12908 {
12909         MonoException *exc;
12910         GET_CONTEXT;
12911
12912         exc = mono_get_exception_execution_engine ("Interrupted (SIGINT).");
12913         
12914         mono_arch_handle_exception (ctx, exc, FALSE);
12915 }
12916
12917 #ifdef PLATFORM_MACOSX
12918
12919 /*
12920  * This code disables the CrashReporter of MacOS X by installing
12921  * a dummy Mach exception handler.
12922  */
12923
12924 /*
12925  * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/exc_server.html
12926  */
12927 extern
12928 boolean_t
12929 exc_server (mach_msg_header_t *request_msg,
12930             mach_msg_header_t *reply_msg);
12931
12932 /*
12933  * The exception message
12934  */
12935 typedef struct {
12936         mach_msg_base_t msg;  /* common mach message header */
12937         char payload [1024];  /* opaque */
12938 } mach_exception_msg_t;
12939
12940 /* The exception port */
12941 static mach_port_t mach_exception_port = VM_MAP_NULL;
12942
12943 /*
12944  * Implicitly called by exc_server. Must be public.
12945  *
12946  * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/catch_exception_raise.html
12947  */
12948 kern_return_t
12949 catch_exception_raise (
12950         mach_port_t exception_port,
12951         mach_port_t thread,
12952         mach_port_t task,
12953         exception_type_t exception,
12954         exception_data_t code,
12955         mach_msg_type_number_t code_count)
12956 {
12957         /* consume the exception */
12958         return KERN_FAILURE;
12959 }
12960
12961 /*
12962  * Exception thread handler.
12963  */
12964 static
12965 void *
12966 mach_exception_thread (void *arg)
12967 {
12968         for (;;) {
12969                 mach_exception_msg_t request;
12970                 mach_exception_msg_t reply;
12971                 mach_msg_return_t result;
12972
12973                 /* receive from "mach_exception_port" */
12974                 result = mach_msg (&request.msg.header,
12975                                    MACH_RCV_MSG | MACH_RCV_LARGE,
12976                                    0,
12977                                    sizeof (request),
12978                                    mach_exception_port,
12979                                    MACH_MSG_TIMEOUT_NONE,
12980                                    MACH_PORT_NULL);
12981
12982                 g_assert (result == MACH_MSG_SUCCESS);
12983
12984                 /* dispatch to catch_exception_raise () */
12985                 exc_server (&request.msg.header, &reply.msg.header);
12986
12987                 /* send back to sender */
12988                 result = mach_msg (&reply.msg.header,
12989                                    MACH_SEND_MSG,
12990                                    reply.msg.header.msgh_size,
12991                                    0,
12992                                    MACH_PORT_NULL,
12993                                    MACH_MSG_TIMEOUT_NONE,
12994                                    MACH_PORT_NULL);
12995
12996                 g_assert (result == MACH_MSG_SUCCESS);
12997         }
12998         return NULL;
12999 }
13000
13001 static void
13002 macosx_register_exception_handler ()
13003 {
13004         mach_port_t task;
13005         pthread_attr_t attr;
13006         pthread_t thread;
13007
13008         if (mach_exception_port != VM_MAP_NULL)
13009                 return;
13010
13011         task = mach_task_self ();
13012
13013         /* create the "mach_exception_port" with send & receive rights */
13014         g_assert (mach_port_allocate (task, MACH_PORT_RIGHT_RECEIVE,
13015                                       &mach_exception_port) == KERN_SUCCESS);
13016         g_assert (mach_port_insert_right (task, mach_exception_port, mach_exception_port,
13017                                           MACH_MSG_TYPE_MAKE_SEND) == KERN_SUCCESS);
13018
13019         /* create the exception handler thread */
13020         g_assert (!pthread_attr_init (&attr));
13021         g_assert (!pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED));
13022         g_assert (!pthread_create (&thread, &attr, mach_exception_thread, NULL));
13023         pthread_attr_destroy (&attr);
13024
13025         /*
13026          * register "mach_exception_port" as a receiver for the
13027          * EXC_BAD_ACCESS exception
13028          *
13029          * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/task_set_exception_ports.html
13030          */
13031         g_assert (task_set_exception_ports (task, EXC_MASK_BAD_ACCESS,
13032                                             mach_exception_port,
13033                                             EXCEPTION_DEFAULT,
13034                                             MACHINE_THREAD_STATE) == KERN_SUCCESS);
13035 }
13036 #endif
13037
13038 #ifndef PLATFORM_WIN32
13039 static void
13040 add_signal_handler (int signo, gpointer handler)
13041 {
13042         struct sigaction sa;
13043
13044 #ifdef MONO_ARCH_USE_SIGACTION
13045         sa.sa_sigaction = handler;
13046         sigemptyset (&sa.sa_mask);
13047         sa.sa_flags = SA_SIGINFO;
13048 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
13049         if (signo == SIGSEGV)
13050                 sa.sa_flags |= SA_ONSTACK;
13051 #endif
13052 #else
13053         sa.sa_handler = handler;
13054         sigemptyset (&sa.sa_mask);
13055         sa.sa_flags = 0;
13056 #endif
13057         g_assert (sigaction (signo, &sa, NULL) != -1);
13058 }
13059
13060 static void
13061 remove_signal_handler (int signo)
13062 {
13063         struct sigaction sa;
13064
13065         sa.sa_handler = SIG_DFL;
13066         sigemptyset (&sa.sa_mask);
13067         sa.sa_flags = 0;
13068
13069         g_assert (sigaction (signo, &sa, NULL) != -1);
13070 }
13071 #endif
13072
13073 static void
13074 mono_runtime_install_handlers (void)
13075 {
13076 #ifdef PLATFORM_WIN32
13077         win32_seh_init();
13078         win32_seh_set_handler(SIGFPE, sigfpe_signal_handler);
13079         win32_seh_set_handler(SIGILL, sigill_signal_handler);
13080         win32_seh_set_handler(SIGSEGV, sigsegv_signal_handler);
13081         if (debug_options.handle_sigint)
13082                 win32_seh_set_handler(SIGINT, sigint_signal_handler);
13083
13084 #else /* !PLATFORM_WIN32 */
13085
13086
13087 #ifdef PLATFORM_MACOSX
13088         macosx_register_exception_handler ();
13089 #endif
13090
13091         if (debug_options.handle_sigint)
13092                 add_signal_handler (SIGINT, sigint_signal_handler);
13093
13094         add_signal_handler (SIGFPE, sigfpe_signal_handler);
13095         add_signal_handler (SIGQUIT, sigquit_signal_handler);
13096         add_signal_handler (SIGILL, sigill_signal_handler);
13097         add_signal_handler (SIGBUS, sigsegv_signal_handler);
13098         if (mono_jit_trace_calls != NULL)
13099                 add_signal_handler (SIGUSR2, sigusr2_signal_handler);
13100
13101         add_signal_handler (mono_thread_get_abort_signal (), sigusr1_signal_handler);
13102         signal (SIGPIPE, SIG_IGN);
13103
13104         add_signal_handler (SIGABRT, sigabrt_signal_handler);
13105
13106         /* catch SIGSEGV */
13107         add_signal_handler (SIGSEGV, sigsegv_signal_handler);
13108 #endif /* PLATFORM_WIN32 */
13109 }
13110
13111 static void
13112 mono_runtime_cleanup_handlers (void)
13113 {
13114 #ifdef PLATFORM_WIN32
13115         win32_seh_cleanup();
13116 #else
13117         if (debug_options.handle_sigint)
13118                 remove_signal_handler (SIGINT);
13119
13120         remove_signal_handler (SIGFPE);
13121         remove_signal_handler (SIGQUIT);
13122         remove_signal_handler (SIGILL);
13123         remove_signal_handler (SIGBUS);
13124         if (mono_jit_trace_calls != NULL)
13125                 remove_signal_handler (SIGUSR2);
13126
13127         remove_signal_handler (mono_thread_get_abort_signal ());
13128
13129         remove_signal_handler (SIGABRT);
13130
13131         remove_signal_handler (SIGSEGV);
13132 #endif /* PLATFORM_WIN32 */
13133 }
13134
13135
13136 #ifdef HAVE_LINUX_RTC_H
13137 #include <linux/rtc.h>
13138 #include <sys/ioctl.h>
13139 #include <fcntl.h>
13140 static int rtc_fd = -1;
13141
13142 static int
13143 enable_rtc_timer (gboolean enable)
13144 {
13145         int flags;
13146         flags = fcntl (rtc_fd, F_GETFL);
13147         if (flags < 0) {
13148                 perror ("getflags");
13149                 return 0;
13150         }
13151         if (enable)
13152                 flags |= FASYNC;
13153         else
13154                 flags &= ~FASYNC;
13155         if (fcntl (rtc_fd, F_SETFL, flags) == -1) {
13156                 perror ("setflags");
13157                 return 0;
13158         }
13159         return 1;
13160 }
13161 #endif
13162
13163 #ifdef PLATFORM_WIN32
13164 static HANDLE win32_main_thread;
13165 static MMRESULT win32_timer;
13166
13167 static void CALLBACK
13168 win32_time_proc (UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2)
13169 {
13170         CONTEXT context;
13171
13172         context.ContextFlags = CONTEXT_CONTROL;
13173         if (GetThreadContext (win32_main_thread, &context)) {
13174 #ifdef _WIN64
13175                 mono_profiler_stat_hit ((guchar *) context.Rip, &context);
13176 #else
13177                 mono_profiler_stat_hit ((guchar *) context.Eip, &context);
13178 #endif
13179         }
13180 }
13181 #endif
13182
13183 static void
13184 setup_stat_profiler (void)
13185 {
13186 #ifdef ITIMER_PROF
13187         struct itimerval itval;
13188         static int inited = 0;
13189 #ifdef HAVE_LINUX_RTC_H
13190         const char *rtc_freq;
13191         if (!inited && (rtc_freq = g_getenv ("MONO_RTC"))) {
13192                 int freq = 0;
13193                 inited = 1;
13194                 if (*rtc_freq)
13195                         freq = atoi (rtc_freq);
13196                 if (!freq)
13197                         freq = 1024;
13198                 rtc_fd = open ("/dev/rtc", O_RDONLY);
13199                 if (rtc_fd == -1) {
13200                         perror ("open /dev/rtc");
13201                         return;
13202                 }
13203                 add_signal_handler (SIGPROF, sigprof_signal_handler);
13204                 if (ioctl (rtc_fd, RTC_IRQP_SET, freq) == -1) {
13205                         perror ("set rtc freq");
13206                         return;
13207                 }
13208                 if (ioctl (rtc_fd, RTC_PIE_ON, 0) == -1) {
13209                         perror ("start rtc");
13210                         return;
13211                 }
13212                 if (fcntl (rtc_fd, F_SETSIG, SIGPROF) == -1) {
13213                         perror ("setsig");
13214                         return;
13215                 }
13216                 if (fcntl (rtc_fd, F_SETOWN, getpid ()) == -1) {
13217                         perror ("setown");
13218                         return;
13219                 }
13220                 enable_rtc_timer (TRUE);
13221                 return;
13222         }
13223         if (rtc_fd >= 0)
13224                 return;
13225 #endif
13226
13227         itval.it_interval.tv_usec = 999;
13228         itval.it_interval.tv_sec = 0;
13229         itval.it_value = itval.it_interval;
13230         setitimer (ITIMER_PROF, &itval, NULL);
13231         if (inited)
13232                 return;
13233         inited = 1;
13234         add_signal_handler (SIGPROF, sigprof_signal_handler);
13235 #elif defined (PLATFORM_WIN32)
13236         static int inited = 0;
13237         TIMECAPS timecaps;
13238
13239         if (inited)
13240                 return;
13241
13242         inited = 1;
13243         if (timeGetDevCaps (&timecaps, sizeof (timecaps)) != TIMERR_NOERROR)
13244                 return;
13245
13246         if ((win32_main_thread = OpenThread (READ_CONTROL | THREAD_GET_CONTEXT, FALSE, GetCurrentThreadId ())) == NULL)
13247                 return;
13248
13249         if (timeBeginPeriod (1) != TIMERR_NOERROR)
13250                 return;
13251
13252         if ((win32_timer = timeSetEvent (1, 0, win32_time_proc, 0, TIME_PERIODIC)) == 0) {
13253                 timeEndPeriod (1);
13254                 return;
13255         }
13256 #endif
13257 }
13258
13259 /* mono_jit_create_remoting_trampoline:
13260  * @method: pointer to the method info
13261  *
13262  * Creates a trampoline which calls the remoting functions. This
13263  * is used in the vtable of transparent proxies.
13264  * 
13265  * Returns: a pointer to the newly created code 
13266  */
13267 static gpointer
13268 mono_jit_create_remoting_trampoline (MonoMethod *method, MonoRemotingTarget target)
13269 {
13270         MonoMethod *nm;
13271         guint8 *addr = NULL;
13272
13273         if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) || 
13274             (mono_method_signature (method)->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class))) {
13275                 nm = mono_marshal_get_remoting_invoke_for_target (method, target);
13276                 addr = mono_compile_method (nm);
13277         } else {
13278                 addr = mono_compile_method (method);
13279         }
13280         return mono_get_addr_from_ftnptr (addr);
13281 }
13282
13283 #ifdef MONO_ARCH_HAVE_IMT
13284 static gpointer
13285 mini_get_imt_trampoline (void)
13286 {
13287         static gpointer tramp = NULL;
13288         if (!tramp)
13289                 tramp =  mono_arch_create_specific_trampoline (MONO_FAKE_IMT_METHOD, MONO_TRAMPOLINE_GENERIC, mono_get_root_domain (), NULL);
13290         return tramp;
13291 }
13292 #endif
13293
13294 #ifdef MONO_ARCH_COMMON_VTABLE_TRAMPOLINE
13295 gpointer
13296 mini_get_vtable_trampoline (void)
13297 {
13298         static gpointer tramp = NULL;
13299         if (!tramp)
13300                 tramp =  mono_arch_create_specific_trampoline (MONO_FAKE_VTABLE_METHOD, MONO_TRAMPOLINE_GENERIC, mono_get_root_domain (), NULL);
13301         return tramp;
13302 }
13303 #endif
13304
13305 static void
13306 mini_parse_debug_options (void)
13307 {
13308         char *options = getenv ("MONO_DEBUG");
13309         gchar **args, **ptr;
13310         
13311         if (!options)
13312                 return;
13313
13314         args = g_strsplit (options, ",", -1);
13315
13316         for (ptr = args; ptr && *ptr; ptr++) {
13317                 const char *arg = *ptr;
13318
13319                 if (!strcmp (arg, "handle-sigint"))
13320                         debug_options.handle_sigint = TRUE;
13321                 else if (!strcmp (arg, "keep-delegates"))
13322                         debug_options.keep_delegates = TRUE;
13323                 else if (!strcmp (arg, "collect-pagefault-stats"))
13324                         debug_options.collect_pagefault_stats = TRUE;
13325                 else if (!strcmp (arg, "break-on-unverified"))
13326                         debug_options.break_on_unverified = TRUE;
13327                 else {
13328                         fprintf (stderr, "Invalid option for the MONO_DEBUG env variable: %s\n", arg);
13329                         fprintf (stderr, "Available options: 'handle-sigint', 'keep-delegates', 'collect-pagefault-stats', 'break-on-unverified'\n");
13330                         exit (1);
13331                 }
13332         }
13333 }
13334
13335 MonoDomain *
13336 mini_init (const char *filename, const char *runtime_version)
13337 {
13338         MonoDomain *domain;
13339
13340 #ifdef __linux__
13341         if (access ("/proc/self/maps", F_OK) != 0) {
13342                 g_print ("Mono requires /proc to be mounted.\n");
13343                 exit (1);
13344         }
13345 #endif
13346
13347         /* Happens when using the embedding interface */
13348         if (!default_opt_set)
13349                 default_opt = mono_parse_default_optimizations (NULL);
13350
13351         InitializeCriticalSection (&jit_mutex);
13352
13353         if (!global_codeman)
13354                 global_codeman = mono_code_manager_new ();
13355         jit_icall_name_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
13356
13357         mono_arch_cpu_init ();
13358
13359         mono_arch_init ();
13360
13361         mono_trampolines_init ();
13362
13363         mono_exceptions_init ();
13364
13365         if (!g_thread_supported ())
13366                 g_thread_init (NULL);
13367
13368         if (getenv ("MONO_DEBUG") != NULL)
13369                 mini_parse_debug_options ();
13370
13371         mono_gc_base_init ();
13372
13373         mono_jit_tls_id = TlsAlloc ();
13374         setup_jit_tls_data ((gpointer)-1, mono_thread_abort);
13375
13376         mono_burg_init ();
13377
13378         if (default_opt & MONO_OPT_AOT)
13379                 mono_aot_init ();
13380
13381         mono_runtime_install_handlers ();
13382         mono_threads_install_cleanup (mini_thread_cleanup);
13383
13384 #ifdef MONO_ARCH_HAVE_NOTIFY_PENDING_EXC
13385         // This is experimental code so provide an env var to switch it off
13386         if (getenv ("MONO_DISABLE_PENDING_EXCEPTIONS")) {
13387                 printf ("MONO_DISABLE_PENDING_EXCEPTIONS env var set.\n");
13388         } else {
13389                 check_for_pending_exc = FALSE;
13390                 mono_threads_install_notify_pending_exc (mono_arch_notify_pending_exc);
13391         }
13392 #endif
13393
13394 #define JIT_TRAMPOLINES_WORK
13395 #ifdef JIT_TRAMPOLINES_WORK
13396         mono_install_compile_method (mono_jit_compile_method);
13397         mono_install_free_method (mono_jit_free_method);
13398         mono_install_trampoline (mono_create_jit_trampoline);
13399         mono_install_jump_trampoline (mono_create_jump_trampoline);
13400         mono_install_remoting_trampoline (mono_jit_create_remoting_trampoline);
13401         mono_install_delegate_trampoline (mono_create_delegate_trampoline);
13402 #endif
13403 #define JIT_INVOKE_WORKS
13404 #ifdef JIT_INVOKE_WORKS
13405         mono_install_runtime_invoke (mono_jit_runtime_invoke);
13406         mono_install_handler (mono_arch_get_throw_exception ());
13407 #endif
13408         mono_install_stack_walk (mono_jit_walk_stack);
13409         mono_install_init_vtable (mono_aot_init_vtable);
13410         mono_install_get_cached_class_info (mono_aot_get_cached_class_info);
13411         mono_install_get_class_from_name (mono_aot_get_class_from_name);
13412         mono_install_jit_info_find_in_aot (mono_aot_find_jit_info);
13413
13414         if (debug_options.collect_pagefault_stats) {
13415                 mono_raw_buffer_set_make_unreadable (TRUE);
13416                 mono_aot_set_make_unreadable (TRUE);
13417         }
13418
13419         if (runtime_version)
13420                 domain = mono_init_version (filename, runtime_version);
13421         else
13422                 domain = mono_init_from_assembly (filename, filename);
13423 #ifdef MONO_ARCH_HAVE_IMT
13424         mono_install_imt_thunk_builder (mono_arch_build_imt_thunk);
13425         mono_install_imt_trampoline (mini_get_imt_trampoline ());
13426 #if MONO_ARCH_COMMON_VTABLE_TRAMPOLINE
13427         mono_install_vtable_trampoline (mini_get_vtable_trampoline ());
13428 #endif
13429 #endif
13430         mono_icall_init ();
13431
13432         mono_add_internal_call ("System.Diagnostics.StackFrame::get_frame_info", 
13433                                 ves_icall_get_frame_info);
13434         mono_add_internal_call ("System.Diagnostics.StackTrace::get_trace", 
13435                                 ves_icall_get_trace);
13436         mono_add_internal_call ("System.Exception::get_trace", 
13437                                 ves_icall_System_Exception_get_trace);
13438         mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityFrame",
13439                                 ves_icall_System_Security_SecurityFrame_GetSecurityFrame);
13440         mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityStack",
13441                                 ves_icall_System_Security_SecurityFrame_GetSecurityStack);
13442         mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers", 
13443                                 mono_runtime_install_handlers);
13444
13445
13446         create_helper_signature ();
13447
13448 #define JIT_CALLS_WORK
13449 #ifdef JIT_CALLS_WORK
13450         /* Needs to be called here since register_jit_icall depends on it */
13451         mono_marshal_init ();
13452
13453         mono_arch_register_lowlevel_calls ();
13454         register_icall (mono_profiler_method_enter, "mono_profiler_method_enter", NULL, TRUE);
13455         register_icall (mono_profiler_method_leave, "mono_profiler_method_leave", NULL, TRUE);
13456         register_icall (mono_trace_enter_method, "mono_trace_enter_method", NULL, TRUE);
13457         register_icall (mono_trace_leave_method, "mono_trace_leave_method", NULL, TRUE);
13458         register_icall (mono_get_lmf_addr, "mono_get_lmf_addr", "ptr", TRUE);
13459         register_icall (mono_jit_thread_attach, "mono_jit_thread_attach", "void", TRUE);
13460         register_icall (mono_domain_get, "mono_domain_get", "ptr", TRUE);
13461
13462         register_icall (mono_arch_get_throw_exception (), "mono_arch_throw_exception", "void object", TRUE);
13463         register_icall (mono_arch_get_rethrow_exception (), "mono_arch_rethrow_exception", "void object", TRUE);
13464         register_icall (mono_arch_get_throw_exception_by_name (), "mono_arch_throw_exception_by_name", "void ptr", TRUE); 
13465 #if MONO_ARCH_HAVE_THROW_CORLIB_EXCEPTION
13466         register_icall (mono_arch_get_throw_corlib_exception (), "mono_arch_throw_corlib_exception", 
13467                                  "void ptr", TRUE);
13468 #endif
13469         register_icall (mono_thread_get_undeniable_exception, "mono_thread_get_undeniable_exception", "object", FALSE);
13470         register_icall (mono_thread_interruption_checkpoint, "mono_thread_interruption_checkpoint", "void", FALSE);
13471         register_icall (mono_thread_force_interruption_checkpoint, "mono_thread_force_interruption_checkpoint", "void", FALSE);
13472         register_icall (mono_load_remote_field_new, "mono_load_remote_field_new", "object object ptr ptr", FALSE);
13473         register_icall (mono_store_remote_field_new, "mono_store_remote_field_new", "void object ptr ptr object", FALSE);
13474
13475         /* 
13476          * NOTE, NOTE, NOTE, NOTE:
13477          * when adding emulation for some opcodes, remember to also add a dummy
13478          * rule to the burg files, because we need the arity information to be correct.
13479          */
13480 #ifndef MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS
13481         mono_register_opcode_emulation (OP_LMUL, "__emul_lmul", "long long long", mono_llmult, TRUE);
13482         mono_register_opcode_emulation (OP_LDIV, "__emul_ldiv", "long long long", mono_lldiv, FALSE);
13483         mono_register_opcode_emulation (OP_LDIV_UN, "__emul_ldiv_un", "long long long", mono_lldiv_un, FALSE);
13484         mono_register_opcode_emulation (OP_LREM, "__emul_lrem", "long long long", mono_llrem, FALSE);
13485         mono_register_opcode_emulation (OP_LREM_UN, "__emul_lrem_un", "long long long", mono_llrem_un, FALSE);
13486         mono_register_opcode_emulation (OP_LMUL_OVF_UN, "__emul_lmul_ovf_un", "long long long", mono_llmult_ovf_un, FALSE);
13487         mono_register_opcode_emulation (OP_LMUL_OVF, "__emul_lmul_ovf", "long long long", mono_llmult_ovf, FALSE);
13488 #endif
13489
13490 #ifndef MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS
13491         mono_register_opcode_emulation (OP_LSHL, "__emul_lshl", "long long int32", mono_lshl, TRUE);
13492         mono_register_opcode_emulation (OP_LSHR, "__emul_lshr", "long long int32", mono_lshr, TRUE);
13493         mono_register_opcode_emulation (OP_LSHR_UN, "__emul_lshr_un", "long long int32", mono_lshr_un, TRUE);
13494 #endif
13495
13496 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
13497         mono_register_opcode_emulation (CEE_DIV, "__emul_idiv", "int32 int32 int32", mono_idiv, FALSE);
13498         mono_register_opcode_emulation (CEE_DIV_UN, "__emul_idiv_un", "int32 int32 int32", mono_idiv_un, FALSE);
13499         mono_register_opcode_emulation (CEE_REM, "__emul_irem", "int32 int32 int32", mono_irem, FALSE);
13500         mono_register_opcode_emulation (CEE_REM_UN, "__emul_irem_un", "int32 int32 int32", mono_irem_un, FALSE);
13501 #endif
13502
13503 #ifdef MONO_ARCH_EMULATE_MUL_DIV
13504         mono_register_opcode_emulation (CEE_MUL_OVF, "__emul_imul_ovf", "int32 int32 int32", mono_imul_ovf, FALSE);
13505         mono_register_opcode_emulation (CEE_MUL_OVF_UN, "__emul_imul_ovf_un", "int32 int32 int32", mono_imul_ovf_un, FALSE);
13506         mono_register_opcode_emulation (CEE_MUL, "__emul_imul", "int32 int32 int32", mono_imul, TRUE);
13507 #endif
13508 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_SOFT_FLOAT)
13509         mono_register_opcode_emulation (OP_FDIV, "__emul_fdiv", "double double double", mono_fdiv, FALSE);
13510 #endif
13511
13512         mono_register_opcode_emulation (OP_FCONV_TO_U8, "__emul_fconv_to_u8", "ulong double", mono_fconv_u8, FALSE);
13513         mono_register_opcode_emulation (OP_FCONV_TO_U4, "__emul_fconv_to_u4", "uint32 double", mono_fconv_u4, FALSE);
13514         mono_register_opcode_emulation (OP_FCONV_TO_OVF_I8, "__emul_fconv_to_ovf_i8", "long double", mono_fconv_ovf_i8, FALSE);
13515         mono_register_opcode_emulation (OP_FCONV_TO_OVF_U8, "__emul_fconv_to_ovf_u8", "ulong double", mono_fconv_ovf_u8, FALSE);
13516
13517 #ifdef MONO_ARCH_EMULATE_FCONV_TO_I8
13518         mono_register_opcode_emulation (OP_FCONV_TO_I8, "__emul_fconv_to_i8", "long double", mono_fconv_i8, FALSE);
13519 #endif
13520 #ifdef MONO_ARCH_EMULATE_CONV_R8_UN
13521         mono_register_opcode_emulation (CEE_CONV_R_UN, "__emul_conv_r_un", "double int32", mono_conv_to_r8_un, FALSE);
13522 #endif
13523 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8
13524         mono_register_opcode_emulation (OP_LCONV_TO_R8, "__emul_lconv_to_r8", "double long", mono_lconv_to_r8, FALSE);
13525 #endif
13526 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R4
13527         mono_register_opcode_emulation (OP_LCONV_TO_R4, "__emul_lconv_to_r4", "float long", mono_lconv_to_r4, FALSE);
13528 #endif
13529 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8_UN
13530         mono_register_opcode_emulation (OP_LCONV_TO_R_UN, "__emul_lconv_to_r8_un", "double long", mono_lconv_to_r8_un, FALSE);
13531 #endif
13532 #ifdef MONO_ARCH_EMULATE_FREM
13533         mono_register_opcode_emulation (OP_FREM, "__emul_frem", "double double double", fmod, FALSE);
13534 #endif
13535
13536 #ifdef MONO_ARCH_SOFT_FLOAT
13537         mono_register_opcode_emulation (OP_FSUB, "__emul_fsub", "double double double", mono_fsub, FALSE);
13538         mono_register_opcode_emulation (OP_FADD, "__emul_fadd", "double double double", mono_fadd, FALSE);
13539         mono_register_opcode_emulation (OP_FMUL, "__emul_fmul", "double double double", mono_fmul, FALSE);
13540         mono_register_opcode_emulation (OP_FNEG, "__emul_fneg", "double double", mono_fneg, FALSE);
13541         mono_register_opcode_emulation (CEE_CONV_R8, "__emul_conv_r8", "double int32", mono_conv_to_r8, FALSE);
13542         mono_register_opcode_emulation (CEE_CONV_R4, "__emul_conv_r4", "double int32", mono_conv_to_r4, FALSE);
13543         mono_register_opcode_emulation (OP_FCONV_TO_R4, "__emul_fconv_to_r4", "double double", mono_fconv_r4, FALSE);
13544         mono_register_opcode_emulation (OP_FCONV_TO_I1, "__emul_fconv_to_i1", "int8 double", mono_fconv_i1, FALSE);
13545         mono_register_opcode_emulation (OP_FCONV_TO_I2, "__emul_fconv_to_i2", "int16 double", mono_fconv_i2, FALSE);
13546         mono_register_opcode_emulation (OP_FCONV_TO_I4, "__emul_fconv_to_i4", "int32 double", mono_fconv_i4, FALSE);
13547         mono_register_opcode_emulation (OP_FCONV_TO_U1, "__emul_fconv_to_u1", "uint8 double", mono_fconv_u1, FALSE);
13548         mono_register_opcode_emulation (OP_FCONV_TO_U2, "__emul_fconv_to_u2", "uint16 double", mono_fconv_u2, FALSE);
13549
13550         mono_register_opcode_emulation (OP_FBEQ, "__emul_fcmp_eq", "uint32 double double", mono_fcmp_eq, FALSE);
13551         mono_register_opcode_emulation (OP_FBLT, "__emul_fcmp_lt", "uint32 double double", mono_fcmp_lt, FALSE);
13552         mono_register_opcode_emulation (OP_FBGT, "__emul_fcmp_gt", "uint32 double double", mono_fcmp_gt, FALSE);
13553         mono_register_opcode_emulation (OP_FBLE, "__emul_fcmp_le", "uint32 double double", mono_fcmp_le, FALSE);
13554         mono_register_opcode_emulation (OP_FBGE, "__emul_fcmp_ge", "uint32 double double", mono_fcmp_ge, FALSE);
13555         mono_register_opcode_emulation (OP_FBNE_UN, "__emul_fcmp_ne_un", "uint32 double double", mono_fcmp_ne_un, FALSE);
13556         mono_register_opcode_emulation (OP_FBLT_UN, "__emul_fcmp_lt_un", "uint32 double double", mono_fcmp_lt_un, FALSE);
13557         mono_register_opcode_emulation (OP_FBGT_UN, "__emul_fcmp_gt_un", "uint32 double double", mono_fcmp_gt_un, FALSE);
13558         mono_register_opcode_emulation (OP_FBLE_UN, "__emul_fcmp_le_un", "uint32 double double", mono_fcmp_le_un, FALSE);
13559         mono_register_opcode_emulation (OP_FBGE_UN, "__emul_fcmp_ge_un", "uint32 double double", mono_fcmp_ge_un, FALSE);
13560
13561         mono_register_opcode_emulation (OP_FCEQ, "__emul_fcmp_ceq", "uint32 double double", mono_fceq, FALSE);
13562         mono_register_opcode_emulation (OP_FCGT, "__emul_fcmp_cgt", "uint32 double double", mono_fcgt, FALSE);
13563         mono_register_opcode_emulation (OP_FCGT_UN, "__emul_fcmp_cgt_un", "uint32 double double", mono_fcgt_un, FALSE);
13564         mono_register_opcode_emulation (OP_FCLT, "__emul_fcmp_clt", "uint32 double double", mono_fclt, FALSE);
13565         mono_register_opcode_emulation (OP_FCLT_UN, "__emul_fcmp_clt_un", "uint32 double double", mono_fclt_un, FALSE);
13566
13567         register_icall (mono_fload_r4, "mono_fload_r4", "double ptr", FALSE);
13568         register_icall (mono_fstore_r4, "mono_fstore_r4", "void double ptr", FALSE);
13569         register_icall (mono_fload_r4_arg, "mono_fload_r4_arg", "uint32 double", FALSE);
13570 #endif
13571
13572 #if SIZEOF_VOID_P == 4
13573         mono_register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", "uint32 double", mono_fconv_u4, TRUE);
13574 #endif
13575
13576         /* other jit icalls */
13577         register_icall (mono_delegate_ctor, "mono_delegate_ctor", "void object object ptr", FALSE);
13578         register_icall (mono_class_static_field_address , "mono_class_static_field_address", 
13579                                  "ptr ptr ptr", FALSE);
13580         register_icall (mono_ldtoken_wrapper, "mono_ldtoken_wrapper", "ptr ptr ptr ptr", FALSE);
13581         register_icall (mono_get_special_static_data, "mono_get_special_static_data", "ptr int", FALSE);
13582         register_icall (mono_ldstr, "mono_ldstr", "object ptr ptr int32", FALSE);
13583         register_icall (mono_helper_stelem_ref_check, "helper_stelem_ref_check", "void object object", FALSE);
13584         register_icall (mono_object_new, "mono_object_new", "object ptr ptr", FALSE);
13585         register_icall (mono_object_new_specific, "mono_object_new_specific", "object ptr", FALSE);
13586         register_icall (mono_array_new, "mono_array_new", "object ptr ptr int32", FALSE);
13587         register_icall (mono_array_new_specific, "mono_array_new_specific", "object ptr int32", FALSE);
13588         register_icall (mono_runtime_class_init, "mono_runtime_class_init", "void ptr", FALSE);
13589         register_icall (mono_ldftn, "mono_ldftn", "ptr ptr", FALSE);
13590         register_icall (mono_ldftn_nosync, "mono_ldftn_nosync", "ptr ptr", FALSE);
13591         register_icall (mono_ldvirtfn, "mono_ldvirtfn", "ptr object ptr", FALSE);
13592         register_icall (mono_helper_compile_generic_method, "compile_generic_method", "ptr object ptr ptr ptr", FALSE);
13593         register_icall (mono_helper_ldstr, "helper_ldstr", "object ptr int", FALSE);
13594         register_icall (mono_helper_ldstr_mscorlib, "helper_ldstr_mscorlib", "object int", FALSE);
13595         register_icall (mono_helper_newobj_mscorlib, "helper_newobj_mscorlib", "object int", FALSE);
13596         register_icall (mono_value_copy, "mono_value_copy", "void ptr ptr ptr", FALSE);
13597         register_icall (mono_helper_get_rgctx_other_ptr, "get_rgctx_other_ptr", "ptr ptr ptr int32 int32 int32 int32", FALSE);
13598         register_icall (mono_break, "mono_break", NULL, TRUE);
13599         register_icall (mono_create_corlib_exception_0, "mono_create_corlib_exception_0", "object int", TRUE);
13600         register_icall (mono_create_corlib_exception_1, "mono_create_corlib_exception_1", "object int object", TRUE);
13601         register_icall (mono_create_corlib_exception_2, "mono_create_corlib_exception_2", "object int object object", TRUE);
13602 #endif
13603
13604 #define JIT_RUNTIME_WORKS
13605 #ifdef JIT_RUNTIME_WORKS
13606         mono_install_runtime_cleanup ((MonoDomainFunc)mini_cleanup);
13607         mono_runtime_init (domain, mono_thread_start_cb, mono_thread_attach_cb);
13608 #endif
13609
13610         mono_generic_sharing_init ();
13611
13612         mono_thread_attach (domain);
13613         return domain;
13614 }
13615
13616 MonoJitStats mono_jit_stats = {0};
13617
13618 static void 
13619 print_jit_stats (void)
13620 {
13621         if (mono_jit_stats.enabled) {
13622                 g_print ("Mono Jit statistics\n");
13623                 g_print ("Compiled methods:       %ld\n", mono_jit_stats.methods_compiled);
13624                 g_print ("Methods from AOT:       %ld\n", mono_jit_stats.methods_aot);
13625                 g_print ("Methods cache lookup:   %ld\n", mono_jit_stats.methods_lookups);
13626                 g_print ("Method trampolines:     %ld\n", mono_jit_stats.method_trampolines);
13627                 g_print ("Basic blocks:           %ld\n", mono_jit_stats.basic_blocks);
13628                 g_print ("Max basic blocks:       %ld\n", mono_jit_stats.max_basic_blocks);
13629                 g_print ("Allocated vars:         %ld\n", mono_jit_stats.allocate_var);
13630                 g_print ("Analyze stack repeat:   %ld\n", mono_jit_stats.analyze_stack_repeat);
13631                 g_print ("Compiled CIL code size: %ld\n", mono_jit_stats.cil_code_size);
13632                 g_print ("Native code size:       %ld\n", mono_jit_stats.native_code_size);
13633                 g_print ("Max code size ratio:    %.2f (%s::%s)\n", mono_jit_stats.max_code_size_ratio/100.0,
13634                                 mono_jit_stats.max_ratio_method->klass->name, mono_jit_stats.max_ratio_method->name);
13635                 g_print ("Biggest method:         %ld (%s::%s)\n", mono_jit_stats.biggest_method_size,
13636                                 mono_jit_stats.biggest_method->klass->name, mono_jit_stats.biggest_method->name);
13637                 g_print ("Code reallocs:          %ld\n", mono_jit_stats.code_reallocs);
13638                 g_print ("Allocated code size:    %ld\n", mono_jit_stats.allocated_code_size);
13639                 g_print ("Inlineable methods:     %ld\n", mono_jit_stats.inlineable_methods);
13640                 g_print ("Inlined methods:        %ld\n", mono_jit_stats.inlined_methods);
13641                 g_print ("Locals stack size:      %ld\n", mono_jit_stats.locals_stack_size);
13642
13643                 g_print ("\nCreated object count:   %ld\n", mono_stats.new_object_count);
13644                 g_print ("Delegates created:      %ld\n", mono_stats.delegate_creations);
13645                 g_print ("Initialized classes:    %ld\n", mono_stats.initialized_class_count);
13646                 g_print ("Used classes:           %ld\n", mono_stats.used_class_count);
13647                 g_print ("Generic vtables:        %ld\n", mono_stats.generic_vtable_count);
13648                 g_print ("Methods:                %ld\n", mono_stats.method_count);
13649                 g_print ("Static data size:       %ld\n", mono_stats.class_static_data_size);
13650                 g_print ("VTable data size:       %ld\n", mono_stats.class_vtable_size);
13651                 g_print ("Mscorlib mempool size:  %d\n", mono_mempool_get_allocated (mono_defaults.corlib->mempool));
13652
13653                 g_print ("\nGeneric instances:      %ld\n", mono_stats.generic_instance_count);
13654                 g_print ("Initialized classes:    %ld\n", mono_stats.generic_class_count);
13655                 g_print ("Inflated methods:       %ld / %ld\n", mono_stats.inflated_method_count_2,
13656                          mono_stats.inflated_method_count);
13657                 g_print ("Inflated types:         %ld\n", mono_stats.inflated_type_count);
13658                 g_print ("Generics metadata size: %ld\n", mono_stats.generics_metadata_size);
13659                 g_print ("Generics virtual invokes: %ld\n", mono_jit_stats.generic_virtual_invocations);
13660
13661                 g_print ("Sharable generic methods: %ld\n", mono_stats.generics_sharable_methods);
13662                 g_print ("Unsharable generic methods: %ld\n", mono_stats.generics_unsharable_methods);
13663                 g_print ("Shared generic methods: %ld\n", mono_stats.generics_shared_methods);
13664
13665                 g_print ("Dynamic code allocs:    %ld\n", mono_stats.dynamic_code_alloc_count);
13666                 g_print ("Dynamic code bytes:     %ld\n", mono_stats.dynamic_code_bytes_count);
13667                 g_print ("Dynamic code frees:     %ld\n", mono_stats.dynamic_code_frees_count);
13668
13669                 g_print ("IMT tables size:        %ld\n", mono_stats.imt_tables_size);
13670                 g_print ("IMT number of tables:   %ld\n", mono_stats.imt_number_of_tables);
13671                 g_print ("IMT number of methods:  %ld\n", mono_stats.imt_number_of_methods);
13672                 g_print ("IMT used slots:         %ld\n", mono_stats.imt_used_slots);
13673                 g_print ("IMT colliding slots:    %ld\n", mono_stats.imt_slots_with_collisions);
13674                 g_print ("IMT max collisions:     %ld\n", mono_stats.imt_max_collisions_in_slot);
13675                 g_print ("IMT methods at max col: %ld\n", mono_stats.imt_method_count_when_max_collisions);
13676                 g_print ("IMT thunks size:        %ld\n", mono_stats.imt_thunks_size);
13677
13678                 g_print ("JIT info table inserts: %ld\n", mono_stats.jit_info_table_insert_count);
13679                 g_print ("JIT info table removes: %ld\n", mono_stats.jit_info_table_remove_count);
13680                 g_print ("JIT info table lookups: %ld\n", mono_stats.jit_info_table_lookup_count);
13681
13682                 g_print ("Hazardous pointers:     %ld\n", mono_stats.hazardous_pointer_count);
13683 #ifdef HAVE_SGEN_GC
13684                 g_print ("Minor GC collections:   %ld\n", mono_stats.minor_gc_count);
13685                 g_print ("Major GC collections:   %ld\n", mono_stats.major_gc_count);
13686                 g_print ("Minor GC time in msecs: %lf\n", (double)mono_stats.minor_gc_time_usecs / 1000.0);
13687                 g_print ("Major GC time in msecs: %lf\n", (double)mono_stats.major_gc_time_usecs / 1000.0);
13688 #endif
13689                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
13690                         g_print ("\nDecl security check   : %ld\n", mono_jit_stats.cas_declsec_check);
13691                         g_print ("LinkDemand (user)     : %ld\n", mono_jit_stats.cas_linkdemand);
13692                         g_print ("LinkDemand (icall)    : %ld\n", mono_jit_stats.cas_linkdemand_icall);
13693                         g_print ("LinkDemand (pinvoke)  : %ld\n", mono_jit_stats.cas_linkdemand_pinvoke);
13694                         g_print ("LinkDemand (aptc)     : %ld\n", mono_jit_stats.cas_linkdemand_aptc);
13695                         g_print ("Demand (code gen)     : %ld\n", mono_jit_stats.cas_demand_generation);
13696                 }
13697                 if (debug_options.collect_pagefault_stats) {
13698                         g_print ("Metadata pagefaults   : %d\n", mono_raw_buffer_get_n_pagefaults ());
13699                         g_print ("AOT pagefaults        : %d\n", mono_aot_get_n_pagefaults ());
13700                 }
13701         }
13702 }
13703
13704 void
13705 mini_cleanup (MonoDomain *domain)
13706 {
13707 #ifdef HAVE_LINUX_RTC_H
13708         if (rtc_fd >= 0)
13709                 enable_rtc_timer (FALSE);
13710 #endif
13711
13712         /* 
13713          * mono_runtime_cleanup() and mono_domain_finalize () need to
13714          * be called early since they need the execution engine still
13715          * fully working (mono_domain_finalize may invoke managed finalizers
13716          * and mono_runtime_cleanup will wait for other threads to finish).
13717          */
13718         mono_domain_finalize (domain, 2000);
13719
13720         /* This accesses metadata so needs to be called before runtime shutdown */
13721         print_jit_stats ();
13722
13723         mono_runtime_cleanup (domain);
13724
13725         mono_profiler_shutdown ();
13726
13727         mono_icall_cleanup ();
13728
13729         mono_runtime_cleanup_handlers ();
13730
13731         mono_domain_free (domain, TRUE);
13732
13733         mono_debugger_cleanup ();
13734
13735         mono_trampolines_cleanup ();
13736
13737         mono_code_manager_destroy (global_codeman);
13738         g_hash_table_destroy (jit_icall_name_hash);
13739         g_free (emul_opcode_map);
13740
13741         mono_arch_cleanup ();
13742
13743         mono_cleanup ();
13744
13745         mono_trace_cleanup ();
13746
13747         mono_counters_dump (-1, stdout);
13748
13749         if (mono_inject_async_exc_method)
13750                 mono_method_desc_free (mono_inject_async_exc_method);
13751
13752         TlsFree(mono_jit_tls_id);
13753
13754         DeleteCriticalSection (&jit_mutex);
13755
13756         DeleteCriticalSection (&mono_delegate_section);
13757 }
13758
13759 void
13760 mono_set_defaults (int verbose_level, guint32 opts)
13761 {
13762         mini_verbose = verbose_level;
13763         default_opt = opts;
13764         default_opt_set = TRUE;
13765 }
13766
13767 static void
13768 mono_precompile_assembly (MonoAssembly *ass, void *user_data)
13769 {
13770         GHashTable *assemblies = (GHashTable*)user_data;
13771         MonoImage *image = mono_assembly_get_image (ass);
13772         MonoMethod *method, *invoke;
13773         int i, count = 0;
13774
13775         if (g_hash_table_lookup (assemblies, ass))
13776                 return;
13777
13778         g_hash_table_insert (assemblies, ass, ass);
13779
13780         if (mini_verbose > 0)
13781                 printf ("PRECOMPILE: %s.\n", mono_image_get_filename (image));
13782
13783         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
13784                 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
13785                 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
13786                         continue;
13787
13788                 count++;
13789                 if (mini_verbose > 1) {
13790                         char * desc = mono_method_full_name (method, TRUE);
13791                         g_print ("Compiling %d %s\n", count, desc);
13792                         g_free (desc);
13793                 }
13794                 mono_compile_method (method);
13795                 if (strcmp (method->name, "Finalize") == 0) {
13796                         invoke = mono_marshal_get_runtime_invoke (method);
13797                         mono_compile_method (invoke);
13798                 }
13799                 if (method->klass->marshalbyref && mono_method_signature (method)->hasthis) {
13800                         invoke = mono_marshal_get_remoting_invoke_with_check (method);
13801                         mono_compile_method (invoke);
13802                 }
13803         }
13804
13805         /* Load and precompile referenced assemblies as well */
13806         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_ASSEMBLYREF); ++i) {
13807                 mono_assembly_load_reference (image, i);
13808                 if (image->references [i])
13809                         mono_precompile_assembly (image->references [i], assemblies);
13810         }
13811 }
13812
13813 void mono_precompile_assemblies ()
13814 {
13815         GHashTable *assemblies = g_hash_table_new (NULL, NULL);
13816
13817         mono_assembly_foreach ((GFunc)mono_precompile_assembly, assemblies);
13818
13819         g_hash_table_destroy (assemblies);
13820 }