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