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