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