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