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