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