2004-04-07 Zoltan Varga <vargaz@freemail.hu>
[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_handle_exception (struct sigcontext *ctx, gpointer obj, gboolean test_only);
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         if (cfg->prof_options & MONO_PROFILE_INS_COVERAGE)
2696                 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, header->code_size);
2697
2698         dont_inline = g_list_prepend (dont_inline, method);
2699         if (cfg->method == method) {
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->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
3390                                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
3391                                                 
3392                                                 iargs [0] = sp [0];
3393                                                 iargs [1] = sp [fsig->param_count];
3394                         
3395                                                 mono_emit_jit_icall (cfg, bblock, helper_stelem_ref_check, iargs, ip);                                          
3396                                         }
3397
3398                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, TRUE);
3399                                         NEW_INDSTORE (cfg, ins, addr, sp [fsig->param_count], fsig->params [fsig->param_count - 1]);
3400                                         ins->cil_code = ip;
3401                                         if (ins->opcode == CEE_STOBJ) {
3402                                                 handle_stobj (cfg, bblock, addr, sp [fsig->param_count], ip, mono_class_from_mono_type (fsig->params [fsig->param_count-1]), FALSE, FALSE);
3403                                         } else {
3404                                                 MONO_ADD_INS (bblock, ins);
3405                                         }
3406
3407                                 } else if (strcmp (cmethod->name, "Get") == 0) { /* array Get */
3408                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
3409                                         NEW_INDLOAD (cfg, ins, addr, fsig->ret);
3410                                         ins->cil_code = ip;
3411
3412                                         *sp++ = ins;
3413                                 } else if (strcmp (cmethod->name, "Address") == 0) { /* array Address */
3414                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
3415                                         *sp++ = addr;
3416                                 } else {
3417                                         g_assert_not_reached ();
3418                                 }
3419
3420                         } else {
3421                                 if (0 && CODE_IS_STLOC (ip + 5) && (!MONO_TYPE_ISSTRUCT (fsig->ret)) && (!MONO_TYPE_IS_VOID (fsig->ret) || cmethod->string_ctor)) {
3422                                         /* no need to spill */
3423                                         ins = (MonoInst*)mono_emit_method_call (cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL);
3424                                         *sp++ = ins;
3425                                 } else {
3426                                         if ((temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL)) != -1) {
3427                                                 NEW_TEMPLOAD (cfg, *sp, temp);
3428                                                 sp++;
3429                                         }
3430                                 }
3431                         }
3432
3433                         ip += 5;
3434                         break;
3435                 }
3436                 case CEE_RET:
3437                         if (cfg->method != method) {
3438                                 /* return from inlined methode */
3439                                 if (return_var) {
3440                                         MonoInst *store;
3441                                         CHECK_STACK (1);
3442                                         --sp;
3443                                         //g_assert (returnvar != -1);
3444                                         NEW_TEMPSTORE (cfg, store, return_var->inst_c0, *sp);
3445                                         store->cil_code = sp [0]->cil_code;
3446                                         if (store->opcode == CEE_STOBJ) {
3447                                                 g_assert_not_reached ();
3448                                                 NEW_TEMPLOADA (cfg, store, return_var->inst_c0);
3449                                                 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, return_var->klass, FALSE, FALSE);
3450                                         } else
3451                                                 MONO_ADD_INS (bblock, store);
3452                                 } 
3453                         } else {
3454                                 if (cfg->ret) {
3455                                         g_assert (!return_var);
3456                                         CHECK_STACK (1);
3457                                         --sp;
3458                                         MONO_INST_NEW (cfg, ins, CEE_NOP);
3459                                         ins->opcode = mono_type_to_stind (method->signature->ret);
3460                                         if (ins->opcode == CEE_STOBJ) {
3461                                                 NEW_RETLOADA (cfg, ins);
3462                                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
3463                                         } else {
3464                                                 ins->opcode = OP_SETRET;
3465                                                 ins->cil_code = ip;
3466                                                 ins->inst_i0 = *sp;;
3467                                                 ins->inst_i1 = NULL;
3468                                                 MONO_ADD_INS (bblock, ins);
3469                                         }
3470                                 }
3471                         }
3472                         if (sp != stack_start)
3473                                 goto unverified;
3474                         MONO_INST_NEW (cfg, ins, CEE_BR);
3475                         ins->cil_code = ip++;
3476                         ins->inst_target_bb = end_bblock;
3477                         MONO_ADD_INS (bblock, ins);
3478                         link_bblock (cfg, bblock, end_bblock);
3479                         start_new_bblock = 1;
3480                         break;
3481                 case CEE_BR_S:
3482                         CHECK_OPSIZE (2);
3483                         MONO_INST_NEW (cfg, ins, CEE_BR);
3484                         ins->cil_code = ip++;
3485                         MONO_ADD_INS (bblock, ins);
3486                         target = ip + 1 + (signed char)(*ip);
3487                         ++ip;
3488                         GET_BBLOCK (cfg, bbhash, tblock, target);
3489                         link_bblock (cfg, bblock, tblock);
3490                         CHECK_BBLOCK (target, ip, tblock);
3491                         ins->inst_target_bb = tblock;
3492                         if (sp != stack_start) {
3493                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3494                                 sp = stack_start;
3495                         }
3496                         start_new_bblock = 1;
3497                         inline_costs += 10;
3498                         break;
3499                 case CEE_BRFALSE_S:
3500                 case CEE_BRTRUE_S:
3501                         CHECK_OPSIZE (2);
3502                         CHECK_STACK (1);
3503                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
3504                         ins->cil_code = ip++;
3505                         target = ip + 1 + *(signed char*)ip;
3506                         ip++;
3507                         ADD_UNCOND (ins->opcode == CEE_BRTRUE);
3508                         if (sp != stack_start) {
3509                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3510                                 sp = stack_start;
3511                         }
3512                         inline_costs += 10;
3513                         break;
3514                 case CEE_BEQ_S:
3515                 case CEE_BGE_S:
3516                 case CEE_BGT_S:
3517                 case CEE_BLE_S:
3518                 case CEE_BLT_S:
3519                 case CEE_BNE_UN_S:
3520                 case CEE_BGE_UN_S:
3521                 case CEE_BGT_UN_S:
3522                 case CEE_BLE_UN_S:
3523                 case CEE_BLT_UN_S:
3524                         CHECK_OPSIZE (2);
3525                         CHECK_STACK (2);
3526                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
3527                         ins->cil_code = ip++;
3528                         target = ip + 1 + *(signed char*)ip;
3529                         ip++;
3530                         ADD_BINCOND (NULL);
3531                         if (sp != stack_start) {
3532                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3533                                 sp = stack_start;
3534                         }
3535                         inline_costs += 10;
3536                         break;
3537                 case CEE_BR:
3538                         CHECK_OPSIZE (5);
3539                         MONO_INST_NEW (cfg, ins, CEE_BR);
3540                         ins->cil_code = ip++;
3541                         MONO_ADD_INS (bblock, ins);
3542                         target = ip + 4 + (gint32)read32(ip);
3543                         ip += 4;
3544                         GET_BBLOCK (cfg, bbhash, tblock, target);
3545                         link_bblock (cfg, bblock, tblock);
3546                         CHECK_BBLOCK (target, ip, tblock);
3547                         ins->inst_target_bb = tblock;
3548                         if (sp != stack_start) {
3549                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3550                                 sp = stack_start;
3551                         }
3552                         start_new_bblock = 1;
3553                         inline_costs += 10;
3554                         break;
3555                 case CEE_BRFALSE:
3556                 case CEE_BRTRUE:
3557                         CHECK_OPSIZE (5);
3558                         CHECK_STACK (1);
3559                         MONO_INST_NEW (cfg, ins, *ip);
3560                         ins->cil_code = ip++;
3561                         target = ip + 4 + (gint32)read32(ip);
3562                         ip += 4;
3563                         ADD_UNCOND(ins->opcode == CEE_BRTRUE);
3564                         if (sp != stack_start) {
3565                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3566                                 sp = stack_start;
3567                         }
3568                         inline_costs += 10;
3569                         break;
3570                 case CEE_BEQ:
3571                 case CEE_BGE:
3572                 case CEE_BGT:
3573                 case CEE_BLE:
3574                 case CEE_BLT:
3575                 case CEE_BNE_UN:
3576                 case CEE_BGE_UN:
3577                 case CEE_BGT_UN:
3578                 case CEE_BLE_UN:
3579                 case CEE_BLT_UN:
3580                         CHECK_OPSIZE (5);
3581                         CHECK_STACK (2);
3582                         MONO_INST_NEW (cfg, ins, *ip);
3583                         ins->cil_code = ip++;
3584                         target = ip + 4 + (gint32)read32(ip);
3585                         ip += 4;
3586                         ADD_BINCOND(NULL);
3587                         if (sp != stack_start) {
3588                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3589                                 sp = stack_start;
3590                         }
3591                         inline_costs += 10;
3592                         break;
3593                 case CEE_SWITCH:
3594                         CHECK_OPSIZE (5);
3595                         CHECK_STACK (1);
3596                         n = read32 (ip + 1);
3597                         MONO_INST_NEW (cfg, ins, *ip);
3598                         --sp;
3599                         ins->inst_left = *sp;
3600                         if (ins->inst_left->type != STACK_I4) goto unverified;
3601                         ins->cil_code = ip;
3602                         ip += 5;
3603                         CHECK_OPSIZE (n * sizeof (guint32));
3604                         target = ip + n * sizeof (guint32);
3605                         MONO_ADD_INS (bblock, ins);
3606                         GET_BBLOCK (cfg, bbhash, tblock, target);
3607                         link_bblock (cfg, bblock, tblock);
3608                         ins->klass = GUINT_TO_POINTER (n);
3609                         ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (n + 1));
3610                         ins->inst_many_bb [n] = tblock;
3611
3612                         for (i = 0; i < n; ++i) {
3613                                 GET_BBLOCK (cfg, bbhash, tblock, target + (gint32)read32(ip));
3614                                 link_bblock (cfg, bblock, tblock);
3615                                 ins->inst_many_bb [i] = tblock;
3616                                 ip += 4;
3617                         }
3618                         if (sp != stack_start) {
3619                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3620                                 sp = stack_start;
3621                         }
3622                         inline_costs += 20;
3623                         break;
3624                 case CEE_LDIND_I1:
3625                 case CEE_LDIND_U1:
3626                 case CEE_LDIND_I2:
3627                 case CEE_LDIND_U2:
3628                 case CEE_LDIND_I4:
3629                 case CEE_LDIND_U4:
3630                 case CEE_LDIND_I8:
3631                 case CEE_LDIND_I:
3632                 case CEE_LDIND_R4:
3633                 case CEE_LDIND_R8:
3634                 case CEE_LDIND_REF:
3635                         CHECK_STACK (1);
3636                         MONO_INST_NEW (cfg, ins, *ip);
3637                         ins->cil_code = ip;
3638                         --sp;
3639                         ins->inst_i0 = *sp;
3640                         *sp++ = ins;
3641                         ins->type = ldind_type [*ip - CEE_LDIND_I1];
3642                         ins->flags |= ins_flag;
3643                         ins_flag = 0;
3644                         ++ip;
3645                         break;
3646                 case CEE_STIND_REF:
3647                 case CEE_STIND_I1:
3648                 case CEE_STIND_I2:
3649                 case CEE_STIND_I4:
3650                 case CEE_STIND_I8:
3651                 case CEE_STIND_R4:
3652                 case CEE_STIND_R8:
3653                         CHECK_STACK (2);
3654                         MONO_INST_NEW (cfg, ins, *ip);
3655                         ins->cil_code = ip++;
3656                         sp -= 2;
3657                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3658                         MONO_ADD_INS (bblock, ins);
3659                         ins->inst_i0 = sp [0];
3660                         ins->inst_i1 = sp [1];
3661                         ins->flags |= ins_flag;
3662                         ins_flag = 0;
3663                         inline_costs += 1;
3664                         break;
3665                 case CEE_ADD:
3666                 case CEE_SUB:
3667                 case CEE_MUL:
3668                 case CEE_DIV:
3669                 case CEE_DIV_UN:
3670                 case CEE_REM:
3671                 case CEE_REM_UN:
3672                 case CEE_AND:
3673                 case CEE_OR:
3674                 case CEE_XOR:
3675                 case CEE_SHL:
3676                 case CEE_SHR:
3677                 case CEE_SHR_UN:
3678                         CHECK_STACK (2);
3679                         ADD_BINOP (*ip);
3680                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
3681                                 MonoInst *store, *temp, *load;
3682                                 --sp;
3683                                 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
3684                                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
3685                                 store->cil_code = ins->cil_code;
3686                                 MONO_ADD_INS (bblock, store);
3687                                 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
3688                                 load->cil_code = ins->cil_code;
3689                                 *sp++ = load;
3690                                 /*g_print ("found emulation for %d\n", ins->opcode);*/
3691                         }
3692                         ip++;
3693                         break;
3694                 case CEE_NEG:
3695                 case CEE_NOT:
3696                 case CEE_CONV_I1:
3697                 case CEE_CONV_I2:
3698                 case CEE_CONV_I4:
3699                 case CEE_CONV_R4:
3700                 case CEE_CONV_R8:
3701                 case CEE_CONV_U4:
3702                 case CEE_CONV_I8:
3703                 case CEE_CONV_U8:
3704                 case CEE_CONV_OVF_I8:
3705                 case CEE_CONV_OVF_U8:
3706                 case CEE_CONV_R_UN:
3707                         CHECK_STACK (1);
3708                         ADD_UNOP (*ip);
3709                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
3710                                 MonoInst *store, *temp, *load;
3711                                 --sp;
3712                                 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
3713                                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
3714                                 store->cil_code = ins->cil_code;
3715                                 MONO_ADD_INS (bblock, store);
3716                                 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
3717                                 load->cil_code = ins->cil_code;
3718                                 *sp++ = load;
3719                                 /*g_print ("found emulation for %d\n", ins->opcode);*/
3720                         }
3721                         ip++;                   
3722                         break;
3723                 case CEE_CONV_OVF_I4:
3724                 case CEE_CONV_OVF_I1:
3725                 case CEE_CONV_OVF_I2:
3726                 case CEE_CONV_OVF_I:
3727                 case CEE_CONV_OVF_U:
3728                         CHECK_STACK (1);
3729
3730                         if (sp [-1]->type == STACK_R8) {
3731                                 ADD_UNOP (CEE_CONV_OVF_I8);
3732                                 ADD_UNOP (*ip);
3733                         } else {
3734                                 ADD_UNOP (*ip);
3735                         }
3736
3737                         ip++;
3738                         break;
3739                 case CEE_CONV_OVF_U1:
3740                 case CEE_CONV_OVF_U2:
3741                 case CEE_CONV_OVF_U4:
3742                         CHECK_STACK (1);
3743
3744                         if (sp [-1]->type == STACK_R8) {
3745                                 ADD_UNOP (CEE_CONV_OVF_U8);
3746                                 ADD_UNOP (*ip);
3747                         } else {
3748                                 ADD_UNOP (*ip);
3749                         }
3750
3751                         ip++;
3752                         break;
3753                 case CEE_CONV_OVF_I1_UN:
3754                 case CEE_CONV_OVF_I2_UN:
3755                 case CEE_CONV_OVF_I4_UN:
3756                 case CEE_CONV_OVF_I8_UN:
3757                 case CEE_CONV_OVF_U1_UN:
3758                 case CEE_CONV_OVF_U2_UN:
3759                 case CEE_CONV_OVF_U4_UN:
3760                 case CEE_CONV_OVF_U8_UN:
3761                 case CEE_CONV_OVF_I_UN:
3762                 case CEE_CONV_OVF_U_UN:
3763                         CHECK_STACK (1);
3764                         ADD_UNOP (*ip);
3765                         ip++;
3766                         break;
3767                 case CEE_CPOBJ:
3768                         CHECK_OPSIZE (5);
3769                         CHECK_STACK (2);
3770                         token = read32 (ip + 1);
3771                         if (method->wrapper_type != MONO_WRAPPER_NONE)
3772                                 klass = mono_method_get_wrapper_data (method, token);
3773                         else
3774                                 klass = mono_class_get_full (image, token, generic_context);
3775
3776                         mono_class_init (klass);
3777                         sp -= 2;
3778                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
3779                                 MonoInst *store, *load;
3780                                 MONO_INST_NEW (cfg, load, CEE_LDIND_REF);
3781                                 load->cil_code = ip;
3782                                 load->inst_i0 = sp [1];
3783                                 load->type = ldind_type [CEE_LDIND_REF];
3784                                 load->flags |= ins_flag;
3785                                 MONO_INST_NEW (cfg, store, CEE_STIND_REF);
3786                                 store->cil_code = ip;
3787                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
3788                                 MONO_ADD_INS (bblock, store);
3789                                 store->inst_i0 = sp [0];
3790                                 store->inst_i1 = load;
3791                                 store->flags |= ins_flag;
3792                         } else {
3793                                 n = mono_class_value_size (klass, NULL);
3794                                 if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
3795                                         MonoInst *copy;
3796                                         MONO_INST_NEW (cfg, copy, OP_MEMCPY);
3797                                         copy->inst_left = sp [0];
3798                                         copy->inst_right = sp [1];
3799                                         copy->cil_code = ip;
3800                                         copy->unused = n;
3801                                         MONO_ADD_INS (bblock, copy);
3802                                 } else {
3803                                         MonoInst *iargs [3];
3804                                         iargs [0] = sp [0];
3805                                         iargs [1] = sp [1];
3806                                         NEW_ICONST (cfg, iargs [2], n);
3807                                         iargs [2]->cil_code = ip;
3808
3809                                         mono_emit_jit_icall (cfg, bblock, helper_memcpy, iargs, ip);
3810                                 }
3811                         }
3812                         ins_flag = 0;
3813                         ip += 5;
3814                         break;
3815                 case CEE_LDOBJ: {
3816                         MonoInst *iargs [3];
3817                         CHECK_OPSIZE (5);
3818                         CHECK_STACK (1);
3819                         --sp;
3820                         token = read32 (ip + 1);
3821                         if (method->wrapper_type != MONO_WRAPPER_NONE)
3822                                 klass = mono_method_get_wrapper_data (method, token);
3823                         else
3824                                 klass = mono_class_get_full (image, token, generic_context);
3825
3826                         mono_class_init (klass);
3827                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
3828                                 MONO_INST_NEW (cfg, ins, CEE_LDIND_REF);
3829                                 ins->cil_code = ip;
3830                                 ins->inst_i0 = sp [0];
3831                                 ins->type = ldind_type [CEE_LDIND_REF];
3832                                 ins->flags |= ins_flag;
3833                                 ins_flag = 0;
3834                                 *sp++ = ins;
3835                                 ip += 5;
3836                                 break;
3837                         }
3838                         n = mono_class_value_size (klass, NULL);
3839                         ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
3840                         NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
3841                         if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
3842                                 MonoInst *copy;
3843                                 MONO_INST_NEW (cfg, copy, OP_MEMCPY);
3844                                 copy->inst_left = iargs [0];
3845                                 copy->inst_right = *sp;
3846                                 copy->cil_code = ip;
3847                                 copy->unused = n;
3848                                 MONO_ADD_INS (bblock, copy);
3849                         } else {
3850                                 iargs [1] = *sp;
3851                                 NEW_ICONST (cfg, iargs [2], n);
3852                                 iargs [2]->cil_code = ip;
3853
3854                                 mono_emit_jit_icall (cfg, bblock, helper_memcpy, iargs, ip);
3855                         }
3856                         NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
3857                         ++sp;
3858                         ip += 5;
3859                         ins_flag = 0;
3860                         inline_costs += 1;
3861                         break;
3862                 }
3863                 case CEE_LDSTR:
3864                         CHECK_STACK_OVF (1);
3865                         CHECK_OPSIZE (5);
3866                         n = read32 (ip + 1);
3867
3868                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
3869                                 int temp;
3870                                 MonoInst *iargs [1];
3871
3872                                 NEW_PCONST (cfg, iargs [0], mono_method_get_wrapper_data (method, n));                          
3873                                 temp = mono_emit_jit_icall (cfg, bblock, mono_string_new_wrapper, iargs, ip);
3874                                 NEW_TEMPLOAD (cfg, *sp, temp);
3875
3876                         } else {
3877
3878                                 if (cfg->opt & MONO_OPT_SHARED) {
3879                                         int temp;
3880                                         MonoInst *iargs [3];
3881
3882                                         if (mono_compile_aot) {
3883                                                 cfg->ldstr_list = g_list_prepend (cfg->ldstr_list, (gpointer)n);
3884                                         }
3885
3886                                         NEW_TEMPLOAD (cfg, iargs [0], mono_get_domainvar (cfg)->inst_c0);
3887                                         NEW_IMAGECONST (cfg, iargs [1], image);
3888                                         NEW_ICONST (cfg, iargs [2], mono_metadata_token_index (n));
3889                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldstr, iargs, ip);
3890                                         NEW_TEMPLOAD (cfg, *sp, temp);
3891                                         mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
3892                                 } else {
3893                                         if (mono_compile_aot)
3894                                                 NEW_LDSTRCONST (cfg, ins, image, n);
3895                                         else {
3896                                                 NEW_PCONST (cfg, ins, NULL);
3897                                                 ins->cil_code = ip;
3898                                                 ins->type = STACK_OBJ;
3899                                                 ins->inst_p0 = mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
3900                                         }
3901                                         *sp = ins;
3902                                 }
3903                         }
3904
3905                         sp++;
3906                         ip += 5;
3907                         break;
3908                 case CEE_NEWOBJ: {
3909                         MonoInst *iargs [2];
3910                         MonoMethodSignature *fsig;
3911                         int temp;
3912
3913                         CHECK_OPSIZE (5);
3914                         token = read32 (ip + 1);
3915                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
3916                                 cmethod = mono_method_get_wrapper_data (method, token);
3917                         } else
3918                                 cmethod = mono_get_method_full (image, token, NULL, generic_context);
3919                         fsig = mono_method_get_signature (cmethod, image, token);
3920
3921                         mono_class_init (cmethod->klass);
3922
3923                         n = fsig->param_count;
3924                         CHECK_STACK (n);
3925
3926                         /* move the args to allow room for 'this' in the first position */
3927                         while (n--) {
3928                                 --sp;
3929                                 sp [1] = sp [0];
3930                         }
3931
3932                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3933                         
3934
3935                         if (cmethod->klass->parent == mono_defaults.array_class) {
3936                                 NEW_METHODCONST (cfg, *sp, cmethod);
3937                                 temp = mono_emit_native_call (cfg, bblock, mono_array_new_va, fsig, sp, ip, FALSE);
3938
3939                         } else if (cmethod->string_ctor) {
3940                                 /* we simply pass a null pointer */
3941                                 NEW_PCONST (cfg, *sp, NULL); 
3942                                 /* now call the string ctor */
3943                                 temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, NULL);
3944                         } else {
3945                                 if (cmethod->klass->valuetype) {
3946                                         iargs [0] = mono_compile_create_var (cfg, &cmethod->klass->byval_arg, OP_LOCAL);
3947                                         temp = iargs [0]->inst_c0;
3948                                         NEW_TEMPLOADA (cfg, *sp, temp);
3949                                 } else {
3950                                         if (cfg->opt & MONO_OPT_SHARED) {
3951                                                 NEW_DOMAINCONST (cfg, iargs [0]);
3952                                                 NEW_CLASSCONST (cfg, iargs [1], cmethod->klass);
3953
3954                                                 temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
3955                                         } else {
3956                                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
3957                                                 NEW_VTABLECONST (cfg, iargs [0], vtable);
3958                                                 if (cmethod->klass->has_finalize || cmethod->klass->marshalbyref || (cfg->prof_options & MONO_PROFILE_ALLOCATIONS))
3959                                                         temp = mono_emit_jit_icall (cfg, bblock, mono_object_new_specific, iargs, ip);
3960                                                 else
3961                                                         temp = mono_emit_jit_icall (cfg, bblock, mono_object_new_fast, iargs, ip);
3962                                         }
3963                                         NEW_TEMPLOAD (cfg, *sp, temp);
3964                                 }
3965
3966                                 if ((cfg->opt & MONO_OPT_INLINE) && cmethod &&
3967                                     mono_method_check_inlining (cfg, cmethod) &&
3968                                     !mono_class_is_subclass_of (cmethod->klass, mono_defaults.exception_class, FALSE) &&
3969                                     !g_list_find (dont_inline, cmethod)) {
3970                                         int costs;
3971                                         MonoBasicBlock *ebblock;
3972                                         if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock))) {
3973
3974                                                 ip += 5;
3975                                                 real_offset += 5;
3976                                                 
3977                                                 GET_BBLOCK (cfg, bbhash, bblock, ip);
3978                                                 ebblock->next_bb = bblock;
3979                                                 link_bblock (cfg, ebblock, bblock);
3980
3981                                                 NEW_TEMPLOAD (cfg, *sp, temp);
3982                                                 sp++;
3983
3984                                                 /* indicates start of a new block, and triggers a load 
3985                                                    of all stack arguments at bb boundarie */
3986                                                 bblock = ebblock;
3987
3988                                                 inline_costs += costs;
3989                                                 break;
3990                                                 
3991                                         } else {
3992                                                 mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, sp[0]);
3993                                         }
3994                                 } else {
3995                                         /* now call the actual ctor */
3996                                         mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, sp[0]);
3997                                 }
3998                         }
3999
4000                         NEW_TEMPLOAD (cfg, *sp, temp);
4001                         sp++;
4002                         
4003                         ip += 5;
4004                         inline_costs += 5;
4005                         break;
4006                 }
4007                 case CEE_ISINST:
4008                         CHECK_STACK (1);
4009                         --sp;
4010                         CHECK_OPSIZE (5);
4011                         klass = mono_class_get_full (image, read32 (ip + 1), generic_context);
4012                         mono_class_init (klass);
4013                 
4014                         if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
4015                         
4016                                 MonoMethod *mono_isinst;
4017                                 MonoInst *iargs [1];
4018                                 MonoBasicBlock *ebblock;
4019                                 int costs;
4020                                 int temp;
4021                                 
4022                                 mono_isinst = mono_marshal_get_isinst (klass); 
4023                                 iargs [0] = sp [0];
4024                                 
4025                                 costs = inline_method (cfg, mono_isinst, mono_isinst->signature, bblock, 
4026                                                            iargs, ip, real_offset, dont_inline, &ebblock);
4027                         
4028                                 g_assert (costs > 0);
4029                                 
4030                                 ip += 5;
4031                                 real_offset += 5;
4032                         
4033                                 GET_BBLOCK (cfg, bbhash, bblock, ip);
4034                                 ebblock->next_bb = bblock;
4035                                 link_bblock (cfg, ebblock, bblock);
4036
4037                                 temp = iargs [0]->inst_i0->inst_c0;
4038                                 NEW_TEMPLOAD (cfg, *sp, temp);
4039                                 
4040                                 sp++;
4041                                 bblock = ebblock;
4042                                 inline_costs += costs;
4043
4044                         }
4045                         else {
4046                                 MONO_INST_NEW (cfg, ins, *ip);
4047                                 ins->type = STACK_OBJ;
4048                                 ins->inst_left = *sp;
4049                                 ins->inst_newa_class = klass;
4050                                 ins->cil_code = ip;
4051                                 *sp++ = ins;
4052                                 ip += 5;
4053                         }
4054                         break;
4055                 case CEE_UNBOX_ANY: {
4056                         MonoInst *add, *vtoffset;
4057                         MonoInst *iargs [3];
4058
4059                         CHECK_STACK (1);
4060                         --sp;
4061                         CHECK_OPSIZE (5);
4062                         token = read32 (ip + 1);
4063                         if (method->wrapper_type != MONO_WRAPPER_NONE)
4064                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
4065                         else 
4066                                 klass = mono_class_get_full (image, token, generic_context);
4067                         mono_class_init (klass);
4068
4069                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
4070                                 /* CASTCLASS */
4071                                 if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
4072                                         MonoMethod *mono_castclass;
4073                                         MonoInst *iargs [1];
4074                                         MonoBasicBlock *ebblock;
4075                                         int costs;
4076                                         int temp;
4077                                         
4078                                         mono_castclass = mono_marshal_get_castclass (klass); 
4079                                         iargs [0] = sp [0];
4080                                         
4081                                         costs = inline_method (cfg, mono_castclass, mono_castclass->signature, bblock, 
4082                                                                    iargs, ip, real_offset, dont_inline, &ebblock);
4083                                 
4084                                         g_assert (costs > 0);
4085                                         
4086                                         ip += 5;
4087                                         real_offset += 5;
4088                                 
4089                                         GET_BBLOCK (cfg, bbhash, bblock, ip);
4090                                         ebblock->next_bb = bblock;
4091                                         link_bblock (cfg, ebblock, bblock);
4092         
4093                                         temp = iargs [0]->inst_i0->inst_c0;
4094                                         NEW_TEMPLOAD (cfg, *sp, temp);
4095                                         
4096                                         sp++;
4097                                         bblock = ebblock;
4098                                         inline_costs += costs;                          
4099                                 }
4100                                 else {
4101                                         MONO_INST_NEW (cfg, ins, CEE_CASTCLASS);
4102                                         ins->type = STACK_OBJ;
4103                                         ins->inst_left = *sp;
4104                                         ins->klass = klass;
4105                                         ins->inst_newa_class = klass;
4106                                         ins->cil_code = ip;
4107                                         *sp++ = ins;
4108                                 }
4109                                 ip += 5;
4110                                 break;
4111                         }
4112
4113                         MONO_INST_NEW (cfg, ins, OP_UNBOXCAST);
4114                         ins->type = STACK_OBJ;
4115                         ins->inst_left = *sp;
4116                         ins->klass = klass;
4117                         ins->inst_newa_class = klass;
4118                         ins->cil_code = ip;
4119
4120                         MONO_INST_NEW (cfg, add, CEE_ADD);
4121                         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
4122                         add->inst_left = ins;
4123                         add->inst_right = vtoffset;
4124                         add->type = STACK_MP;
4125                         *sp = add;
4126                         ip += 5;
4127                         /* LDOBJ impl */
4128                         n = mono_class_value_size (klass, NULL);
4129                         ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
4130                         NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
4131                         if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
4132                                 MonoInst *copy;
4133                                 MONO_INST_NEW (cfg, copy, OP_MEMCPY);
4134                                 copy->inst_left = iargs [0];
4135                                 copy->inst_right = *sp;
4136                                 copy->cil_code = ip;
4137                                 copy->unused = n;
4138                                 MONO_ADD_INS (bblock, copy);
4139                         } else {
4140                                 iargs [1] = *sp;
4141                                 NEW_ICONST (cfg, iargs [2], n);
4142                                 iargs [2]->cil_code = ip;
4143
4144                                 mono_emit_jit_icall (cfg, bblock, helper_memcpy, iargs, ip);
4145                         }
4146                         NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
4147                         ++sp;
4148                         inline_costs += 2;
4149                         break;
4150                 }
4151                 case CEE_UNBOX: {
4152                         MonoInst *add, *vtoffset;
4153
4154                         CHECK_STACK (1);
4155                         --sp;
4156                         CHECK_OPSIZE (5);
4157                         token = read32 (ip + 1);
4158                         if (method->wrapper_type != MONO_WRAPPER_NONE)
4159                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
4160                         else 
4161                                 klass = mono_class_get_full (image, token, generic_context);
4162                         mono_class_init (klass);
4163
4164                         MONO_INST_NEW (cfg, ins, OP_UNBOXCAST);
4165                         ins->type = STACK_OBJ;
4166                         ins->inst_left = *sp;
4167                         ins->klass = klass;
4168                         ins->inst_newa_class = klass;
4169                         ins->cil_code = ip;
4170
4171                         MONO_INST_NEW (cfg, add, CEE_ADD);
4172                         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
4173                         add->inst_left = ins;
4174                         add->inst_right = vtoffset;
4175                         add->type = STACK_MP;
4176                         *sp++ = add;
4177                         ip += 5;
4178                         inline_costs += 2;
4179                         break;
4180                 }
4181                 case CEE_CASTCLASS:
4182                         CHECK_STACK (1);
4183                         --sp;
4184                         CHECK_OPSIZE (5);
4185                         klass = mono_class_get_full (image, read32 (ip + 1), generic_context);
4186                         mono_class_init (klass);
4187                 
4188                         if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
4189                                 
4190                                 MonoMethod *mono_castclass;
4191                                 MonoInst *iargs [1];
4192                                 MonoBasicBlock *ebblock;
4193                                 int costs;
4194                                 int temp;
4195                                 
4196                                 mono_castclass = mono_marshal_get_castclass (klass); 
4197                                 iargs [0] = sp [0];
4198                                 
4199                                 costs = inline_method (cfg, mono_castclass, mono_castclass->signature, bblock, 
4200                                                            iargs, ip, real_offset, dont_inline, &ebblock);
4201                         
4202                                 g_assert (costs > 0);
4203                                 
4204                                 ip += 5;
4205                                 real_offset += 5;
4206                         
4207                                 GET_BBLOCK (cfg, bbhash, bblock, ip);
4208                                 ebblock->next_bb = bblock;
4209                                 link_bblock (cfg, ebblock, bblock);
4210
4211                                 temp = iargs [0]->inst_i0->inst_c0;
4212                                 NEW_TEMPLOAD (cfg, *sp, temp);
4213                                 
4214                                 sp++;
4215                                 bblock = ebblock;
4216                                 inline_costs += costs;
4217                         }
4218                         else {
4219                                 MONO_INST_NEW (cfg, ins, *ip);
4220                                 ins->type = STACK_OBJ;
4221                                 ins->inst_left = *sp;
4222                                 ins->klass = klass;
4223                                 ins->inst_newa_class = klass;
4224                                 ins->cil_code = ip;
4225                                 *sp++ = ins;
4226                                 ip += 5;
4227                         }
4228                         break;
4229                 case CEE_THROW:
4230                         CHECK_STACK (1);
4231                         MONO_INST_NEW (cfg, ins, *ip);
4232                         --sp;
4233                         ins->inst_left = *sp;
4234                         ins->cil_code = ip++;
4235                         MONO_ADD_INS (bblock, ins);
4236                         sp = stack_start;
4237                         start_new_bblock = 1;
4238                         break;
4239                 case CEE_LDFLD:
4240                 case CEE_LDFLDA:
4241                 case CEE_STFLD: {
4242                         MonoInst *offset_ins;
4243                         MonoClassField *field;
4244                         MonoBasicBlock *ebblock;
4245                         int costs;
4246                         guint foffset;
4247
4248                         if (*ip == CEE_STFLD) {
4249                                 CHECK_STACK (2);
4250                                 sp -= 2;
4251                         } else {
4252                                 CHECK_STACK (1);
4253                                 --sp;
4254                         }
4255                         // FIXME: enable this test later.
4256                         //if (sp [0]->type != STACK_OBJ && sp [0]->type != STACK_MP)
4257                         //      goto unverified;
4258                         CHECK_OPSIZE (5);
4259                         token = read32 (ip + 1);
4260                         field = mono_field_from_token (image, token, &klass, generic_context);
4261                         mono_class_init (klass);
4262
4263                         foffset = klass->valuetype? field->offset - sizeof (MonoObject): field->offset;
4264                         /* FIXME: mark instructions for use in SSA */
4265                         if (*ip == CEE_STFLD) {
4266                                 if ((klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) || klass->contextbound) {
4267                                         MonoMethod *stfld_wrapper = mono_marshal_get_stfld_wrapper (field->type); 
4268                                         MonoInst *iargs [5];
4269
4270                                         iargs [0] = sp [0];
4271                                         NEW_CLASSCONST (cfg, iargs [1], klass);
4272                                         NEW_FIELDCONST (cfg, iargs [2], field);
4273                                         NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : 
4274                                                     field->offset);
4275                                         iargs [4] = sp [1];
4276
4277                                         if (cfg->opt & MONO_OPT_INLINE) {
4278                                                 costs = inline_method (cfg, stfld_wrapper, stfld_wrapper->signature, bblock, 
4279                                                                        iargs, ip, real_offset, dont_inline, &ebblock);
4280                                                 g_assert (costs > 0);
4281                                                       
4282                                                 ip += 5;
4283                                                 real_offset += 5;
4284
4285                                                 GET_BBLOCK (cfg, bbhash, bblock, ip);
4286                                                 ebblock->next_bb = bblock;
4287                                                 link_bblock (cfg, ebblock, bblock);
4288
4289                                                 /* indicates start of a new block, and triggers a load 
4290                                                    of all stack arguments at bb boundarie */
4291                                                 bblock = ebblock;
4292
4293                                                 inline_costs += costs;
4294                                                 break;
4295                                         } else {
4296                                                 mono_emit_method_call_spilled (cfg, bblock, stfld_wrapper, stfld_wrapper->signature, iargs, ip, NULL);
4297                                         }
4298                                 } else {
4299                                         MonoInst *store;
4300                                         NEW_ICONST (cfg, offset_ins, foffset);
4301                                         MONO_INST_NEW (cfg, ins, CEE_ADD);
4302                                         ins->cil_code = ip;
4303                                         ins->inst_left = *sp;
4304                                         ins->inst_right = offset_ins;
4305                                         ins->type = STACK_MP;
4306
4307                                         MONO_INST_NEW (cfg, store, mono_type_to_stind (field->type));
4308                                         store->cil_code = ip;
4309                                         store->inst_left = ins;
4310                                         store->inst_right = sp [1];
4311                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
4312                                         store->flags |= ins_flag;
4313                                         ins_flag = 0;
4314                                         if (store->opcode == CEE_STOBJ) {
4315                                                 handle_stobj (cfg, bblock, ins, sp [1], ip, 
4316                                                               mono_class_from_mono_type (field->type), FALSE, FALSE);
4317                                         } else
4318                                                 MONO_ADD_INS (bblock, store);
4319                                 }
4320                         } else {
4321                                 if ((klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) || klass->contextbound) {
4322                                         /* fixme: we need to inline that call somehow */
4323                                         MonoMethod *ldfld_wrapper = mono_marshal_get_ldfld_wrapper (field->type); 
4324                                         MonoInst *iargs [4];
4325                                         int temp;
4326                                         
4327                                         iargs [0] = sp [0];
4328                                         NEW_CLASSCONST (cfg, iargs [1], klass);
4329                                         NEW_FIELDCONST (cfg, iargs [2], field);
4330                                         NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
4331                                         if (cfg->opt & MONO_OPT_INLINE) {
4332                                                 costs = inline_method (cfg, ldfld_wrapper, ldfld_wrapper->signature, bblock, 
4333                                                                        iargs, ip, real_offset, dont_inline, &ebblock);
4334                                                 g_assert (costs > 0);
4335                                                       
4336                                                 ip += 5;
4337                                                 real_offset += 5;
4338
4339                                                 GET_BBLOCK (cfg, bbhash, bblock, ip);
4340                                                 ebblock->next_bb = bblock;
4341                                                 link_bblock (cfg, ebblock, bblock);
4342
4343                                                 temp = iargs [0]->inst_i0->inst_c0;
4344
4345                                                 if (*ip == CEE_LDFLDA) {
4346                                                         /* not sure howto handle this */
4347                                                         NEW_TEMPLOADA (cfg, *sp, temp);
4348                                                 } else {
4349                                                         NEW_TEMPLOAD (cfg, *sp, temp);
4350                                                 }
4351                                                 sp++;
4352
4353                                                 /* indicates start of a new block, and triggers a load of
4354                                                    all stack arguments at bb boundarie */
4355                                                 bblock = ebblock;
4356                                                 
4357                                                 inline_costs += costs;
4358                                                 break;
4359                                         } else {
4360                                                 temp = mono_emit_method_call_spilled (cfg, bblock, ldfld_wrapper, ldfld_wrapper->signature, iargs, ip, NULL);
4361                                                 if (*ip == CEE_LDFLDA) {
4362                                                         /* not sure howto handle this */
4363                                                         NEW_TEMPLOADA (cfg, *sp, temp);
4364                                                 } else {
4365                                                         NEW_TEMPLOAD (cfg, *sp, temp);
4366                                                 }
4367                                                 sp++;
4368                                         }
4369                                 } else {
4370                                         NEW_ICONST (cfg, offset_ins, foffset);
4371                                         MONO_INST_NEW (cfg, ins, CEE_ADD);
4372                                         ins->cil_code = ip;
4373                                         ins->inst_left = *sp;
4374                                         ins->inst_right = offset_ins;
4375                                         ins->type = STACK_MP;
4376
4377                                         if (*ip == CEE_LDFLDA) {
4378                                                 *sp++ = ins;
4379                                         } else {
4380                                                 MonoInst *load;
4381                                                 MONO_INST_NEW (cfg, load, mono_type_to_ldind (field->type));
4382                                                 type_to_eval_stack_type (field->type, load);
4383                                                 load->cil_code = ip;
4384                                                 load->inst_left = ins;
4385                                                 load->flags |= ins_flag;
4386                                                 ins_flag = 0;
4387                                                 *sp++ = load;
4388                                         }
4389                                 }
4390                         }
4391                         ip += 5;
4392                         break;
4393                 }
4394                 case CEE_LDSFLD:
4395                 case CEE_LDSFLDA:
4396                 case CEE_STSFLD: {
4397                         MonoClassField *field;
4398                         gpointer addr = NULL;
4399
4400                         CHECK_OPSIZE (5);
4401                         token = read32 (ip + 1);
4402
4403                         field = mono_field_from_token (image, token, &klass, generic_context);
4404                         mono_class_init (klass);
4405
4406                         if ((*ip) == CEE_STSFLD)
4407                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4408
4409                         if (cfg->domain->special_static_fields)
4410                                 addr = g_hash_table_lookup (cfg->domain->special_static_fields, field);
4411
4412                         if ((cfg->opt & MONO_OPT_SHARED) || (mono_compile_aot && addr)) {
4413                                 int temp;
4414                                 MonoInst *iargs [2];
4415                                 g_assert (field->parent);
4416                                 NEW_TEMPLOAD (cfg, iargs [0], mono_get_domainvar (cfg)->inst_c0);
4417                                 NEW_FIELDCONST (cfg, iargs [1], field);
4418                                 temp = mono_emit_jit_icall (cfg, bblock, mono_class_static_field_address, iargs, ip);
4419                                 NEW_TEMPLOAD (cfg, ins, temp);
4420                         } else {
4421                                 MonoVTable *vtable;
4422                                 vtable = mono_class_vtable (cfg->domain, klass);
4423                                 if (!addr) {
4424                                         if ((!vtable->initialized || mono_compile_aot) && !(klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) && mono_class_needs_cctor_run (klass, method)) {
4425                                                 guint8 *tramp = mono_create_class_init_trampoline (vtable);
4426                                                 mono_emit_native_call (cfg, bblock, tramp, 
4427                                                                                            helper_sig_class_init_trampoline,
4428                                                                                            NULL, ip, FALSE);
4429                                                 if (cfg->verbose_level > 2)
4430                                                         g_print ("class %s.%s needs init call for %s\n", klass->name_space, klass->name, field->name);
4431                                         } else {
4432                                                 if (cfg->run_cctors)
4433                                                         mono_runtime_class_init (vtable);
4434                                         }
4435                                         addr = (char*)vtable->data + field->offset;
4436
4437                                         if (mono_compile_aot)
4438                                                 NEW_SFLDACONST (cfg, ins, field);
4439                                         else
4440                                                 NEW_PCONST (cfg, ins, addr);
4441                                         ins->cil_code = ip;
4442                                 } else {
4443                                         /* 
4444                                          * insert call to mono_threads_get_static_data (GPOINTER_TO_UINT (addr)) 
4445                                          * This could be later optimized to do just a couple of
4446                                          * memory dereferences with constant offsets.
4447                                          */
4448                                         int temp;
4449                                         MonoInst *iargs [1];
4450                                         NEW_ICONST (cfg, iargs [0], GPOINTER_TO_UINT (addr));
4451                                         temp = mono_emit_jit_icall (cfg, bblock, mono_get_special_static_data, iargs, ip);
4452                                         NEW_TEMPLOAD (cfg, ins, temp);
4453                                 }
4454                         }
4455
4456                         /* FIXME: mark instructions for use in SSA */
4457                         if (*ip == CEE_LDSFLDA) {
4458                                 *sp++ = ins;
4459                         } else if (*ip == CEE_STSFLD) {
4460                                 MonoInst *store;
4461                                 CHECK_STACK (1);
4462                                 sp--;
4463                                 MONO_INST_NEW (cfg, store, mono_type_to_stind (field->type));
4464                                 store->cil_code = ip;
4465                                 store->inst_left = ins;
4466                                 store->inst_right = sp [0];
4467                                 store->flags |= ins_flag;
4468                                 ins_flag = 0;
4469
4470                                 if (store->opcode == CEE_STOBJ) {
4471                                         handle_stobj (cfg, bblock, ins, sp [0], ip, mono_class_from_mono_type (field->type), FALSE, FALSE);
4472                                 } else
4473                                         MONO_ADD_INS (bblock, store);
4474                         } else {
4475                                 gboolean is_const = FALSE;
4476                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
4477                                 if (!((cfg->opt & MONO_OPT_SHARED) || mono_compile_aot) && 
4478                                     vtable->initialized && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY)) {
4479                                         gpointer addr = (char*)vtable->data + field->offset;
4480                                         /* g_print ("RO-FIELD %s.%s:%s\n", klass->name_space, klass->name, field->name);*/
4481                                         is_const = TRUE;
4482                                         switch (field->type->type) {
4483                                         case MONO_TYPE_BOOLEAN:
4484                                         case MONO_TYPE_U1:
4485                                                 NEW_ICONST (cfg, *sp, *((guint8 *)addr));
4486                                                 sp++;
4487                                                 break;
4488                                         case MONO_TYPE_I1:
4489                                                 NEW_ICONST (cfg, *sp, *((gint8 *)addr));
4490                                                 sp++;
4491                                                 break;                                          
4492                                         case MONO_TYPE_CHAR:
4493                                         case MONO_TYPE_U2:
4494                                                 NEW_ICONST (cfg, *sp, *((guint16 *)addr));
4495                                                 sp++;
4496                                                 break;
4497                                         case MONO_TYPE_I2:
4498                                                 NEW_ICONST (cfg, *sp, *((gint16 *)addr));
4499                                                 sp++;
4500                                                 break;
4501                                                 break;
4502                                         case MONO_TYPE_I4:
4503                                                 NEW_ICONST (cfg, *sp, *((gint32 *)addr));
4504                                                 sp++;
4505                                                 break;                                          
4506                                         case MONO_TYPE_U4:
4507                                                 NEW_ICONST (cfg, *sp, *((guint32 *)addr));
4508                                                 sp++;
4509                                                 break;
4510                                         case MONO_TYPE_I:
4511                                         case MONO_TYPE_U:
4512                                         case MONO_TYPE_STRING:
4513                                         case MONO_TYPE_OBJECT:
4514                                         case MONO_TYPE_CLASS:
4515                                         case MONO_TYPE_SZARRAY:
4516                                         case MONO_TYPE_PTR:
4517                                         case MONO_TYPE_FNPTR:
4518                                         case MONO_TYPE_ARRAY:
4519                                                 NEW_PCONST (cfg, *sp, *((gpointer *)addr));
4520                                                 type_to_eval_stack_type (field->type, *sp);
4521                                                 sp++;
4522                                                 break;
4523                                         case MONO_TYPE_I8:
4524                                         case MONO_TYPE_U8:
4525                                                 MONO_INST_NEW (cfg, *sp, OP_I8CONST);
4526                                                 sp [0]->type = STACK_I8;
4527                                                 sp [0]->inst_l = *((gint64 *)addr);
4528                                                 sp++;
4529                                                 break;
4530                                         case MONO_TYPE_R4:
4531                                         case MONO_TYPE_R8:
4532                                         case MONO_TYPE_VALUETYPE:
4533                                         default:
4534                                                 is_const = FALSE;
4535                                                 break;
4536                                         }
4537                                 }
4538
4539                                 if (!is_const) {
4540                                         MonoInst *load;
4541                                         CHECK_STACK_OVF (1);
4542                                         MONO_INST_NEW (cfg, load, mono_type_to_ldind (field->type));
4543                                         type_to_eval_stack_type (field->type, load);
4544                                         load->cil_code = ip;
4545                                         load->inst_left = ins;
4546                                         *sp++ = load;
4547                                         load->flags |= ins_flag;
4548                                         ins_flag = 0;
4549                                         /* fixme: dont see the problem why this does not work */
4550                                         //cfg->disable_aot = TRUE;
4551                                 }
4552                         }
4553                         ip += 5;
4554                         break;
4555                 }
4556                 case CEE_STOBJ:
4557                         CHECK_STACK (2);
4558                         sp -= 2;
4559                         CHECK_OPSIZE (5);
4560                         token = read32 (ip + 1);
4561                         if (method->wrapper_type != MONO_WRAPPER_NONE)
4562                                 klass = mono_method_get_wrapper_data (method, token);
4563                         else
4564                                 klass = mono_class_get_full (image, token, generic_context);
4565                         mono_class_init (klass);
4566                         n = mono_type_to_stind (&klass->byval_arg);
4567                         if (n == CEE_STOBJ) {
4568                                 handle_stobj (cfg, bblock, sp [0], sp [1], ip, klass, FALSE, FALSE);
4569                         } else {
4570                                 /* FIXME: should check item at sp [1] is compatible with the type of the store. */
4571                                 MonoInst *store;
4572                                 MONO_INST_NEW (cfg, store, n);
4573                                 store->cil_code = ip;
4574                                 store->inst_left = sp [0];
4575                                 store->inst_right = sp [1];
4576                                 store->flags |= ins_flag;
4577                                 MONO_ADD_INS (bblock, store);
4578                         }
4579                         ins_flag = 0;
4580                         ip += 5;
4581                         inline_costs += 1;
4582                         break;
4583                 case CEE_BOX: {
4584                         MonoInst *val;
4585                         CHECK_STACK (1);
4586                         --sp;
4587                         val = *sp;
4588                         CHECK_OPSIZE (5);
4589                         token = read32 (ip + 1);
4590                         if (method->wrapper_type != MONO_WRAPPER_NONE)
4591                                 klass = mono_method_get_wrapper_data (method, token);
4592                         else
4593                                 klass = mono_class_get_full (image, token, generic_context);
4594                         mono_class_init (klass);
4595
4596                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
4597                                 *sp++ = val;
4598                                 ip += 5;
4599                                 break;
4600                         }
4601                         *sp++ = handle_box (cfg, bblock, val, ip, klass);
4602                         ip += 5;
4603                         inline_costs += 1;
4604                         break;
4605                 }
4606                 case CEE_NEWARR:
4607                         CHECK_STACK (1);
4608                         MONO_INST_NEW (cfg, ins, *ip);
4609                         ins->cil_code = ip;
4610                         --sp;
4611
4612                         CHECK_OPSIZE (5);
4613                         token = read32 (ip + 1);
4614
4615                         /* allocate the domainvar - becaus this is used in decompose_foreach */
4616                         if (cfg->opt & MONO_OPT_SHARED)
4617                                 mono_get_domainvar (cfg);
4618                         
4619                         if (method->wrapper_type != MONO_WRAPPER_NONE)
4620                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
4621                         else
4622                                 klass = mono_class_get_full (image, token, generic_context);
4623
4624                         mono_class_init (klass);
4625                         ins->inst_newa_class = klass;
4626                         ins->inst_newa_len = *sp;
4627                         ins->type = STACK_OBJ;
4628                         ip += 5;
4629                         *sp++ = ins;
4630                         /* 
4631                          * we store the object so calls to create the array are not interleaved
4632                          * with the arguments of other calls.
4633                          */
4634                         if (1) {
4635                                 MonoInst *store, *temp, *load;
4636                                 --sp;
4637                                 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
4638                                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
4639                                 store->cil_code = ins->cil_code;
4640                                 MONO_ADD_INS (bblock, store);
4641                                 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
4642                                 load->cil_code = ins->cil_code;
4643                                 *sp++ = load;
4644                         }
4645                         inline_costs += 1;
4646                         break;
4647                 case CEE_LDLEN:
4648                         CHECK_STACK (1);
4649                         MONO_INST_NEW (cfg, ins, *ip);
4650                         ins->cil_code = ip++;
4651                         --sp;
4652                         ins->inst_left = *sp;
4653                         ins->type = STACK_PTR;
4654                         *sp++ = ins;
4655                         break;
4656                 case CEE_LDELEMA:
4657                         CHECK_STACK (2);
4658                         sp -= 2;
4659                         CHECK_OPSIZE (5);
4660
4661                         if (method->wrapper_type != MONO_WRAPPER_NONE)
4662                                 klass = (MonoClass*)mono_method_get_wrapper_data (method, read32 (ip + 1));
4663                         else
4664                                 klass = mono_class_get_full (image, read32 (ip + 1), generic_context);
4665                         mono_class_init (klass);
4666                         NEW_LDELEMA (cfg, ins, sp, klass);
4667                         ins->cil_code = ip;
4668                         *sp++ = ins;
4669                         ip += 5;
4670                         break;
4671                 case CEE_LDELEM: {
4672                         MonoInst *load;
4673                         CHECK_STACK (2);
4674                         sp -= 2;
4675                         CHECK_OPSIZE (5);
4676                         token = read32 (ip + 1);
4677                         klass = mono_class_get_full (image, token, generic_context);
4678                         mono_class_init (klass);
4679                         NEW_LDELEMA (cfg, load, sp, klass);
4680                         load->cil_code = ip;
4681                         MONO_INST_NEW (cfg, ins, mono_type_to_ldind (&klass->byval_arg));
4682                         ins->cil_code = ip;
4683                         ins->inst_left = load;
4684                         *sp++ = ins;
4685                         type_to_eval_stack_type (&klass->byval_arg, ins);
4686                         ip += 5;
4687                         break;
4688                 }
4689                 case CEE_LDELEM_I1:
4690                 case CEE_LDELEM_U1:
4691                 case CEE_LDELEM_I2:
4692                 case CEE_LDELEM_U2:
4693                 case CEE_LDELEM_I4:
4694                 case CEE_LDELEM_U4:
4695                 case CEE_LDELEM_I8:
4696                 case CEE_LDELEM_I:
4697                 case CEE_LDELEM_R4:
4698                 case CEE_LDELEM_R8:
4699                 case CEE_LDELEM_REF: {
4700                         MonoInst *load;
4701                         /*
4702                          * translate to:
4703                          * ldind.x (ldelema (array, index))
4704                          * ldelema does the bounds check
4705                          */
4706                         CHECK_STACK (2);
4707                         sp -= 2;
4708                         klass = array_access_to_klass (*ip);
4709                         NEW_LDELEMA (cfg, load, sp, klass);
4710                         load->cil_code = ip;
4711                         MONO_INST_NEW (cfg, ins, ldelem_to_ldind [*ip - CEE_LDELEM_I1]);
4712                         ins->cil_code = ip;
4713                         ins->inst_left = load;
4714                         *sp++ = ins;
4715                         ins->type = ldind_type [ins->opcode - CEE_LDIND_I1];
4716                         ++ip;
4717                         break;
4718                 }
4719                 case CEE_STELEM_I:
4720                 case CEE_STELEM_I1:
4721                 case CEE_STELEM_I2:
4722                 case CEE_STELEM_I4:
4723                 case CEE_STELEM_I8:
4724                 case CEE_STELEM_R4:
4725                 case CEE_STELEM_R8: {
4726                         MonoInst *load;
4727                         /*
4728                          * translate to:
4729                          * stind.x (ldelema (array, index), val)
4730                          * ldelema does the bounds check
4731                          */
4732                         CHECK_STACK (3);
4733                         sp -= 3;
4734                         klass = array_access_to_klass (*ip);
4735                         NEW_LDELEMA (cfg, load, sp, klass);
4736                         load->cil_code = ip;
4737                         MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
4738                         ins->cil_code = ip;
4739                         ins->inst_left = load;
4740                         ins->inst_right = sp [2];
4741                         ++ip;
4742                         handle_loaded_temps (cfg, bblock, stack_start, sp);
4743                         MONO_ADD_INS (bblock, ins);
4744                         inline_costs += 1;
4745                         break;
4746                 }
4747                 case CEE_STELEM: {
4748                         MonoInst *load;
4749                         /*
4750                          * translate to:
4751                          * stind.x (ldelema (array, index), val)
4752                          * ldelema does the bounds check
4753                          */
4754                         CHECK_STACK (3);
4755                         sp -= 3;
4756                         CHECK_OPSIZE (5);
4757                         token = read32 (ip + 1);
4758                         klass = mono_class_get_full (image, token, generic_context);
4759                         mono_class_init (klass);
4760                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
4761                                 MonoInst *iargs [3];
4762                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4763
4764                                 iargs [2] = sp [2];
4765                                 iargs [1] = sp [1];
4766                                 iargs [0] = sp [0];
4767                         
4768                                 mono_emit_jit_icall (cfg, bblock, helper_stelem_ref, iargs, ip);
4769                         } else {
4770                                 NEW_LDELEMA (cfg, load, sp, klass);
4771                                 load->cil_code = ip;
4772
4773                                 n = mono_type_to_stind (&klass->byval_arg);
4774                                 if (n == CEE_STOBJ)
4775                                         handle_stobj (cfg, bblock, load, sp [2], ip, klass, FALSE, FALSE);
4776                                 else {
4777                                         MONO_INST_NEW (cfg, ins, n);
4778                                         ins->cil_code = ip;
4779                                         ins->inst_left = load;
4780                                         ins->inst_right = sp [2];
4781                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
4782                                         MONO_ADD_INS (bblock, ins);
4783                                 }
4784                         }
4785                         ip += 5;
4786                         inline_costs += 1;
4787                         break;
4788                 }
4789                 case CEE_STELEM_REF: {
4790                         MonoInst *iargs [3];
4791
4792                         CHECK_STACK (3);
4793                         sp -= 3;
4794
4795                         handle_loaded_temps (cfg, bblock, stack_start, sp);
4796
4797                         iargs [2] = sp [2];
4798                         iargs [1] = sp [1];
4799                         iargs [0] = sp [0];
4800                         
4801                         mono_emit_jit_icall (cfg, bblock, helper_stelem_ref, iargs, ip);
4802
4803                         /*
4804                         MonoInst *group;
4805                         NEW_GROUP (cfg, group, sp [0], sp [1]);
4806                         MONO_INST_NEW (cfg, ins, CEE_STELEM_REF);
4807                         ins->cil_code = ip;
4808                         ins->inst_left = group;
4809                         ins->inst_right = sp [2];
4810                         MONO_ADD_INS (bblock, ins);
4811                         */
4812
4813                         ++ip;
4814                         inline_costs += 1;
4815                         break;
4816                 }
4817                 case CEE_CKFINITE: {
4818                         MonoInst *store, *temp;
4819                         CHECK_STACK (1);
4820
4821                         /* this instr. can throw exceptions as side effect,
4822                          * so we cant eliminate dead code which contains CKFINITE opdodes.
4823                          * Spilling to memory makes sure that we always perform
4824                          * this check */
4825
4826                         
4827                         MONO_INST_NEW (cfg, ins, CEE_CKFINITE);
4828                         ins->cil_code = ip;
4829                         ins->inst_left = sp [-1];
4830                         temp = mono_compile_create_var (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL);
4831
4832                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
4833                         store->cil_code = ip;
4834                         MONO_ADD_INS (bblock, store);
4835
4836                         NEW_TEMPLOAD (cfg, sp [-1], temp->inst_c0);
4837                        
4838                         ++ip;
4839                         break;
4840                 }
4841                 case CEE_REFANYVAL:
4842                         CHECK_STACK (1);
4843                         MONO_INST_NEW (cfg, ins, *ip);
4844                         --sp;
4845                         CHECK_OPSIZE (5);
4846                         klass = mono_class_get_full (image, read32 (ip + 1), generic_context);
4847                         mono_class_init (klass);
4848                         ins->type = STACK_MP;
4849                         ins->inst_left = *sp;
4850                         ins->klass = klass;
4851                         ins->inst_newa_class = klass;
4852                         ins->cil_code = ip;
4853                         ip += 5;
4854                         *sp++ = ins;
4855                         break;
4856                 case CEE_MKREFANY: {
4857                         MonoInst *loc, *klassconst;
4858
4859                         CHECK_STACK (1);
4860                         MONO_INST_NEW (cfg, ins, *ip);
4861                         --sp;
4862                         CHECK_OPSIZE (5);
4863                         klass = mono_class_get_full (image, read32 (ip + 1), generic_context);
4864                         mono_class_init (klass);
4865                         ins->cil_code = ip;
4866
4867                         loc = mono_compile_create_var (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL);
4868                         NEW_TEMPLOADA (cfg, ins->inst_right, loc->inst_c0);
4869
4870                         NEW_PCONST (cfg, klassconst, klass);
4871                         NEW_GROUP (cfg, ins->inst_left, *sp, klassconst);
4872                         
4873                         MONO_ADD_INS (bblock, ins);
4874
4875                         NEW_TEMPLOAD (cfg, *sp, loc->inst_c0);
4876                         ++sp;
4877                         ip += 5;
4878                         break;
4879                 }
4880                 case CEE_LDTOKEN: {
4881                         gpointer handle;
4882                         MonoClass *handle_class;
4883
4884                         CHECK_STACK_OVF (1);
4885
4886                         CHECK_OPSIZE (5);
4887                         n = read32 (ip + 1);
4888
4889                         handle = mono_ldtoken (image, n, &handle_class, generic_context);
4890                         mono_class_init (handle_class);
4891
4892                         if (cfg->opt & MONO_OPT_SHARED) {
4893                                 int temp;
4894                                 MonoInst *res, *store, *addr, *vtvar, *iargs [2];
4895
4896                                 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL); 
4897
4898                                 NEW_IMAGECONST (cfg, iargs [0], image);
4899                                 NEW_ICONST (cfg, iargs [1], n);
4900                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldtoken_wrapper, iargs, ip);
4901                                 NEW_TEMPLOAD (cfg, res, temp);
4902                                 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
4903                                 NEW_INDSTORE (cfg, store, addr, res, &mono_defaults.int_class->byval_arg);
4904                                 MONO_ADD_INS (bblock, store);
4905                                 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
4906                         } else {
4907                                 if ((ip [5] == CEE_CALL) && (cmethod = mono_get_method_full (image, read32 (ip + 6), NULL, generic_context)) &&
4908                                                 (cmethod->klass == mono_defaults.monotype_class->parent) &&
4909                                                 (strcmp (cmethod->name, "GetTypeFromHandle") == 0)) {
4910                                         MonoClass *tclass = mono_class_from_mono_type (handle);
4911                                         mono_class_init (tclass);
4912                                         if (mono_compile_aot)
4913                                                 NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, image, n);
4914                                         else
4915                                                 NEW_PCONST (cfg, ins, mono_type_get_object (cfg->domain, handle));
4916                                         ins->type = STACK_OBJ;
4917                                         ins->klass = cmethod->klass;
4918                                         ip += 5;
4919                                 } else {
4920                                         if (mono_compile_aot)
4921                                                 NEW_LDTOKENCONST (cfg, ins, image, n);
4922                                         else
4923                                                 NEW_PCONST (cfg, ins, handle);
4924                                         ins->type = STACK_VTYPE;
4925                                         ins->klass = handle_class;
4926                                 }
4927                         }
4928
4929                         *sp++ = ins;
4930                         ip += 5;
4931                         break;
4932                 }
4933                 case CEE_CONV_U2:
4934                 case CEE_CONV_U1:
4935                 case CEE_CONV_I:
4936                         CHECK_STACK (1);
4937                         ADD_UNOP (*ip);
4938                         ip++;
4939                         break;
4940                 case CEE_ADD_OVF:
4941                 case CEE_ADD_OVF_UN:
4942                 case CEE_MUL_OVF:
4943                 case CEE_MUL_OVF_UN:
4944                 case CEE_SUB_OVF:
4945                 case CEE_SUB_OVF_UN:
4946                         CHECK_STACK (2);
4947                         ADD_BINOP (*ip);
4948                         ip++;
4949                         break;
4950                 case CEE_ENDFINALLY:
4951                         MONO_INST_NEW (cfg, ins, *ip);
4952                         MONO_ADD_INS (bblock, ins);
4953                         ins->cil_code = ip++;
4954                         start_new_bblock = 1;
4955
4956                         /*
4957                          * Control will leave the method so empty the stack, otherwise
4958                          * the next basic block will start with a nonempty stack.
4959                          */
4960                         while (sp != stack_start) {
4961                                 MONO_INST_NEW (cfg, ins, CEE_POP);
4962                                 ins->cil_code = ip;
4963                                 sp--;
4964                                 ins->inst_i0 = *sp;
4965                                 MONO_ADD_INS (bblock, ins);
4966                         }
4967                         break;
4968                 case CEE_LEAVE:
4969                 case CEE_LEAVE_S: {
4970                         GList *handlers;
4971                         if (*ip == CEE_LEAVE) {
4972                                 CHECK_OPSIZE (5);
4973                                 target = ip + 5 + (gint32)read32(ip + 1);
4974                         } else {
4975                                 CHECK_OPSIZE (2);
4976                                 target = ip + 2 + (signed char)(ip [1]);
4977                         }
4978
4979                         /* empty the stack */
4980                         while (sp != stack_start) {
4981                                 MONO_INST_NEW (cfg, ins, CEE_POP);
4982                                 ins->cil_code = ip;
4983                                 sp--;
4984                                 ins->inst_i0 = *sp;
4985                                 MONO_ADD_INS (bblock, ins);
4986                         }
4987
4988                         /* 
4989                          * If this leave statement is in a catch block, check for a
4990                          * pending exception, and rethrow it if necessary.
4991                          */
4992                         for (i = 0; i < header->num_clauses; ++i) {
4993                                 MonoExceptionClause *clause = &header->clauses [i];
4994                                 if (MONO_OFFSET_IN_HANDLER (clause, ip - header->code)) {
4995                                         int temp;
4996
4997                                         temp = mono_emit_jit_icall (cfg, bblock, mono_thread_get_pending_exception, NULL, ip);
4998                                         NEW_TEMPLOAD (cfg, *sp, temp);
4999
5000                                         MONO_INST_NEW (cfg, ins, OP_THROW_OR_NULL);
5001                                         ins->inst_left = *sp;
5002                                         ins->cil_code = ip;
5003                                         MONO_ADD_INS (bblock, ins);
5004                                 }
5005                         }
5006
5007                         /* fixme: call fault handler ? */
5008
5009                         if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
5010                                 GList *tmp;
5011                                 for (tmp = handlers; tmp; tmp = tmp->next) {
5012                                         tblock = tmp->data;
5013                                         link_bblock (cfg, bblock, tblock);
5014                                         MONO_INST_NEW (cfg, ins, OP_CALL_HANDLER);
5015                                         ins->cil_code = ip;
5016                                         ins->inst_target_bb = tblock;
5017                                         MONO_ADD_INS (bblock, ins);
5018                                 }
5019                                 g_list_free (handlers);
5020                         } 
5021
5022                         MONO_INST_NEW (cfg, ins, CEE_BR);
5023                         ins->cil_code = ip;
5024                         MONO_ADD_INS (bblock, ins);
5025                         GET_BBLOCK (cfg, bbhash, tblock, target);
5026                         link_bblock (cfg, bblock, tblock);
5027                         CHECK_BBLOCK (target, ip, tblock);
5028                         ins->inst_target_bb = tblock;
5029                         start_new_bblock = 1;
5030
5031                         if (*ip == CEE_LEAVE)
5032                                 ip += 5;
5033                         else
5034                                 ip += 2;
5035
5036                         break;
5037                 }
5038                 case CEE_STIND_I:
5039                         CHECK_STACK (2);
5040                         MONO_INST_NEW (cfg, ins, *ip);
5041                         sp -= 2;
5042                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5043                         MONO_ADD_INS (bblock, ins);
5044                         ins->cil_code = ip++;
5045                         ins->inst_i0 = sp [0];
5046                         ins->inst_i1 = sp [1];
5047                         inline_costs += 1;
5048                         break;
5049                 case CEE_CONV_U:
5050                         CHECK_STACK (1);
5051                         ADD_UNOP (*ip);
5052                         ip++;
5053                         break;
5054                 /* trampoline mono specific opcodes */
5055                 case MONO_CUSTOM_PREFIX: {
5056
5057                         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
5058
5059                         CHECK_OPSIZE (2);
5060                         switch (ip [1]) {
5061
5062                         case CEE_MONO_FUNC1: {
5063                                 int temp;
5064                                 gpointer func = NULL;
5065                                 CHECK_STACK (1);
5066                                 sp--;
5067
5068                                 CHECK_OPSIZE (3);
5069                                 switch (ip [2]) {
5070                                 case MONO_MARSHAL_CONV_STR_LPWSTR:
5071                                         func = mono_string_to_utf16;
5072                                         break;
5073                                 case MONO_MARSHAL_CONV_LPWSTR_STR:
5074                                         func = mono_string_from_utf16;
5075                                         break;
5076                                 case MONO_MARSHAL_CONV_LPSTR_STR:
5077                                         func = mono_string_new_wrapper;
5078                                         break;
5079                                 case MONO_MARSHAL_CONV_STR_LPTSTR:
5080                                 case MONO_MARSHAL_CONV_STR_LPSTR:
5081                                         func = mono_string_to_utf8;
5082                                         break;
5083                                 case MONO_MARSHAL_CONV_STR_BSTR:
5084                                         func = mono_string_to_bstr;
5085                                         break;
5086                                 case MONO_MARSHAL_CONV_STR_TBSTR:
5087                                 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
5088                                         func = mono_string_to_ansibstr;
5089                                         break;
5090                                 case MONO_MARSHAL_CONV_SB_LPSTR:
5091                                 case MONO_MARSHAL_CONV_SB_LPTSTR:
5092                                         func = mono_string_builder_to_utf8;
5093                                         break;
5094                                 case MONO_MARSHAL_CONV_SB_LPWSTR:
5095                                         func = mono_string_builder_to_utf16;
5096                                         break;
5097                                 case MONO_MARSHAL_CONV_ARRAY_SAVEARRAY:
5098                                         func = mono_array_to_savearray;
5099                                         break;
5100                                 case MONO_MARSHAL_CONV_ARRAY_LPARRAY:
5101                                         func = mono_array_to_lparray;
5102                                         break;
5103                                 case MONO_MARSHAL_CONV_DEL_FTN:
5104                                         func = mono_delegate_to_ftnptr;
5105                                         break;
5106                                 case MONO_MARSHAL_CONV_STRARRAY_STRLPARRAY:
5107                                         func = mono_marshal_string_array;
5108                                         break;
5109                                 default:
5110                                         g_warning ("unknown conversion %d\n", ip [2]);
5111                                         g_assert_not_reached ();
5112                                 }
5113
5114                                 temp = mono_emit_jit_icall (cfg, bblock, func, sp, ip);
5115                                 NEW_TEMPLOAD (cfg, *sp, temp);
5116                                 sp++;
5117
5118                                 ip += 3;
5119                                 inline_costs += 10 * num_calls++;
5120                                 break;
5121                         }
5122                         case CEE_MONO_PROC2: {
5123                                 gpointer func = NULL;
5124                                 CHECK_STACK (2);
5125                                 sp -= 2;
5126
5127                                 CHECK_OPSIZE (3);
5128                                 switch (ip [2]) {
5129                                 case MONO_MARSHAL_CONV_LPSTR_SB:
5130                                 case MONO_MARSHAL_CONV_LPTSTR_SB:
5131                                         func = mono_string_utf8_to_builder;
5132                                         break;
5133                                 case MONO_MARSHAL_CONV_LPWSTR_SB:
5134                                         func = mono_string_utf16_to_builder;
5135                                         break;
5136                                 case MONO_MARSHAL_FREE_ARRAY:
5137                                         func = mono_marshal_free_array;
5138                                         break;
5139                                 default:
5140                                         g_assert_not_reached ();
5141                                 }
5142
5143                                 mono_emit_jit_icall (cfg, bblock, func, sp, ip);
5144                                 ip += 3;
5145                                 inline_costs += 10 * num_calls++;
5146                                 break;
5147                         }
5148                         case CEE_MONO_PROC3: {
5149                                 gpointer func = NULL;
5150                                 CHECK_STACK (3);
5151                                 sp -= 3;
5152
5153                                 CHECK_OPSIZE (3);
5154                                 switch (ip [2]) {
5155                                 case MONO_MARSHAL_CONV_STR_BYVALSTR:
5156                                         func = mono_string_to_byvalstr;
5157                                         break;
5158                                 case MONO_MARSHAL_CONV_STR_BYVALWSTR:
5159                                         func = mono_string_to_byvalwstr;
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_FREE:
5171                                 CHECK_STACK (1);
5172                                 sp -= 1;
5173                                 mono_emit_jit_icall (cfg, bblock, g_free, sp, ip);
5174                                 ip += 2;
5175                                 inline_costs += 10 * num_calls++;
5176                                 break;
5177                         case CEE_MONO_LDPTR:
5178                                 CHECK_STACK_OVF (1);
5179                                 CHECK_OPSIZE (6);
5180                                 token = read32 (ip + 2);
5181                                 NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
5182                                 ins->cil_code = ip;
5183                                 *sp++ = ins;
5184                                 ip += 6;
5185                                 inline_costs += 10 * num_calls++;
5186                                 break;
5187                         case CEE_MONO_VTADDR:
5188                                 CHECK_STACK (1);
5189                                 --sp;
5190                                 MONO_INST_NEW (cfg, ins, OP_VTADDR);
5191                                 ins->cil_code = ip;
5192                                 ins->type = STACK_MP;
5193                                 ins->inst_left = *sp;
5194                                 *sp++ = ins;
5195                                 ip += 2;
5196                                 break;
5197                         case CEE_MONO_NEWOBJ: {
5198                                 MonoInst *iargs [2];
5199                                 int temp;
5200                                 CHECK_STACK_OVF (1);
5201                                 CHECK_OPSIZE (6);
5202                                 token = read32 (ip + 2);
5203                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
5204                                 mono_class_init (klass);
5205                                 NEW_DOMAINCONST (cfg, iargs [0]);
5206                                 NEW_CLASSCONST (cfg, iargs [1], klass);
5207                                 temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
5208                                 NEW_TEMPLOAD (cfg, *sp, temp);
5209                                 sp++;
5210                                 ip += 6;
5211                                 inline_costs += 10 * num_calls++;
5212                                 break;
5213                         }
5214                         case CEE_MONO_OBJADDR:
5215                                 CHECK_STACK (1);
5216                                 --sp;
5217                                 MONO_INST_NEW (cfg, ins, OP_OBJADDR);
5218                                 ins->cil_code = ip;
5219                                 ins->type = STACK_MP;
5220                                 ins->inst_left = *sp;
5221                                 *sp++ = ins;
5222                                 ip += 2;
5223                                 break;
5224                         case CEE_MONO_LDNATIVEOBJ:
5225                                 CHECK_STACK (1);
5226                                 CHECK_OPSIZE (6);
5227                                 token = read32 (ip + 2);
5228                                 klass = mono_method_get_wrapper_data (method, token);
5229                                 g_assert (klass->valuetype);
5230                                 mono_class_init (klass);
5231                                 NEW_INDLOAD (cfg, ins, sp [-1], &klass->byval_arg);
5232                                 sp [-1] = ins;
5233                                 ip += 6;
5234                                 break;
5235                         case CEE_MONO_RETOBJ:
5236                                 g_assert (cfg->ret);
5237                                 g_assert (method->signature->pinvoke); 
5238                                 CHECK_STACK (1);
5239                                 --sp;
5240                                 
5241                                 CHECK_OPSIZE (6);
5242                                 token = read32 (ip + 2);    
5243                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
5244
5245                                 NEW_RETLOADA (cfg, ins);
5246                                 handle_stobj (cfg, bblock, ins, *sp, ip, klass, FALSE, TRUE);
5247                                 
5248                                 if (sp != stack_start)
5249                                         goto unverified;
5250                                 
5251                                 MONO_INST_NEW (cfg, ins, CEE_BR);
5252                                 ins->cil_code = ip;
5253                                 ins->inst_target_bb = end_bblock;
5254                                 MONO_ADD_INS (bblock, ins);
5255                                 link_bblock (cfg, bblock, end_bblock);
5256                                 start_new_bblock = 1;
5257                                 ip += 6;
5258                                 break;
5259                         case CEE_MONO_CISINST:
5260                         case CEE_MONO_CCASTCLASS: {
5261                                 int token;
5262                                 CHECK_STACK (1);
5263                                 --sp;
5264                                 CHECK_OPSIZE (6);
5265                                 token = read32 (ip + 2);
5266                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
5267                                 MONO_INST_NEW (cfg, ins, (ip [1] == CEE_MONO_CISINST) ? OP_CISINST : OP_CCASTCLASS);
5268                                 ins->type = STACK_I4;
5269                                 ins->inst_left = *sp;
5270                                 ins->inst_newa_class = klass;
5271                                 ins->cil_code = ip;
5272                                 *sp++ = ins;
5273                                 ip += 6;
5274                                 break;
5275                         }
5276                         default:
5277                                 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
5278                                 break;
5279                         }
5280                         break;
5281                 }
5282                 case CEE_PREFIX1: {
5283                         CHECK_OPSIZE (2);
5284                         switch (ip [1]) {
5285                         case CEE_ARGLIST: {
5286                                 /* somewhat similar to LDTOKEN */
5287                                 MonoInst *addr, *vtvar;
5288                                 CHECK_STACK_OVF (1);
5289                                 vtvar = mono_compile_create_var (cfg, &mono_defaults.argumenthandle_class->byval_arg, OP_LOCAL); 
5290
5291                                 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
5292                                 addr->cil_code = ip;
5293                                 MONO_INST_NEW (cfg, ins, OP_ARGLIST);
5294                                 ins->cil_code = ip;
5295                                 ins->inst_left = addr;
5296                                 MONO_ADD_INS (bblock, ins);
5297                                 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
5298                                 ins->cil_code = ip;
5299                                 *sp++ = ins;
5300                                 ip += 2;
5301                                 break;
5302                         }
5303                         case CEE_CEQ:
5304                         case CEE_CGT:
5305                         case CEE_CGT_UN:
5306                         case CEE_CLT:
5307                         case CEE_CLT_UN: {
5308                                 MonoInst *cmp;
5309                                 CHECK_STACK (2);
5310                                 /*
5311                                  * The following transforms:
5312                                  *    CEE_CEQ    into OP_CEQ
5313                                  *    CEE_CGT    into OP_CGT
5314                                  *    CEE_CGT_UN into OP_CGT_UN
5315                                  *    CEE_CLT    into OP_CLT
5316                                  *    CEE_CLT_UN into OP_CLT_UN
5317                                  */
5318                                 MONO_INST_NEW (cfg, cmp, 256 + ip [1]);
5319                                 
5320                                 MONO_INST_NEW (cfg, ins, cmp->opcode);
5321                                 sp -= 2;
5322                                 cmp->inst_i0 = sp [0];
5323                                 cmp->inst_i1 = sp [1];
5324                                 cmp->cil_code = ip;
5325                                 type_from_op (cmp);
5326                                 CHECK_TYPE (cmp);
5327                                 cmp->opcode = OP_COMPARE;
5328                                 ins->cil_code = ip;
5329                                 ins->type = STACK_I4;
5330                                 ins->inst_i0 = cmp;
5331                                 *sp++ = ins;
5332                                 ip += 2;
5333                                 break;
5334                         }
5335                         case CEE_LDFTN: {
5336                                 MonoInst *argconst;
5337                                 int temp;
5338
5339                                 CHECK_STACK_OVF (1);
5340                                 CHECK_OPSIZE (6);
5341                                 n = read32 (ip + 2);
5342                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
5343                                         cmethod = mono_method_get_wrapper_data (method, n);
5344                                 else {
5345                                         cmethod = mono_get_method_full (image, n, NULL, generic_context);
5346                                 }
5347
5348                                 mono_class_init (cmethod->klass);
5349                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
5350
5351                                 NEW_METHODCONST (cfg, argconst, cmethod);
5352                                 if (method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED)
5353                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn, &argconst, ip);
5354                                 else
5355                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn_nosync, &argconst, ip);
5356                                 NEW_TEMPLOAD (cfg, *sp, temp);
5357                                 sp ++;
5358                                 
5359                                 ip += 6;
5360                                 inline_costs += 10 * num_calls++;
5361                                 break;
5362                         }
5363                         case CEE_LDVIRTFTN: {
5364                                 MonoInst *args [2];
5365                                 int temp;
5366
5367                                 CHECK_STACK (1);
5368                                 CHECK_OPSIZE (6);
5369                                 n = read32 (ip + 2);
5370                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
5371                                         cmethod = mono_method_get_wrapper_data (method, n);
5372                                 else
5373                                         cmethod = mono_get_method_full (image, n, NULL, generic_context);
5374
5375                                 mono_class_init (cmethod->klass);
5376                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
5377
5378                                 --sp;
5379                                 args [0] = *sp;
5380                                 NEW_METHODCONST (cfg, args [1], cmethod);
5381                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldvirtfn, args, ip);
5382                                 NEW_TEMPLOAD (cfg, *sp, temp);
5383                                 sp ++;
5384
5385                                 ip += 6;
5386                                 inline_costs += 10 * num_calls++;
5387                                 break;
5388                         }
5389                         case CEE_LDARG:
5390                                 CHECK_STACK_OVF (1);
5391                                 CHECK_OPSIZE (4);
5392                                 n = read16 (ip + 2);
5393                                 CHECK_ARG (n);
5394                                 NEW_ARGLOAD (cfg, ins, n);
5395                                 ins->cil_code = ip;
5396                                 *sp++ = ins;
5397                                 ip += 4;
5398                                 break;
5399                         case CEE_LDARGA:
5400                                 CHECK_STACK_OVF (1);
5401                                 CHECK_OPSIZE (4);
5402                                 n = read16 (ip + 2);
5403                                 CHECK_ARG (n);
5404                                 NEW_ARGLOADA (cfg, ins, n);
5405                                 ins->cil_code = ip;
5406                                 *sp++ = ins;
5407                                 ip += 4;
5408                                 break;
5409                         case CEE_STARG:
5410                                 CHECK_STACK (1);
5411                                 --sp;
5412                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
5413                                 CHECK_OPSIZE (4);
5414                                 n = read16 (ip + 2);
5415                                 CHECK_ARG (n);
5416                                 NEW_ARGSTORE (cfg, ins, n, *sp);
5417                                 ins->cil_code = ip;
5418                                 if (ins->opcode == CEE_STOBJ) {
5419                                         NEW_ARGLOADA (cfg, ins, n);
5420                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
5421                                 } else
5422                                         MONO_ADD_INS (bblock, ins);
5423                                 ip += 4;
5424                                 break;
5425                         case CEE_LDLOC:
5426                                 CHECK_STACK_OVF (1);
5427                                 CHECK_OPSIZE (4);
5428                                 n = read16 (ip + 2);
5429                                 CHECK_LOCAL (n);
5430                                 NEW_LOCLOAD (cfg, ins, n);
5431                                 ins->cil_code = ip;
5432                                 *sp++ = ins;
5433                                 ip += 4;
5434                                 break;
5435                         case CEE_LDLOCA:
5436                                 CHECK_STACK_OVF (1);
5437                                 CHECK_OPSIZE (4);
5438                                 n = read16 (ip + 2);
5439                                 CHECK_LOCAL (n);
5440                                 NEW_LOCLOADA (cfg, ins, n);
5441                                 ins->cil_code = ip;
5442                                 *sp++ = ins;
5443                                 ip += 4;
5444                                 break;
5445                         case CEE_STLOC:
5446                                 CHECK_STACK (1);
5447                                 --sp;
5448                                 CHECK_OPSIZE (4);
5449                                 n = read16 (ip + 2);
5450                                 CHECK_LOCAL (n);
5451                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
5452                                 NEW_LOCSTORE (cfg, ins, n, *sp);
5453                                 ins->cil_code = ip;
5454                                 if (ins->opcode == CEE_STOBJ) {
5455                                         NEW_LOCLOADA (cfg, ins, n);
5456                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
5457                                 } else
5458                                         MONO_ADD_INS (bblock, ins);
5459                                 ip += 4;
5460                                 inline_costs += 1;
5461                                 break;
5462                         case CEE_LOCALLOC:
5463                                 CHECK_STACK (1);
5464                                 --sp;
5465                                 if (sp != stack_start) 
5466                                         goto unverified;
5467                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
5468                                 ins->inst_left = *sp;
5469                                 ins->cil_code = ip;
5470
5471                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
5472                                 if (header->init_locals)
5473                                         ins->flags |= MONO_INST_INIT;
5474
5475                                 *sp++ = ins;
5476                                 ip += 2;
5477                                 /* FIXME: set init flag if locals init is set in this method */
5478                                 break;
5479                         case CEE_ENDFILTER: {
5480                                 MonoExceptionClause *clause, *nearest;
5481                                 int cc, nearest_num;
5482
5483                                 CHECK_STACK (1);
5484                                 --sp;
5485                                 if ((sp != stack_start) || (sp [0]->type != STACK_I4)) 
5486                                         goto unverified;
5487                                 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
5488                                 ins->inst_left = *sp;
5489                                 ins->cil_code = ip;
5490                                 MONO_ADD_INS (bblock, ins);
5491                                 start_new_bblock = 1;
5492                                 ip += 2;
5493
5494                                 nearest = NULL;
5495                                 nearest_num = 0;
5496                                 for (cc = 0; cc < header->num_clauses; ++cc) {
5497                                         clause = &header->clauses [cc];
5498                                         if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
5499                                             (!nearest || (clause->token_or_filter > nearest->token_or_filter))) {
5500                                                 nearest = clause;
5501                                                 nearest_num = cc;
5502                                         }
5503                                 }
5504                                 g_assert (nearest);
5505                                 filter_lengths [nearest_num] = (ip - header->code) -  nearest->token_or_filter;
5506
5507                                 break;
5508                         }
5509                         case CEE_UNALIGNED_:
5510                                 ins_flag |= MONO_INST_UNALIGNED;
5511                                 /* FIXME: record alignment? we can assume 1 for now */
5512                                 CHECK_OPSIZE (3);
5513                                 ip += 3;
5514                                 break;
5515                         case CEE_VOLATILE_:
5516                                 ins_flag |= MONO_INST_VOLATILE;
5517                                 ip += 2;
5518                                 break;
5519                         case CEE_TAIL_:
5520                                 ins_flag |= MONO_INST_TAILCALL;
5521                                 /* Can't inline tail calls at this time */
5522                                 inline_costs += 100000;
5523                                 ip += 2;
5524                                 break;
5525                         case CEE_INITOBJ:
5526                                 CHECK_STACK (1);
5527                                 --sp;
5528                                 CHECK_OPSIZE (6);
5529                                 token = read32 (ip + 2);
5530                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
5531                                         klass = mono_method_get_wrapper_data (method, token);
5532                                 else
5533                                         klass = mono_class_get_full (image, token, generic_context);
5534                                 if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
5535                                         MonoInst *store, *load;
5536                                         NEW_PCONST (cfg, load, NULL);
5537                                         load->cil_code = ip;
5538                                         load->type = STACK_OBJ;
5539                                         MONO_INST_NEW (cfg, store, CEE_STIND_REF);
5540                                         store->cil_code = ip;
5541                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5542                                         MONO_ADD_INS (bblock, store);
5543                                         store->inst_i0 = sp [0];
5544                                         store->inst_i1 = load;
5545                                 } else {
5546                                         handle_initobj (cfg, bblock, *sp, NULL, klass, stack_start, sp);
5547                                 }
5548                                 ip += 6;
5549                                 inline_costs += 1;
5550                                 break;
5551                         case CEE_CONSTRAINED_:
5552                                 /* FIXME: implement */
5553                                 CHECK_OPSIZE (6);
5554                                 token = read32 (ip + 2);
5555                                 constrained_call = mono_class_get_full (image, token, generic_context);
5556                                 ip += 6;
5557                                 break;
5558                         case CEE_CPBLK:
5559                         case CEE_INITBLK: {
5560                                 MonoInst *iargs [3];
5561                                 CHECK_STACK (3);
5562                                 sp -= 3;
5563                                 if ((cfg->opt & MONO_OPT_INTRINS) && (ip [1] == CEE_CPBLK) && (sp [2]->opcode == OP_ICONST) && ((n = sp [2]->inst_c0) <= sizeof (gpointer) * 5)) {
5564                                         MonoInst *copy;
5565                                         MONO_INST_NEW (cfg, copy, OP_MEMCPY);
5566                                         copy->inst_left = sp [0];
5567                                         copy->inst_right = sp [1];
5568                                         copy->cil_code = ip;
5569                                         copy->unused = n;
5570                                         MONO_ADD_INS (bblock, copy);
5571                                         ip += 2;
5572                                         break;
5573                                 }
5574                                 iargs [0] = sp [0];
5575                                 iargs [1] = sp [1];
5576                                 iargs [2] = sp [2];
5577                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
5578                                 if (ip [1] == CEE_CPBLK) {
5579                                         mono_emit_jit_icall (cfg, bblock, helper_memcpy, iargs, ip);
5580                                 } else {
5581                                         mono_emit_jit_icall (cfg, bblock, helper_memset, iargs, ip);
5582                                 }
5583                                 ip += 2;
5584                                 inline_costs += 1;
5585                                 break;
5586                         }
5587                         case CEE_NO_:
5588                                 CHECK_OPSIZE (3);
5589                                 if (ip [2] & 0x1)
5590                                         ins_flag |= MONO_INST_NOTYPECHECK;
5591                                 if (ip [2] & 0x2)
5592                                         ins_flag |= MONO_INST_NORANGECHECK;
5593                                 /* we ignore the no-nullcheck for now since we
5594                                  * really do it explicitly only when doing callvirt->call
5595                                  */
5596                                 ip += 3;
5597                                 break;
5598                         case CEE_RETHROW: {
5599                                 MonoInst *load;
5600                                 /* FIXME: check we are in a catch handler */
5601                                 NEW_TEMPLOAD (cfg, load, cfg->exvar->inst_c0);
5602                                 load->cil_code = ip;
5603                                 MONO_INST_NEW (cfg, ins, CEE_THROW);
5604                                 ins->inst_left = load;
5605                                 ins->cil_code = ip;
5606                                 MONO_ADD_INS (bblock, ins);
5607                                 sp = stack_start;
5608                                 start_new_bblock = 1;
5609                                 ip += 2;
5610                                 break;
5611                         }
5612                         case CEE_SIZEOF:
5613                                 CHECK_STACK_OVF (1);
5614                                 CHECK_OPSIZE (6);
5615                                 token = read32 (ip + 2);
5616                                 /* FIXXME: handle generics. */
5617                                 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC) {
5618                                         MonoType *type = mono_type_create_from_typespec (image, token);
5619                                         token = mono_type_size (type, &align);
5620                                 } else {
5621                                         MonoClass *szclass = mono_class_get_full (image, token, generic_context);
5622                                         mono_class_init (szclass);
5623                                         token = mono_class_value_size (szclass, &align);
5624                                 }
5625                                 NEW_ICONST (cfg, ins, token);
5626                                 ins->cil_code = ip;
5627                                 *sp++= ins;
5628                                 ip += 6;
5629                                 break;
5630                         case CEE_REFANYTYPE:
5631                                 CHECK_STACK (1);
5632                                 MONO_INST_NEW (cfg, ins, OP_REFANYTYPE);
5633                                 --sp;
5634                                 ins->type = STACK_MP;
5635                                 ins->inst_left = *sp;
5636                                 ins->type = STACK_VTYPE;
5637                                 ins->klass = mono_defaults.typehandle_class;
5638                                 ins->cil_code = ip;
5639                                 ip += 2;
5640                                 *sp++ = ins;
5641                                 break;
5642                         case CEE_READONLY_:
5643                                 ip += 2;
5644                                 break;
5645                         default:
5646                                 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
5647                         }
5648                         break;
5649                 }
5650                 default:
5651                         g_error ("opcode 0x%02x not handled", *ip);
5652                 }
5653         }
5654         if (start_new_bblock != 1)
5655                 goto unverified;
5656
5657         bblock->cil_length = ip - bblock->cil_code;
5658         bblock->next_bb = end_bblock;
5659         link_bblock (cfg, bblock, end_bblock);
5660
5661         if (cfg->method == method && cfg->domainvar) {
5662                 MonoCallInst *call;
5663                 MonoInst *store;
5664
5665                 MONO_INST_NEW_CALL (cfg, call, CEE_CALL);
5666                 call->signature = helper_sig_domain_get;
5667                 call->inst.type = STACK_PTR;
5668                 call->fptr = mono_domain_get;
5669                 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, (MonoInst*)call);
5670                 
5671                 MONO_ADD_INS (init_localsbb, store);
5672         }
5673
5674         if (header->init_locals) {
5675                 MonoInst *store;
5676                 for (i = 0; i < header->num_locals; ++i) {
5677                         int t = header->locals [i]->type;
5678                         if (t == MONO_TYPE_VALUETYPE && header->locals [i]->data.klass->enumtype)
5679                                 t = header->locals [i]->data.klass->enum_basetype->type;
5680                         /* FIXME: use initobj for valuetypes, handle pointers, long, float. */
5681                         if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
5682                                 NEW_ICONST (cfg, ins, 0);
5683                                 NEW_LOCSTORE (cfg, store, i, ins);
5684                                 MONO_ADD_INS (init_localsbb, store);
5685                         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
5686                                 MONO_INST_NEW (cfg, ins, OP_I8CONST);
5687                                 ins->type = STACK_I8;
5688                                 ins->inst_l = 0;
5689                                 NEW_LOCSTORE (cfg, store, i, ins);
5690                                 MONO_ADD_INS (init_localsbb, store);
5691                         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
5692                                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
5693                                 ins->type = STACK_R8;
5694                                 ins->inst_p0 = (void*)&r8_0;
5695                                 NEW_LOCSTORE (cfg, store, i, ins);
5696                                 MONO_ADD_INS (init_localsbb, store);
5697                         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF)) {
5698                                 NEW_LOCLOADA (cfg, ins, i);
5699                                 handle_initobj (cfg, init_localsbb, ins, NULL, mono_class_from_mono_type (header->locals [i]), NULL, NULL);
5700                                 break;
5701                         } else {
5702                                 NEW_PCONST (cfg, ins, NULL);
5703                                 NEW_LOCSTORE (cfg, store, i, ins);
5704                                 MONO_ADD_INS (init_localsbb, store);
5705                         }
5706                 }
5707         }
5708
5709         
5710         /* resolve backward branches in the middle of an existing basic block */
5711         for (tmp = bb_recheck; tmp; tmp = tmp->next) {
5712                 bblock = tmp->data;
5713                 /*g_print ("need recheck in %s at IL_%04x\n", method->name, bblock->cil_code - header->code);*/
5714                 tblock = find_previous (bbhash, start_bblock, bblock->cil_code);
5715                 if (tblock != start_bblock) {
5716                         int l;
5717                         split_bblock (cfg, tblock, bblock);
5718                         l = bblock->cil_code - header->code;
5719                         bblock->cil_length = tblock->cil_length - l;
5720                         tblock->cil_length = l;
5721                 } else {
5722                         g_print ("recheck failed.\n");
5723                 }
5724         }
5725
5726         /*
5727          * we compute regions here, because the length of filter clauses is not known in advance.
5728          * It is computed in the CEE_ENDFILTER case in the above switch statement
5729          */
5730         if (cfg->method == method) {
5731                 MonoBasicBlock *bb;
5732                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5733                         bb->region = mono_find_block_region (cfg, bb->real_offset, filter_lengths);
5734                         if (cfg->spvars)
5735                                 mono_create_spvar_for_region (cfg, bb->region);
5736                         if (cfg->verbose_level > 2)
5737                                 g_print ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
5738                 }
5739         } else {
5740                 g_hash_table_destroy (bbhash);
5741         }
5742
5743         dont_inline = g_list_remove (dont_inline, method);
5744         return inline_costs;
5745
5746  inline_failure:
5747         if (cfg->method != method) 
5748                 g_hash_table_destroy (bbhash);
5749         dont_inline = g_list_remove (dont_inline, method);
5750         return -1;
5751
5752  unverified:
5753         if (cfg->method != method) 
5754                 g_hash_table_destroy (bbhash);
5755         g_error ("Invalid IL code at IL%04x in %s: %s\n", ip - header->code, 
5756                  mono_method_full_name (method, TRUE), mono_disasm_code_one (NULL, method, ip, NULL));
5757         dont_inline = g_list_remove (dont_inline, method);
5758         return -1;
5759 }
5760
5761 void
5762 mono_print_tree (MonoInst *tree) {
5763         int arity;
5764
5765         if (!tree)
5766                 return;
5767
5768         arity = mono_burg_arity [tree->opcode];
5769
5770         printf (" %s%s", arity?"(":"",  mono_inst_name (tree->opcode));
5771
5772         switch (tree->opcode) {
5773         case OP_ICONST:
5774                 printf ("[%d]", tree->inst_c0);
5775                 break;
5776         case OP_I8CONST:
5777                 printf ("[%lld]", tree->inst_l);
5778                 break;
5779         case OP_R8CONST:
5780                 printf ("[%f]", *(double*)tree->inst_p0);
5781                 break;
5782         case OP_R4CONST:
5783                 printf ("[%f]", *(float*)tree->inst_p0);
5784                 break;
5785         case OP_ARG:
5786         case OP_LOCAL:
5787                 printf ("[%d]", tree->inst_c0);
5788                 break;
5789         case OP_REGOFFSET:
5790                 if (tree->inst_offset < 0)
5791                         printf ("[-0x%x(%s)]", -tree->inst_offset, mono_arch_regname (tree->inst_basereg));
5792                 else
5793                         printf ("[0x%x(%s)]", tree->inst_offset, mono_arch_regname (tree->inst_basereg));
5794                 break;
5795         case OP_REGVAR:
5796                 printf ("[%s]", mono_arch_regname (tree->dreg));
5797                 break;
5798         case CEE_NEWARR:
5799                 printf ("[%s]",  tree->inst_newa_class->name);
5800                 mono_print_tree (tree->inst_newa_len);
5801                 break;
5802         case CEE_CALL:
5803         case CEE_CALLVIRT:
5804         case OP_FCALL:
5805         case OP_FCALLVIRT:
5806         case OP_LCALL:
5807         case OP_LCALLVIRT:
5808         case OP_VCALL:
5809         case OP_VCALLVIRT:
5810         case OP_VOIDCALL:
5811         case OP_VOIDCALLVIRT: {
5812                 MonoCallInst *call = (MonoCallInst*)tree;
5813                 if (call->method)
5814                         printf ("[%s]", call->method->name);
5815                 break;
5816         }
5817         case OP_PHI: {
5818                 int i;
5819                 printf ("[%d (", tree->inst_c0);
5820                 for (i = 0; i < tree->inst_phi_args [0]; i++) {
5821                         if (i)
5822                                 printf (", ");
5823                         printf ("%d", tree->inst_phi_args [i + 1]);
5824                 }
5825                 printf (")]");
5826                 break;
5827         }
5828         case OP_RENAME:
5829         case OP_RETARG:
5830         case CEE_NOP:
5831         case CEE_JMP:
5832         case CEE_BREAK:
5833                 break;
5834         case OP_LOAD_MEMBASE:
5835         case OP_LOADI4_MEMBASE:
5836         case OP_LOADU4_MEMBASE:
5837         case OP_LOADU1_MEMBASE:
5838         case OP_LOADI1_MEMBASE:
5839         case OP_LOADU2_MEMBASE:
5840         case OP_LOADI2_MEMBASE:
5841                 printf ("[%s] <- [%s + 0x%x]", mono_arch_regname (tree->dreg), mono_arch_regname (tree->inst_basereg), tree->inst_offset);
5842                 break;
5843         case CEE_BR:
5844                 printf ("[B%d]", tree->inst_target_bb->block_num);
5845                 break;
5846         case CEE_SWITCH:
5847         case CEE_ISINST:
5848         case CEE_CASTCLASS:
5849         case OP_OUTARG:
5850         case OP_CALL_REG:
5851         case OP_FCALL_REG:
5852         case OP_LCALL_REG:
5853         case OP_VCALL_REG:
5854         case OP_VOIDCALL_REG:
5855                 mono_print_tree (tree->inst_left);
5856                 break;
5857         case CEE_BNE_UN:
5858         case CEE_BEQ:
5859         case CEE_BLT:
5860         case CEE_BLT_UN:
5861         case CEE_BGT:
5862         case CEE_BGT_UN:
5863         case CEE_BGE:
5864         case CEE_BGE_UN:
5865         case CEE_BLE:
5866         case CEE_BLE_UN:
5867                 printf ("[B%dB%d]", tree->inst_true_bb->block_num, tree->inst_false_bb->block_num);
5868                 mono_print_tree (tree->inst_left);
5869                 break;
5870         default:
5871                 if (arity) {
5872                         mono_print_tree (tree->inst_left);
5873                         if (arity > 1)
5874                                 mono_print_tree (tree->inst_right);
5875                 }
5876                 break;
5877         }
5878
5879         if (arity)
5880                 printf (")");
5881 }
5882
5883 void
5884 mono_print_tree_nl (MonoInst *tree)
5885 {
5886         mono_print_tree (tree);
5887         printf ("\n");
5888 }
5889
5890 static void
5891 create_helper_signature (void)
5892 {
5893         /* FIXME: set call conv */
5894         /* MonoArray * mono_array_new (MonoDomain *domain, MonoClass *klass, gint32 len) */
5895         helper_sig_newarr = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
5896         helper_sig_newarr->params [0] = helper_sig_newarr->params [1] = &mono_defaults.int_class->byval_arg;
5897         helper_sig_newarr->ret = &mono_defaults.object_class->byval_arg;
5898         helper_sig_newarr->params [2] = &mono_defaults.int32_class->byval_arg;
5899         helper_sig_newarr->pinvoke = 1;
5900
5901         /* MonoArray * mono_array_new_specific (MonoVTable *vtable, guint32 len) */
5902         helper_sig_newarr_specific = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
5903         helper_sig_newarr_specific->params [0] = &mono_defaults.int_class->byval_arg;
5904         helper_sig_newarr_specific->params [1] = &mono_defaults.int32_class->byval_arg;
5905         helper_sig_newarr_specific->ret = &mono_defaults.object_class->byval_arg;
5906         helper_sig_newarr_specific->pinvoke = 1;
5907
5908         /* MonoObject * mono_object_new (MonoDomain *domain, MonoClass *klass) */
5909         helper_sig_object_new = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
5910         helper_sig_object_new->params [0] = helper_sig_object_new->params [1] = &mono_defaults.int_class->byval_arg;
5911         helper_sig_object_new->ret = &mono_defaults.object_class->byval_arg;
5912         helper_sig_object_new->pinvoke = 1;
5913
5914         /* MonoObject * mono_object_new_specific (MonoVTable *vtable) */
5915         helper_sig_object_new_specific = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
5916         helper_sig_object_new_specific->params [0] = &mono_defaults.int_class->byval_arg;
5917         helper_sig_object_new_specific->ret = &mono_defaults.object_class->byval_arg;
5918         helper_sig_object_new_specific->pinvoke = 1;
5919
5920         /* void* mono_method_compile (MonoMethod*) */
5921         helper_sig_compile = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
5922         helper_sig_compile->params [0] = helper_sig_compile->ret = &mono_defaults.int_class->byval_arg;
5923         helper_sig_compile->pinvoke = 1;
5924
5925         /* void* mono_ldvirtfn (MonoObject *, MonoMethod*) */
5926         helper_sig_compile_virt = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
5927         helper_sig_compile_virt->params [0] = &mono_defaults.object_class->byval_arg;
5928         helper_sig_compile_virt->params [1] = helper_sig_compile_virt->ret = &mono_defaults.int_class->byval_arg;
5929         helper_sig_compile_virt->pinvoke = 1;
5930
5931         /* MonoString* mono_ldstr (MonoDomain *domain, MonoImage *image, guint32 str_index) */
5932         helper_sig_ldstr = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
5933         helper_sig_ldstr->params [0] = helper_sig_ldstr->params [1] = &mono_defaults.int_class->byval_arg;
5934         helper_sig_ldstr->params [2] = &mono_defaults.int32_class->byval_arg;
5935         helper_sig_ldstr->ret = &mono_defaults.object_class->byval_arg;
5936         helper_sig_ldstr->pinvoke = 1;
5937
5938         /* MonoDomain *mono_domain_get (void) */
5939         helper_sig_domain_get = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
5940         helper_sig_domain_get->ret = &mono_defaults.int_class->byval_arg;
5941         helper_sig_domain_get->pinvoke = 1;
5942
5943         /* void* stelem_ref (MonoArray *, int index, MonoObject *) */
5944         helper_sig_stelem_ref = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
5945         helper_sig_stelem_ref->params [0] = &mono_defaults.array_class->byval_arg;
5946         helper_sig_stelem_ref->params [1] = &mono_defaults.int32_class->byval_arg;
5947         helper_sig_stelem_ref->params [2] = &mono_defaults.object_class->byval_arg;
5948         helper_sig_stelem_ref->ret = &mono_defaults.void_class->byval_arg;
5949         helper_sig_stelem_ref->pinvoke = 1;
5950
5951         /* void* stelem_ref_check (MonoArray *, MonoObject *) */
5952         helper_sig_stelem_ref_check = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
5953         helper_sig_stelem_ref_check->params [0] = &mono_defaults.array_class->byval_arg;
5954         helper_sig_stelem_ref_check->params [1] = &mono_defaults.object_class->byval_arg;
5955         helper_sig_stelem_ref_check->ret = &mono_defaults.void_class->byval_arg;
5956         helper_sig_stelem_ref_check->pinvoke = 1;
5957
5958         /* long amethod (long, long) */
5959         helper_sig_long_long_long = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
5960         helper_sig_long_long_long->params [0] = helper_sig_long_long_long->params [1] = 
5961                 &mono_defaults.int64_class->byval_arg;
5962         helper_sig_long_long_long->ret = &mono_defaults.int64_class->byval_arg;
5963         helper_sig_long_long_long->pinvoke = 1;
5964
5965         /* object  amethod (intptr) */
5966         helper_sig_obj_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
5967         helper_sig_obj_ptr->params [0] = &mono_defaults.int_class->byval_arg;
5968         helper_sig_obj_ptr->ret = &mono_defaults.object_class->byval_arg;
5969         helper_sig_obj_ptr->pinvoke = 1;
5970
5971         /* void amethod (intptr) */
5972         helper_sig_void_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
5973         helper_sig_void_ptr->params [0] = &mono_defaults.int_class->byval_arg;
5974         helper_sig_void_ptr->ret = &mono_defaults.void_class->byval_arg;
5975         helper_sig_void_ptr->pinvoke = 1;
5976
5977         /* void amethod (MonoObject *obj) */
5978         helper_sig_void_obj = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
5979         helper_sig_void_obj->params [0] = &mono_defaults.object_class->byval_arg;
5980         helper_sig_void_obj->ret = &mono_defaults.void_class->byval_arg;
5981         helper_sig_void_obj->pinvoke = 1;
5982
5983         /* intptr amethod (void) */
5984         helper_sig_ptr_void = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
5985         helper_sig_ptr_void->ret = &mono_defaults.int_class->byval_arg;
5986         helper_sig_ptr_void->pinvoke = 1;
5987
5988         /* object amethod (void) */
5989         helper_sig_obj_void = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
5990         helper_sig_obj_void->ret = &mono_defaults.object_class->byval_arg;
5991         helper_sig_obj_void->pinvoke = 1;
5992
5993         /* void  amethod (intptr, intptr) */
5994         helper_sig_void_ptr_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
5995         helper_sig_void_ptr_ptr->params [0] = &mono_defaults.int_class->byval_arg;
5996         helper_sig_void_ptr_ptr->params [1] = &mono_defaults.int_class->byval_arg;
5997         helper_sig_void_ptr_ptr->ret = &mono_defaults.void_class->byval_arg;
5998         helper_sig_void_ptr_ptr->pinvoke = 1;
5999
6000         /* void  amethod (intptr, intptr, intptr) */
6001         helper_sig_void_ptr_ptr_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
6002         helper_sig_void_ptr_ptr_ptr->params [0] = &mono_defaults.int_class->byval_arg;
6003         helper_sig_void_ptr_ptr_ptr->params [1] = &mono_defaults.int_class->byval_arg;
6004         helper_sig_void_ptr_ptr_ptr->params [2] = &mono_defaults.int_class->byval_arg;
6005         helper_sig_void_ptr_ptr_ptr->ret = &mono_defaults.void_class->byval_arg;
6006         helper_sig_void_ptr_ptr_ptr->pinvoke = 1;
6007
6008         /* intptr  amethod (intptr, intptr) */
6009         helper_sig_ptr_ptr_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
6010         helper_sig_ptr_ptr_ptr->params [0] = &mono_defaults.int_class->byval_arg;
6011         helper_sig_ptr_ptr_ptr->params [1] = &mono_defaults.int_class->byval_arg;
6012         helper_sig_ptr_ptr_ptr->ret = &mono_defaults.int_class->byval_arg;
6013         helper_sig_ptr_ptr_ptr->pinvoke = 1;
6014
6015         /* IntPtr  amethod (object) */
6016         helper_sig_ptr_obj = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6017         helper_sig_ptr_obj->params [0] = &mono_defaults.object_class->byval_arg;
6018         helper_sig_ptr_obj->ret = &mono_defaults.int_class->byval_arg;
6019         helper_sig_ptr_obj->pinvoke = 1;
6020
6021         /* IntPtr  amethod (int) */
6022         helper_sig_ptr_int = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6023         helper_sig_ptr_int->params [0] = &mono_defaults.int32_class->byval_arg;
6024         helper_sig_ptr_int->ret = &mono_defaults.int_class->byval_arg;
6025         helper_sig_ptr_int->pinvoke = 1;
6026
6027         /* long amethod (long, guint32) */
6028         helper_sig_long_long_int = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
6029         helper_sig_long_long_int->params [0] = &mono_defaults.int64_class->byval_arg;
6030         helper_sig_long_long_int->params [1] = &mono_defaults.int32_class->byval_arg;
6031         helper_sig_long_long_int->ret = &mono_defaults.int64_class->byval_arg;
6032         helper_sig_long_long_int->pinvoke = 1;
6033
6034         /* ulong amethod (double) */
6035         helper_sig_ulong_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6036         helper_sig_ulong_double->params [0] = &mono_defaults.double_class->byval_arg;
6037         helper_sig_ulong_double->ret = &mono_defaults.uint64_class->byval_arg;
6038         helper_sig_ulong_double->pinvoke = 1;
6039
6040         /* long amethod (double) */
6041         helper_sig_long_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6042         helper_sig_long_double->params [0] = &mono_defaults.double_class->byval_arg;
6043         helper_sig_long_double->ret = &mono_defaults.int64_class->byval_arg;
6044         helper_sig_long_double->pinvoke = 1;
6045
6046         /* double amethod (long) */
6047         helper_sig_double_long = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6048         helper_sig_double_long->params [0] = &mono_defaults.int64_class->byval_arg;
6049         helper_sig_double_long->ret = &mono_defaults.double_class->byval_arg;
6050         helper_sig_double_long->pinvoke = 1;
6051
6052         /* double amethod (int) */
6053         helper_sig_double_int = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6054         helper_sig_double_int->params [0] = &mono_defaults.int32_class->byval_arg;
6055         helper_sig_double_int->ret = &mono_defaults.double_class->byval_arg;
6056         helper_sig_double_int->pinvoke = 1;
6057
6058         /* float amethod (long) */
6059         helper_sig_float_long = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6060         helper_sig_float_long->params [0] = &mono_defaults.int64_class->byval_arg;
6061         helper_sig_float_long->ret = &mono_defaults.single_class->byval_arg;
6062         helper_sig_float_long->pinvoke = 1;
6063
6064         /* double amethod (double, double) */
6065         helper_sig_double_double_double = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
6066         helper_sig_double_double_double->params [0] = &mono_defaults.double_class->byval_arg;
6067         helper_sig_double_double_double->params [1] = &mono_defaults.double_class->byval_arg;
6068         helper_sig_double_double_double->ret = &mono_defaults.double_class->byval_arg;
6069         helper_sig_double_double_double->pinvoke = 1;
6070
6071         /* uint amethod (double) */
6072         helper_sig_uint_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6073         helper_sig_uint_double->params [0] = &mono_defaults.double_class->byval_arg;
6074         helper_sig_uint_double->ret = &mono_defaults.uint32_class->byval_arg;
6075         helper_sig_uint_double->pinvoke = 1;
6076
6077         /* int amethod (double) */
6078         helper_sig_int_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6079         helper_sig_int_double->params [0] = &mono_defaults.double_class->byval_arg;
6080         helper_sig_int_double->ret = &mono_defaults.int32_class->byval_arg;
6081         helper_sig_int_double->pinvoke = 1;
6082
6083         /* void  initobj (intptr, int size) */
6084         helper_sig_initobj = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
6085         helper_sig_initobj->params [0] = &mono_defaults.int_class->byval_arg;
6086         helper_sig_initobj->params [1] = &mono_defaults.int32_class->byval_arg;
6087         helper_sig_initobj->ret = &mono_defaults.void_class->byval_arg;
6088         helper_sig_initobj->pinvoke = 1;
6089
6090         /* void  memcpy (intptr, intptr, int size) */
6091         helper_sig_memcpy = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
6092         helper_sig_memcpy->params [0] = &mono_defaults.int_class->byval_arg;
6093         helper_sig_memcpy->params [1] = &mono_defaults.int_class->byval_arg;
6094         helper_sig_memcpy->params [2] = &mono_defaults.int32_class->byval_arg;
6095         helper_sig_memcpy->ret = &mono_defaults.void_class->byval_arg;
6096         helper_sig_memcpy->pinvoke = 1;
6097
6098         /* void  memset (intptr, int val, int size) */
6099         helper_sig_memset = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
6100         helper_sig_memset->params [0] = &mono_defaults.int_class->byval_arg;
6101         helper_sig_memset->params [1] = &mono_defaults.int32_class->byval_arg;
6102         helper_sig_memset->params [2] = &mono_defaults.int32_class->byval_arg;
6103         helper_sig_memset->ret = &mono_defaults.void_class->byval_arg;
6104         helper_sig_memset->pinvoke = 1;
6105
6106         helper_sig_class_init_trampoline = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
6107         helper_sig_class_init_trampoline->ret = &mono_defaults.void_class->byval_arg;
6108         helper_sig_class_init_trampoline->pinvoke = 1;  
6109 }
6110
6111 static GHashTable *jit_icall_hash_name = NULL;
6112 static GHashTable *jit_icall_hash_addr = NULL;
6113
6114 MonoJitICallInfo *
6115 mono_find_jit_icall_by_name (const char *name)
6116 {
6117         MonoJitICallInfo *info;
6118         g_assert (jit_icall_hash_name);
6119
6120         //printf ("lookup addr %s %p\n", name, g_hash_table_lookup (jit_icall_hash_name, name));
6121         EnterCriticalSection (&trampoline_hash_mutex);
6122         info = g_hash_table_lookup (jit_icall_hash_name, name);
6123         LeaveCriticalSection (&trampoline_hash_mutex);
6124         return info;
6125 }
6126
6127 MonoJitICallInfo *
6128 mono_find_jit_icall_by_addr (gconstpointer addr)
6129 {
6130         MonoJitICallInfo *info;
6131         g_assert (jit_icall_hash_addr);
6132
6133         EnterCriticalSection (&trampoline_hash_mutex);
6134         info = g_hash_table_lookup (jit_icall_hash_addr, (gpointer)addr);
6135         LeaveCriticalSection (&trampoline_hash_mutex);
6136
6137         return info;
6138 }
6139
6140 gconstpointer
6141 mono_icall_get_wrapper (MonoJitICallInfo* callinfo)
6142 {
6143         char *name;
6144         MonoMethod *wrapper;
6145         gconstpointer code;
6146         
6147         if (callinfo->wrapper)
6148                 return callinfo->wrapper;
6149         
6150         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
6151         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func);
6152         /* Must be domain neutral since there is only one copy */
6153         code = mono_jit_compile_method_with_opt (wrapper, default_opt | MONO_OPT_SHARED);
6154
6155         EnterCriticalSection (&trampoline_hash_mutex);
6156         if (!callinfo->wrapper) {
6157                 callinfo->wrapper = code;
6158                 g_hash_table_insert (jit_icall_hash_addr, (gpointer)callinfo->wrapper, callinfo);
6159         }
6160         LeaveCriticalSection (&trampoline_hash_mutex);
6161
6162         g_free (name);
6163         return callinfo->wrapper;
6164 }
6165
6166 MonoJitICallInfo *
6167 mono_register_jit_icall (gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean is_save)
6168 {
6169         MonoJitICallInfo *info;
6170         
6171         g_assert (func);
6172         g_assert (name);
6173
6174         EnterCriticalSection (&trampoline_hash_mutex);
6175
6176         if (!jit_icall_hash_name) {
6177                 jit_icall_hash_name = g_hash_table_new (g_str_hash, g_str_equal);
6178                 jit_icall_hash_addr = g_hash_table_new (NULL, NULL);
6179         }
6180
6181         if (g_hash_table_lookup (jit_icall_hash_name, name)) {
6182                 g_warning ("jit icall already defined \"%s\"\n", name);
6183                 g_assert_not_reached ();
6184         }
6185
6186         info = g_new (MonoJitICallInfo, 1);
6187         
6188         info->name = name;
6189         info->func = func;
6190         info->sig = sig;
6191
6192         if (is_save
6193 #ifdef MONO_USE_EXC_TABLES
6194             || mono_arch_has_unwind_info (func)
6195 #endif
6196             ) {
6197                 info->wrapper = func;
6198         } else {
6199                 info->wrapper = NULL;
6200         }
6201
6202         g_hash_table_insert (jit_icall_hash_name, (gpointer)info->name, info);
6203         g_hash_table_insert (jit_icall_hash_addr, (gpointer)func, info);
6204
6205         LeaveCriticalSection (&trampoline_hash_mutex);
6206         return info;
6207 }
6208
6209 gpointer
6210 mono_create_class_init_trampoline (MonoVTable *vtable)
6211 {
6212         gpointer code;
6213
6214         /* previously created trampoline code */
6215         mono_domain_lock (vtable->domain);
6216         code = 
6217                 mono_g_hash_table_lookup (vtable->domain->class_init_trampoline_hash,
6218                                                                   vtable);
6219         mono_domain_unlock (vtable->domain);
6220         if (code)
6221                 return code;
6222
6223         code = mono_arch_create_class_init_trampoline (vtable);
6224
6225         /* store trampoline address */
6226         mono_domain_lock (vtable->domain);
6227         mono_g_hash_table_insert (vtable->domain->class_init_trampoline_hash,
6228                                                           vtable, code);
6229         mono_domain_unlock (vtable->domain);
6230
6231         EnterCriticalSection (&trampoline_hash_mutex);
6232         if (!class_init_hash_addr)
6233                 class_init_hash_addr = g_hash_table_new (NULL, NULL);
6234         g_hash_table_insert (class_init_hash_addr, code, vtable);
6235         LeaveCriticalSection (&trampoline_hash_mutex);
6236
6237         return code;
6238 }
6239
6240 gpointer
6241 mono_create_jump_trampoline (MonoDomain *domain, MonoMethod *method, 
6242                                                          gboolean add_sync_wrapper)
6243 {
6244         MonoJitInfo *ji;
6245         gpointer code;
6246
6247         if (add_sync_wrapper && method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
6248                 return mono_create_jump_trampoline (domain, mono_marshal_get_synchronized_wrapper (method), FALSE);
6249
6250         code = mono_jit_find_compiled_method (domain, method);
6251         if (code)
6252                 return code;
6253
6254         EnterCriticalSection (&trampoline_hash_mutex);
6255
6256         if (jump_trampoline_hash) {
6257                 code = g_hash_table_lookup (jump_trampoline_hash, method);
6258                 if (code) {
6259                         LeaveCriticalSection (&trampoline_hash_mutex);
6260                         return code;
6261                 }
6262         }
6263
6264         ji = mono_arch_create_jump_trampoline (method);
6265
6266         /*
6267          * mono_delegate_ctor needs to find the method metadata from the 
6268          * trampoline address, so we save it here.
6269          */
6270
6271         mono_jit_info_table_add (mono_root_domain, ji);
6272
6273         if (!jump_trampoline_hash)
6274                 jump_trampoline_hash = g_hash_table_new (NULL, NULL);
6275         g_hash_table_insert (jump_trampoline_hash, method, ji->code_start);
6276
6277         LeaveCriticalSection (&trampoline_hash_mutex);
6278
6279         return ji->code_start;
6280 }
6281
6282 MonoVTable*
6283 mono_find_class_init_trampoline_by_addr (gconstpointer addr)
6284 {
6285         MonoVTable *res;
6286
6287         EnterCriticalSection (&trampoline_hash_mutex);
6288         if (class_init_hash_addr)
6289                 res = g_hash_table_lookup (class_init_hash_addr, addr);
6290         else
6291                 res = NULL;
6292         LeaveCriticalSection (&trampoline_hash_mutex);
6293         return res;
6294 }
6295
6296 void
6297 mono_register_opcode_emulation (int opcode, const char *name, MonoMethodSignature *sig, gpointer func, gboolean no_throw)
6298 {
6299         MonoJitICallInfo *info;
6300
6301         if (!emul_opcode_map)
6302                 emul_opcode_map = g_new0 (MonoJitICallInfo*, OP_LAST + 1);
6303
6304         g_assert (!sig->hasthis);
6305         g_assert (sig->param_count < 3);
6306
6307         info = mono_register_jit_icall (func, name, sig, no_throw);
6308
6309         emul_opcode_map [opcode] = info;
6310 }
6311
6312 static void
6313 decompose_foreach (MonoInst *tree, gpointer data) 
6314 {
6315         static MonoJitICallInfo *newarr_info = NULL;
6316         static MonoJitICallInfo *newarr_specific_info = NULL;
6317         MonoJitICallInfo *info;
6318         int i;
6319
6320         switch (tree->opcode) {
6321         case CEE_NEWARR: {
6322                 MonoCompile *cfg = data;
6323                 MonoInst *iargs [3];
6324
6325                 if (!newarr_info) {
6326                         newarr_info = mono_find_jit_icall_by_addr (mono_array_new);
6327                         g_assert (newarr_info);
6328                         newarr_specific_info = mono_find_jit_icall_by_addr (mono_array_new_specific);
6329                         g_assert (newarr_specific_info);
6330                 }
6331
6332                 if (cfg->opt & MONO_OPT_SHARED) {
6333                         NEW_DOMAINCONST (cfg, iargs [0]);
6334                         NEW_CLASSCONST (cfg, iargs [1], tree->inst_newa_class);
6335                         iargs [2] = tree->inst_newa_len;
6336
6337                         info = newarr_info;
6338                 }
6339                 else {
6340                         MonoVTable *vtable = mono_class_vtable (cfg->domain, mono_array_class_get (tree->inst_newa_class, 1));
6341
6342                         NEW_VTABLECONST (cfg, iargs [0], vtable);
6343                         iargs [1] = tree->inst_newa_len;
6344
6345                         info = newarr_specific_info;
6346                 }
6347
6348                 mono_emulate_opcode (cfg, tree, iargs, info);
6349
6350                 /* Need to decompose arguments after the the opcode is decomposed */
6351                 for (i = 0; i < info->sig->param_count; ++i)
6352                         dec_foreach (iargs [i], cfg);
6353                 break;
6354         }
6355
6356         default:
6357                 break;
6358         }
6359 }
6360
6361 void
6362 mono_inst_foreach (MonoInst *tree, MonoInstFunc func, gpointer data) {
6363
6364         switch (mono_burg_arity [tree->opcode]) {
6365         case 0: break;
6366         case 1: 
6367                 mono_inst_foreach (tree->inst_left, func, data);
6368                 break;
6369         case 2: 
6370                 mono_inst_foreach (tree->inst_left, func, data);
6371                 mono_inst_foreach (tree->inst_right, func, data);
6372                 break;
6373         default:
6374                 g_assert_not_reached ();
6375         }
6376         func (tree, data);
6377 }
6378
6379 G_GNUC_UNUSED
6380 static void
6381 mono_print_bb_code (MonoBasicBlock *bb) {
6382         if (bb->code) {
6383                 MonoInst *c = bb->code;
6384                 while (c) {
6385                         mono_print_tree (c);
6386                         g_print ("\n");
6387                         c = c->next;
6388                 }
6389         }
6390 }
6391
6392 static void
6393 print_dfn (MonoCompile *cfg) {
6394         int i, j;
6395         char *code;
6396         MonoBasicBlock *bb;
6397
6398         g_print ("IR code for method %s\n", mono_method_full_name (cfg->method, TRUE));
6399
6400         for (i = 0; i < cfg->num_bblocks; ++i) {
6401                 bb = cfg->bblocks [i];
6402                 if (bb->cil_code) {
6403                         char* code1, *code2;
6404                         code1 = mono_disasm_code_one (NULL, cfg->method, bb->cil_code, NULL);
6405                         if (bb->last_ins->cil_code)
6406                                 code2 = mono_disasm_code_one (NULL, cfg->method, bb->last_ins->cil_code, NULL);
6407                         else
6408                                 code2 = g_strdup ("");
6409
6410                         code1 [strlen (code1) - 1] = 0;
6411                         code = g_strdup_printf ("%s -> %s", code1, code2);
6412                         g_free (code1);
6413                         g_free (code2);
6414                 } else
6415                         code = g_strdup ("\n");
6416                 g_print ("\nBB%d DFN%d (len: %d): %s", bb->block_num, i, bb->cil_length, code);
6417                 if (bb->code) {
6418                         MonoInst *c = bb->code;
6419                         while (c) {
6420                                 mono_print_tree (c);
6421                                 g_print ("\n");
6422                                 c = c->next;
6423                         }
6424                 } else {
6425
6426                 }
6427
6428                 g_print ("\tprev:");
6429                 for (j = 0; j < bb->in_count; ++j) {
6430                         g_print (" BB%d", bb->in_bb [j]->block_num);
6431                 }
6432                 g_print ("\t\tsucc:");
6433                 for (j = 0; j < bb->out_count; ++j) {
6434                         g_print (" BB%d", bb->out_bb [j]->block_num);
6435                 }
6436                 g_print ("\n\tidom: BB%d\n", bb->idom? bb->idom->block_num: -1);
6437
6438                 if (bb->idom)
6439                         g_assert (mono_bitset_test_fast (bb->dominators, bb->idom->dfn));
6440
6441                 if (bb->dominators)
6442                         mono_blockset_print (cfg, bb->dominators, "\tdominators", bb->idom? bb->idom->dfn: -1);
6443                 if (bb->dfrontier)
6444                         mono_blockset_print (cfg, bb->dfrontier, "\tdfrontier", -1);
6445                 g_free (code);
6446         }
6447
6448         g_print ("\n");
6449 }
6450
6451 void
6452 mono_bblock_add_inst (MonoBasicBlock *bb, MonoInst *inst)
6453 {
6454         inst->next = NULL;
6455         if (bb->last_ins) {
6456                 g_assert (bb->code);
6457                 bb->last_ins->next = inst;
6458                 bb->last_ins = inst;
6459         } else {
6460                 bb->last_ins = bb->code = inst;
6461         }
6462 }
6463
6464 void
6465 mono_destroy_compile (MonoCompile *cfg)
6466 {
6467         //mono_mempool_stats (cfg->mempool);
6468         g_hash_table_destroy (cfg->bb_hash);
6469         if (cfg->rs)
6470                 mono_regstate_free (cfg->rs);
6471         if (cfg->spvars)
6472                 g_hash_table_destroy (cfg->spvars);
6473         mono_mempool_destroy (cfg->mempool);
6474         g_list_free (cfg->ldstr_list);
6475
6476         g_free (cfg->varinfo);
6477         g_free (cfg->vars);
6478         g_free (cfg);
6479 }
6480
6481 MonoLMF **
6482 mono_get_lmf_addr (void)
6483 {
6484         MonoJitTlsData *jit_tls;
6485
6486         if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
6487                 return &jit_tls->lmf;
6488
6489         g_assert_not_reached ();
6490         return NULL;
6491 }
6492
6493 /**
6494  * mono_thread_abort:
6495  * @obj: exception object
6496  *
6497  * abort the thread, print exception information and stack trace
6498  */
6499 static void
6500 mono_thread_abort (MonoObject *obj)
6501 {
6502         /* MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id); */
6503         
6504         /* handle_remove should be eventually called for this thread, too
6505         g_free (jit_tls);*/
6506
6507         ExitThread (-1);
6508 }
6509
6510 static void*
6511 setup_jit_tls_data (gpointer stack_start, gpointer abort_func)
6512 {
6513         MonoJitTlsData *jit_tls;
6514         MonoLMF *lmf;
6515
6516         jit_tls = TlsGetValue (mono_jit_tls_id);
6517         if (jit_tls)
6518                 return jit_tls;
6519
6520         jit_tls = g_new0 (MonoJitTlsData, 1);
6521
6522         TlsSetValue (mono_jit_tls_id, jit_tls);
6523
6524         jit_tls->abort_func = abort_func;
6525         jit_tls->end_of_stack = stack_start;
6526
6527         lmf = g_new0 (MonoLMF, 1);
6528         lmf->ebp = -1;
6529
6530         jit_tls->lmf = jit_tls->first_lmf = lmf;
6531
6532         mono_arch_setup_jit_tls_data (jit_tls);
6533
6534         return jit_tls;
6535 }
6536
6537 static void
6538 mono_thread_start_cb (guint32 tid, gpointer stack_start, gpointer func)
6539 {
6540         MonoThread *thread;
6541         void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort);
6542         thread = mono_thread_current ();
6543         if (thread)
6544                 thread->jit_data = jit_tls;
6545 }
6546
6547 void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
6548
6549 static void
6550 mono_thread_abort_dummy (MonoObject *obj)
6551 {
6552   if (mono_thread_attach_aborted_cb)
6553     mono_thread_attach_aborted_cb (obj);
6554   else
6555     mono_thread_abort (obj);
6556 }
6557
6558 static void
6559 mono_thread_attach_cb (guint32 tid, gpointer stack_start)
6560 {
6561         MonoThread *thread;
6562         void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort_dummy);
6563         thread = mono_thread_current ();
6564         if (thread)
6565                 thread->jit_data = jit_tls;
6566 }
6567
6568 static void
6569 mini_thread_cleanup (MonoThread *thread)
6570 {
6571         MonoJitTlsData *jit_tls = thread->jit_data;
6572
6573         if (jit_tls) {
6574                 mono_arch_free_jit_tls_data (jit_tls);
6575                 g_free (jit_tls->first_lmf);
6576                 g_free (jit_tls);
6577                 thread->jit_data = NULL;
6578         }
6579 }
6580
6581 void
6582 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
6583 {
6584         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
6585
6586         ji->ip.i = ip;
6587         ji->type = type;
6588         ji->data.target = target;
6589         ji->next = cfg->patch_info;
6590
6591         cfg->patch_info = ji;
6592 }
6593
6594 void
6595 mono_remove_patch_info (MonoCompile *cfg, int ip)
6596 {
6597         MonoJumpInfo **ji = &cfg->patch_info;
6598
6599         while (*ji) {
6600                 if ((*ji)->ip.i == ip)
6601                         *ji = (*ji)->next;
6602                 else
6603                         ji = &((*ji)->next);
6604         }
6605 }
6606
6607 gpointer
6608 mono_resolve_patch_target (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors)
6609 {
6610         unsigned char *ip = patch_info->ip.i + code;
6611         gconstpointer target = NULL;
6612
6613         switch (patch_info->type) {
6614         case MONO_PATCH_INFO_BB:
6615                 target = patch_info->data.bb->native_offset + code;
6616                 break;
6617         case MONO_PATCH_INFO_ABS:
6618                 target = patch_info->data.target;
6619                 break;
6620         case MONO_PATCH_INFO_LABEL:
6621                 target = patch_info->data.inst->inst_c0 + code;
6622                 break;
6623         case MONO_PATCH_INFO_IP:
6624                 target = ip;
6625                 break;
6626         case MONO_PATCH_INFO_METHOD_REL:
6627                 target = code + patch_info->data.offset;
6628                 break;
6629         case MONO_PATCH_INFO_INTERNAL_METHOD: {
6630                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
6631                 if (!mi) {
6632                         g_warning ("unknown MONO_PATCH_INFO_INTERNAL_METHOD %s", patch_info->data.name);
6633                         g_assert_not_reached ();
6634                 }
6635                 target = mono_icall_get_wrapper (mi);
6636                 break;
6637         }
6638         case MONO_PATCH_INFO_METHOD_JUMP: {
6639                 GSList *list;
6640
6641                 /* get the trampoline to the method from the domain */
6642                 target = mono_create_jump_trampoline (domain, patch_info->data.method, TRUE);
6643                 if (!domain->jump_target_hash)
6644                         domain->jump_target_hash = g_hash_table_new (NULL, NULL);
6645                 list = g_hash_table_lookup (domain->jump_target_hash, patch_info->data.method);
6646                 list = g_slist_prepend (list, ip);
6647                 g_hash_table_insert (domain->jump_target_hash, patch_info->data.method, list);
6648                 break;
6649         }
6650         case MONO_PATCH_INFO_METHOD:
6651                 if (patch_info->data.method == method) {
6652                         target = code;
6653                 } else
6654                         /* get the trampoline to the method from the domain */
6655                         target = mono_arch_create_jit_trampoline (patch_info->data.method);
6656                 break;
6657         case MONO_PATCH_INFO_SWITCH: {
6658                 gpointer *jump_table;
6659                 int i;
6660         
6661                 mono_domain_lock (domain);
6662                 jump_table = mono_code_manager_reserve (domain->code_mp, sizeof (gpointer) * patch_info->table_size);
6663                 mono_domain_unlock (domain);
6664
6665                 for (i = 0; i < patch_info->table_size; i++) {
6666                         jump_table [i] = code + (int)patch_info->data.table [i];
6667                 }
6668                 target = jump_table;
6669                 break;
6670         }
6671         case MONO_PATCH_INFO_METHODCONST:
6672         case MONO_PATCH_INFO_CLASS:
6673         case MONO_PATCH_INFO_IMAGE:
6674         case MONO_PATCH_INFO_FIELD:
6675                 target = patch_info->data.target;
6676                 break;
6677         case MONO_PATCH_INFO_IID:
6678                 mono_class_init (patch_info->data.klass);
6679                 target = (gpointer)patch_info->data.klass->interface_id;
6680                 break;
6681         case MONO_PATCH_INFO_VTABLE:
6682                 target = mono_class_vtable (domain, patch_info->data.klass);
6683                 break;
6684         case MONO_PATCH_INFO_CLASS_INIT:
6685                 target = mono_create_class_init_trampoline (mono_class_vtable (domain, patch_info->data.klass));
6686                 break;
6687         case MONO_PATCH_INFO_SFLDA: {
6688                 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.field->parent);
6689                 if (!vtable->initialized && !(vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) && mono_class_needs_cctor_run (vtable->klass, method))
6690                         /* Done by the generated code */
6691                         ;
6692                 else {
6693                         if (run_cctors)
6694                                 mono_runtime_class_init (vtable);
6695                 }
6696                 target = (char*)vtable->data + patch_info->data.field->offset;
6697                 break;
6698         }
6699         case MONO_PATCH_INFO_R4:
6700         case MONO_PATCH_INFO_R8:
6701                 target = patch_info->data.target;
6702                 break;
6703         case MONO_PATCH_INFO_EXC_NAME:
6704                 target = patch_info->data.name;
6705                 break;
6706         case MONO_PATCH_INFO_LDSTR:
6707                 target =
6708                         mono_ldstr (domain, patch_info->data.token->image, 
6709                                                 mono_metadata_token_index (patch_info->data.token->token));
6710                 break;
6711         case MONO_PATCH_INFO_TYPE_FROM_HANDLE: {
6712                 gpointer handle;
6713                 MonoClass *handle_class;
6714
6715                 handle = mono_ldtoken (patch_info->data.token->image, 
6716                                        patch_info->data.token->token, &handle_class, NULL);
6717                 mono_class_init (handle_class);
6718                 mono_class_init (mono_class_from_mono_type (handle));
6719
6720                 target =
6721                         mono_type_get_object (domain, handle);
6722                 break;
6723         }
6724         case MONO_PATCH_INFO_LDTOKEN: {
6725                 gpointer handle;
6726                 MonoClass *handle_class;
6727                 
6728                 handle = mono_ldtoken (patch_info->data.token->image,
6729                                        patch_info->data.token->token, &handle_class, NULL);
6730                 mono_class_init (handle_class);
6731                 
6732                 target = handle;
6733                 break;
6734         }
6735         default:
6736                 g_assert_not_reached ();
6737         }
6738
6739         return (gpointer)target;
6740 }
6741
6742 static void
6743 dec_foreach (MonoInst *tree, MonoCompile *cfg) {
6744         MonoJitICallInfo *info;
6745
6746         decompose_foreach (tree, cfg);
6747
6748         switch (mono_burg_arity [tree->opcode]) {
6749         case 0: break;
6750         case 1: 
6751                 dec_foreach (tree->inst_left, cfg);
6752
6753                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
6754                         MonoInst *iargs [2];
6755                 
6756                         iargs [0] = tree->inst_left;
6757
6758                         mono_emulate_opcode (cfg, tree, iargs, info);
6759                         return;
6760                 }
6761
6762                 break;
6763         case 2:
6764 #ifdef MONO_ARCH_BIGMUL_INTRINS
6765                 if (tree->opcode == OP_LMUL
6766                                 && (cfg->opt & MONO_OPT_INTRINS)
6767                                 && (tree->inst_left->opcode == CEE_CONV_I8 
6768                                         || tree->inst_left->opcode == CEE_CONV_U8)
6769                                 && tree->inst_left->inst_left->type == STACK_I4
6770                                 && (tree->inst_right->opcode == CEE_CONV_I8 
6771                                         || tree->inst_right->opcode == CEE_CONV_U8)
6772                                 && tree->inst_right->inst_left->type == STACK_I4) {
6773                         tree->opcode = (tree->inst_left->opcode == CEE_CONV_I8 ? OP_BIGMUL: OP_BIGMUL_UN);
6774                         tree->inst_left = tree->inst_left->inst_left;
6775                         tree->inst_right = tree->inst_right->inst_left;
6776                         dec_foreach (tree, cfg);
6777                 } else 
6778 #endif
6779                         if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
6780                         MonoInst *iargs [2];
6781                 
6782                         iargs [0] = tree->inst_i0;
6783                         iargs [1] = tree->inst_i1;
6784                 
6785                         mono_emulate_opcode (cfg, tree, iargs, info);
6786
6787                         dec_foreach (iargs [0], cfg);
6788                         dec_foreach (iargs [1], cfg);
6789                         return;
6790                 } else {
6791                         dec_foreach (tree->inst_left, cfg);
6792                         dec_foreach (tree->inst_right, cfg);
6793                 }
6794                 break;
6795         default:
6796                 g_assert_not_reached ();
6797         }
6798 }
6799
6800 static void
6801 decompose_pass (MonoCompile *cfg) {
6802         MonoBasicBlock *bb;
6803
6804         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
6805                 MonoInst *tree;
6806                 cfg->cbb = bb;
6807                 cfg->prev_ins = NULL;
6808                 for (tree = cfg->cbb->code; tree; tree = tree->next) {
6809                         dec_foreach (tree, cfg);
6810                         cfg->prev_ins = tree;
6811                 }
6812         }
6813 }
6814
6815 static void
6816 nullify_basic_block (MonoBasicBlock *bb) 
6817 {
6818         bb->in_count = 0;
6819         bb->out_count = 0;
6820         bb->in_bb = NULL;
6821         bb->out_bb = NULL;
6822         bb->next_bb = NULL;
6823         bb->code = bb->last_ins = NULL;
6824         bb->cil_code = NULL;
6825 }
6826
6827 static void 
6828 replace_out_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
6829 {
6830         int i;
6831
6832         for (i = 0; i < bb->out_count; i++) {
6833                 MonoBasicBlock *ob = bb->out_bb [i];
6834                 if (ob == orig) {
6835                         if (!repl) {
6836                                 if (bb->out_count > 1) {
6837                                         bb->out_bb [i] = bb->out_bb [bb->out_count - 1];
6838                                 }
6839                                 bb->out_count--;
6840                         } else {
6841                                 bb->out_bb [i] = repl;
6842                         }
6843                 }
6844         }
6845 }
6846
6847 static void 
6848 replace_in_block (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl)
6849 {
6850         int i;
6851
6852         for (i = 0; i < bb->in_count; i++) {
6853                 MonoBasicBlock *ib = bb->in_bb [i];
6854                 if (ib == orig) {
6855                         if (!repl) {
6856                                 if (bb->in_count > 1) {
6857                                         bb->in_bb [i] = bb->in_bb [bb->in_count - 1];
6858                                 }
6859                                 bb->in_count--;
6860                         } else {
6861                                 bb->in_bb [i] = repl;
6862                         }
6863                 }
6864         }
6865 }
6866
6867 static void 
6868 replace_basic_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
6869 {
6870         int i, j;
6871
6872         for (i = 0; i < bb->out_count; i++) {
6873                 MonoBasicBlock *ob = bb->out_bb [i];
6874                 for (j = 0; j < ob->in_count; j++) {
6875                         if (ob->in_bb [j] == orig) {
6876                                 ob->in_bb [j] = repl;
6877                         }
6878                 }
6879         }
6880
6881 }
6882
6883
6884 static void
6885 merge_basic_blocks (MonoBasicBlock *bb, MonoBasicBlock *bbn) 
6886 {
6887         bb->out_count = bbn->out_count;
6888         bb->out_bb = bbn->out_bb;
6889
6890         replace_basic_block (bb, bbn, bb);
6891
6892         if (bb->last_ins) {
6893                 if (bbn->code) {
6894                         bb->last_ins->next = bbn->code;
6895                         bb->last_ins = bbn->last_ins;
6896                 }
6897         } else {
6898                 bb->code = bbn->code;
6899                 bb->last_ins = bbn->last_ins;
6900         }
6901         bb->next_bb = bbn->next_bb;
6902         nullify_basic_block (bbn);
6903 }
6904
6905 /*
6906  * Optimizes the branches on the Control Flow Graph
6907  *
6908  */
6909 static void
6910 optimize_branches (MonoCompile *cfg)
6911 {
6912         int i, changed = FALSE;
6913         MonoBasicBlock *bb, *bbn;
6914         guint32 niterations;
6915
6916         /*
6917          * Some crazy loops could cause the code below to go into an infinite
6918          * loop, see bug #53003 for an example. To prevent this, we put an upper
6919          * bound on the number of iterations.
6920          */
6921         niterations = 1000;
6922         do {
6923                 changed = FALSE;
6924                 niterations --;
6925
6926                 /* we skip the entry block (exit is handled specially instead ) */
6927                 for (bb = cfg->bb_entry->next_bb; bb; bb = bb->next_bb) {
6928
6929                         /* dont touch code inside exception clauses */
6930                         if (bb->region != -1)
6931                                 continue;
6932
6933                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
6934                                 if (cfg->verbose_level > 2)
6935                                         g_print ("nullify block triggered %d\n", bbn->block_num);
6936
6937                                 bb->next_bb = bbn->next_bb;
6938
6939                                 for (i = 0; i < bbn->out_count; i++)
6940                                         replace_in_block (bbn->out_bb [i], bbn, NULL);
6941
6942                                 nullify_basic_block (bbn);                      
6943                                 changed = TRUE;
6944                         }
6945
6946                         if (bb->out_count == 1) {
6947                                 bbn = bb->out_bb [0];
6948
6949                                 /* conditional branches where true and false targets are the same can be also replaced with CEE_BR */
6950                                 if (bb->last_ins && MONO_IS_COND_BRANCH (bb->last_ins->opcode)) {
6951                                         bb->last_ins->opcode = CEE_BR;
6952                                         bb->last_ins->inst_target_bb = bb->last_ins->inst_true_bb;
6953                                         changed = TRUE;
6954                                         if (cfg->verbose_level > 2)
6955                                                 g_print ("cond branch removal triggered in %d %d\n", bb->block_num, bb->out_count);
6956                                 }
6957
6958                                 if (bb->region == bbn->region && bb->next_bb == bbn) {
6959                                         /* the block are in sequence anyway ... */
6960
6961                                         /* branches to the following block can be removed */
6962                                         if (bb->last_ins && bb->last_ins->opcode == CEE_BR) {
6963                                                 bb->last_ins->opcode = CEE_NOP;
6964                                                 changed = TRUE;
6965                                                 if (cfg->verbose_level > 2)
6966                                                         g_print ("br removal triggered %d -> %d\n", bb->block_num, bbn->block_num);
6967                                         }
6968
6969                                         if (bbn->in_count == 1) {
6970
6971                                                 if (bbn != cfg->bb_exit) {
6972                                                         if (cfg->verbose_level > 2)
6973                                                                 g_print ("block merge triggered %d -> %d\n", bb->block_num, bbn->block_num);
6974                                                         merge_basic_blocks (bb, bbn);
6975                                                         changed = TRUE;
6976                                                 }
6977
6978                                                 //mono_print_bb_code (bb);
6979                                         }
6980                                 }                               
6981                         }
6982                 }
6983         } while (changed && (niterations > 0));
6984
6985         niterations = 1000;
6986         do {
6987                 changed = FALSE;
6988                 niterations --;
6989
6990                 /* we skip the entry block (exit is handled specially instead ) */
6991                 for (bb = cfg->bb_entry->next_bb; bb; bb = bb->next_bb) {
6992
6993                         /* dont touch code inside exception clauses */
6994                         if (bb->region != -1)
6995                                 continue;
6996
6997                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
6998                                 if (cfg->verbose_level > 2) {
6999                                         g_print ("nullify block triggered %d\n", bbn->block_num);
7000                                 }
7001                                 bb->next_bb = bbn->next_bb;
7002
7003                                 for (i = 0; i < bbn->out_count; i++)
7004                                         replace_in_block (bbn->out_bb [i], bbn, NULL);
7005
7006                                 nullify_basic_block (bbn);                      
7007                                 changed = TRUE;
7008                                 break;
7009                         }
7010
7011
7012                         if (bb->out_count == 1) {
7013                                 bbn = bb->out_bb [0];
7014
7015                                 if (bb->last_ins && bb->last_ins->opcode == CEE_BR) {
7016                                         bbn = bb->last_ins->inst_target_bb;
7017                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR &&
7018                                             bbn->code->inst_target_bb->region == bb->region) {
7019                                                 
7020                                                 if (cfg->verbose_level > 2)
7021                                                         g_print ("in %s branch to branch triggered %d -> %d\n", cfg->method->name, 
7022                                                                  bb->block_num, bbn->block_num);
7023                                                 
7024                                                 replace_basic_block (bb, bb->out_bb [0], bbn->code->inst_target_bb);
7025                                                 bb->last_ins->inst_target_bb = bbn->code->inst_target_bb;
7026                                                 changed = TRUE;
7027                                                 break;
7028                                         }
7029                                 }
7030                         } else if (bb->out_count == 2) {
7031                                 if (bb->last_ins && MONO_IS_COND_BRANCH (bb->last_ins->opcode)) {
7032                                         bbn = bb->last_ins->inst_true_bb;
7033                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR &&
7034                                             bbn->code->inst_target_bb->region == bb->region) {
7035                                                 if (cfg->verbose_level > 2)             
7036                                                         g_print ("cbranch1 to branch triggered %d -> (%d) %d (0x%02x)\n", 
7037                                                                  bb->block_num, bbn->block_num, bbn->code->inst_target_bb->block_num, 
7038                                                                  bbn->code->opcode);
7039
7040                                                 bb->last_ins->inst_true_bb = bbn->code->inst_target_bb;
7041
7042                                                 replace_in_block (bbn, bb, NULL);
7043                                                 if (!bbn->in_count)
7044                                                         replace_in_block (bbn->code->inst_target_bb, bbn, bb);
7045                                                 replace_out_block (bb, bbn, bbn->code->inst_target_bb);
7046
7047                                                 link_bblock (cfg, bb, bbn->code->inst_target_bb);
7048
7049                                                 changed = TRUE;
7050                                                 break;
7051                                         }
7052
7053                                         bbn = bb->last_ins->inst_false_bb;
7054                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR &&
7055                                             bbn->code->inst_target_bb->region == bb->region) {
7056                                                 if (cfg->verbose_level > 2)
7057                                                         g_print ("cbranch2 to branch triggered %d -> (%d) %d (0x%02x)\n", 
7058                                                                  bb->block_num, bbn->block_num, bbn->code->inst_target_bb->block_num, 
7059                                                                  bbn->code->opcode);
7060
7061                                                 bb->last_ins->inst_false_bb = bbn->code->inst_target_bb;
7062
7063                                                 replace_in_block (bbn, bb, NULL);
7064                                                 if (!bbn->in_count)
7065                                                         replace_in_block (bbn->code->inst_target_bb, bbn, bb);
7066                                                 replace_out_block (bb, bbn, bbn->code->inst_target_bb);
7067
7068                                                 link_bblock (cfg, bb, bbn->code->inst_target_bb);
7069
7070                                                 changed = TRUE;
7071                                                 break;
7072                                         }
7073                                 }
7074                         }
7075                 }
7076         } while (changed && (niterations > 0));
7077
7078 }
7079
7080 static void
7081 mono_compile_create_vars (MonoCompile *cfg)
7082 {
7083         MonoMethodSignature *sig;
7084         MonoMethodHeader *header;
7085         int i;
7086
7087         header = ((MonoMethodNormal *)cfg->method)->header;
7088
7089         sig = cfg->method->signature;
7090         
7091         if (!MONO_TYPE_IS_VOID (sig->ret)) {
7092                 cfg->ret = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
7093                 cfg->ret->opcode = OP_RETARG;
7094                 cfg->ret->inst_vtype = sig->ret;
7095                 cfg->ret->klass = mono_class_from_mono_type (sig->ret);
7096         }
7097         if (cfg->verbose_level > 2)
7098                 g_print ("creating vars\n");
7099
7100         if (sig->hasthis)
7101                 mono_compile_create_var (cfg, &cfg->method->klass->this_arg, OP_ARG);
7102
7103         for (i = 0; i < sig->param_count; ++i)
7104                 mono_compile_create_var (cfg, sig->params [i], OP_ARG);
7105
7106         cfg->locals_start = cfg->num_varinfo;
7107
7108         if (cfg->verbose_level > 2)
7109                 g_print ("creating locals\n");
7110         for (i = 0; i < header->num_locals; ++i)
7111                 mono_compile_create_var (cfg, header->locals [i], OP_LOCAL);
7112         if (cfg->verbose_level > 2)
7113                 g_print ("locals done\n");
7114 }
7115
7116 void
7117 mono_print_code (MonoCompile *cfg)
7118 {
7119         MonoBasicBlock *bb;
7120         
7121         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7122                 MonoInst *tree = bb->code;      
7123
7124                 if (!tree)
7125                         continue;
7126                 
7127                 g_print ("CODE BLOCK %d (nesting %d):\n", bb->block_num, bb->nesting);
7128
7129                 for (; tree; tree = tree->next) {
7130                         mono_print_tree (tree);
7131                         g_print ("\n");
7132                 }
7133
7134                 if (bb->last_ins)
7135                         bb->last_ins->next = NULL;
7136         }
7137 }
7138
7139 extern const char * const mono_burg_rule_string [];
7140
7141 static void
7142 emit_state (MonoCompile *cfg, MBState *state, int goal)
7143 {
7144         MBState *kids [10];
7145         int ern = mono_burg_rule (state, goal);
7146         const guint16 *nts = mono_burg_nts [ern];
7147         MBEmitFunc emit;
7148
7149         //g_print ("rule: %s\n", mono_burg_rule_string [ern]);
7150         switch (goal) {
7151         case MB_NTERM_reg:
7152                 //if (state->reg2)
7153                 //      state->reg1 = state->reg2; /* chain rule */
7154                 //else
7155                 state->reg1 = mono_regstate_next_int (cfg->rs);
7156                 //g_print ("alloc symbolic R%d (reg2: R%d) in block %d\n", state->reg1, state->reg2, cfg->cbb->block_num);
7157                 break;
7158         case MB_NTERM_lreg:
7159                 state->reg1 = mono_regstate_next_int (cfg->rs);
7160                 state->reg2 = mono_regstate_next_int (cfg->rs);
7161                 break;
7162         case MB_NTERM_freg:
7163                 state->reg1 = mono_regstate_next_float (cfg->rs);
7164                 break;
7165         default:
7166                 /* do nothing */
7167                 break;
7168         }
7169         if (nts [0]) {
7170                 mono_burg_kids (state, ern, kids);
7171
7172                 emit_state (cfg, kids [0], nts [0]);
7173                 if (nts [1]) {
7174                         emit_state (cfg, kids [1], nts [1]);
7175                         if (nts [2]) {
7176                                 g_assert (!nts [3]);
7177                                 emit_state (cfg, kids [2], nts [2]);
7178                         }
7179                 }
7180         }
7181
7182 //      g_print ("emit: %s (%p)\n", mono_burg_rule_string [ern], state);
7183         if ((emit = mono_burg_func [ern]))
7184                 emit (state, state->tree, cfg); 
7185 }
7186
7187 #define DEBUG_SELECTION
7188
7189 static void 
7190 mini_select_instructions (MonoCompile *cfg)
7191 {
7192         static int reverse_map [] = {
7193                 CEE_BNE_UN, CEE_BLT, CEE_BLE, CEE_BGT, CEE_BGE,
7194                 CEE_BEQ, CEE_BLT_UN, CEE_BLE_UN, CEE_BGT_UN, CEE_BGE_UN
7195         };
7196         static int reverse_fmap [] = {
7197                 OP_FBNE_UN, OP_FBLT, OP_FBLE, OP_FBGT, OP_FBGE,
7198                 OP_FBEQ, OP_FBLT_UN, OP_FBLE_UN, OP_FBGT_UN, OP_FBGE_UN
7199         };
7200         static int reverse_lmap [] = {
7201                 OP_LBNE_UN, OP_LBLT, OP_LBLE, OP_LBGT, OP_LBGE,
7202                 OP_LBEQ, OP_LBLT_UN, OP_LBLE_UN, OP_LBGT_UN, OP_LBGE_UN
7203         };
7204
7205         MonoBasicBlock *bb;
7206         
7207         cfg->state_pool = mono_mempool_new ();
7208         cfg->rs = mono_regstate_new ();
7209
7210         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7211                 if (bb->last_ins && MONO_IS_COND_BRANCH (bb->last_ins->opcode) &&
7212                     bb->next_bb != bb->last_ins->inst_false_bb) {
7213
7214                         if (bb->next_bb ==  bb->last_ins->inst_true_bb) {
7215                                 MonoBasicBlock *tmp =  bb->last_ins->inst_true_bb;
7216                                 bb->last_ins->inst_true_bb = bb->last_ins->inst_false_bb;
7217                                 bb->last_ins->inst_false_bb = tmp;
7218                                 
7219                                 if (bb->last_ins->opcode >= CEE_BEQ && bb->last_ins->opcode <= CEE_BLT_UN) {
7220                                         bb->last_ins->opcode = reverse_map [bb->last_ins->opcode - CEE_BEQ];
7221                                 } else if (bb->last_ins->opcode >= OP_FBEQ && bb->last_ins->opcode <= OP_FBLT_UN) {
7222                                         bb->last_ins->opcode = reverse_fmap [bb->last_ins->opcode - OP_FBEQ];
7223                                 } else if (bb->last_ins->opcode >= OP_LBEQ && bb->last_ins->opcode <= OP_LBLT_UN) {
7224                                         bb->last_ins->opcode = reverse_lmap [bb->last_ins->opcode - OP_LBEQ];
7225                                 }
7226                         } else {                        
7227                                 MonoInst *inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
7228                                 inst->opcode = CEE_BR;
7229                                 inst->inst_target_bb = bb->last_ins->inst_false_bb;
7230                                 mono_bblock_add_inst (bb, inst);
7231                         }
7232                 }
7233         }
7234
7235 #ifdef DEBUG_SELECTION
7236         if (cfg->verbose_level >= 4) {
7237         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7238                 MonoInst *tree = bb->code;      
7239                 g_print ("DUMP BLOCK %d:\n", bb->block_num);
7240                 if (!tree)
7241                         continue;
7242                 for (; tree; tree = tree->next) {
7243                         mono_print_tree (tree);
7244                         g_print ("\n");
7245                 }
7246         }
7247         }
7248 #endif
7249
7250         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7251                 MonoInst *tree = bb->code, *next;       
7252                 MBState *mbstate;
7253
7254                 if (!tree)
7255                         continue;
7256                 bb->code = NULL;
7257                 bb->last_ins = NULL;
7258                 
7259                 cfg->cbb = bb;
7260                 mono_regstate_reset (cfg->rs);
7261
7262 #ifdef DEBUG_SELECTION
7263                 if (cfg->verbose_level >= 3)
7264                         g_print ("LABEL BLOCK %d:\n", bb->block_num);
7265 #endif
7266                 for (; tree; tree = next) {
7267                         next = tree->next;
7268 #ifdef DEBUG_SELECTION
7269                         if (cfg->verbose_level >= 3) {
7270                                 mono_print_tree (tree);
7271                                 g_print ("\n");
7272                         }
7273 #endif
7274
7275                         if (!(mbstate = mono_burg_label (tree, cfg))) {
7276                                 g_warning ("unable to label tree %p", tree);
7277                                 mono_print_tree (tree);
7278                                 g_print ("\n");                         
7279                                 g_assert_not_reached ();
7280                         }
7281                         emit_state (cfg, mbstate, MB_NTERM_stmt);
7282                 }
7283                 bb->max_ireg = cfg->rs->next_vireg;
7284                 bb->max_freg = cfg->rs->next_vfreg;
7285
7286                 if (bb->last_ins)
7287                         bb->last_ins->next = NULL;
7288
7289                 mono_mempool_empty (cfg->state_pool); 
7290         }
7291         mono_mempool_destroy (cfg->state_pool); 
7292 }
7293
7294 void
7295 mono_codegen (MonoCompile *cfg)
7296 {
7297         MonoJumpInfo *patch_info;
7298         MonoBasicBlock *bb;
7299         int i, max_epilog_size;
7300         guint8 *code;
7301
7302         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7303                 cfg->spill_count = 0;
7304                 /* we reuse dfn here */
7305                 /* bb->dfn = bb_count++; */
7306                 mono_arch_local_regalloc (cfg, bb);
7307         }
7308
7309         if (cfg->prof_options & MONO_PROFILE_COVERAGE)
7310                 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, cfg->num_bblocks);
7311
7312         code = mono_arch_emit_prolog (cfg);
7313
7314         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
7315                 code = mono_arch_instrument_prolog (cfg, mono_profiler_method_enter, code, FALSE);
7316
7317         cfg->code_len = code - cfg->native_code;
7318         cfg->prolog_end = cfg->code_len;
7319
7320         mono_debug_open_method (cfg);
7321
7322         /* emit code all basic blocks */
7323         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7324                 bb->native_offset = cfg->code_len;
7325                 mono_arch_output_basic_block (cfg, bb);
7326         }
7327         cfg->bb_exit->native_offset = cfg->code_len;
7328
7329         code = cfg->native_code + cfg->code_len;
7330
7331         max_epilog_size = mono_arch_max_epilog_size (cfg);
7332
7333         /* we always allocate code in cfg->domain->code_mp to increase locality */
7334         cfg->code_size = cfg->code_len + max_epilog_size;
7335         /* fixme: align to MONO_ARCH_CODE_ALIGNMENT */
7336
7337         mono_domain_lock (cfg->domain);
7338         code = mono_code_manager_reserve (cfg->domain->code_mp, cfg->code_size);
7339         mono_domain_unlock (cfg->domain);
7340
7341         memcpy (code, cfg->native_code, cfg->code_len);
7342         g_free (cfg->native_code);
7343         cfg->native_code = code;
7344         code = cfg->native_code + cfg->code_len;
7345   
7346         /* g_assert (((int)cfg->native_code & (MONO_ARCH_CODE_ALIGNMENT - 1)) == 0); */
7347
7348         cfg->epilog_begin = cfg->code_len;
7349
7350         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
7351                 code = mono_arch_instrument_epilog (cfg, mono_profiler_method_leave, code, FALSE);
7352
7353         cfg->code_len = code - cfg->native_code;
7354
7355         mono_arch_emit_epilog (cfg);
7356
7357         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7358                 switch (patch_info->type) {
7359                 case MONO_PATCH_INFO_ABS: {
7360                         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (patch_info->data.target);
7361                         if (info) {
7362                                 //printf ("TEST %s %p\n", info->name, patch_info->data.target);
7363                                 if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && 
7364                                         strstr (cfg->method->name, info->name))
7365                                         /*
7366                                          * This is an icall wrapper, and this is a call to the
7367                                          * wrapped function.
7368                                          */
7369                                         ;
7370                                 else {
7371                                         patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
7372                                         patch_info->data.name = info->name;
7373                                 }
7374                         }
7375                         else {
7376                                 MonoVTable *vtable = mono_find_class_init_trampoline_by_addr (patch_info->data.target);
7377                                 if (vtable) {
7378                                         patch_info->type = MONO_PATCH_INFO_CLASS_INIT;
7379                                         patch_info->data.klass = vtable->klass;
7380                                 }
7381                         }
7382                         break;
7383                 }
7384                 case MONO_PATCH_INFO_SWITCH: {
7385                         gpointer *table;
7386                         mono_domain_lock (cfg->domain);
7387                         table = mono_code_manager_reserve (cfg->domain->code_mp, sizeof (gpointer) * patch_info->table_size);
7388                         mono_domain_unlock (cfg->domain);
7389                 
7390                         patch_info->ip.i = patch_info->ip.label->inst_c0;
7391                         for (i = 0; i < patch_info->table_size; i++) {
7392                                 table [i] = (gpointer)patch_info->data.table [i]->native_offset;
7393                         }
7394                         patch_info->data.target = table;
7395                         break;
7396                 }
7397                 default:
7398                         /* do nothing */
7399                         break;
7400                 }
7401         }
7402        
7403         if (cfg->verbose_level > 0)
7404                 g_print ("Method %s emitted at %p to %p [%s]\n", 
7405                                  mono_method_full_name (cfg->method, TRUE), 
7406                                  cfg->native_code, cfg->native_code + cfg->code_len, cfg->domain->friendly_name);
7407
7408         mono_arch_patch_code (cfg->method, cfg->domain, cfg->native_code, cfg->patch_info, cfg->run_cctors);
7409
7410         mono_domain_lock (cfg->domain);
7411         mono_code_manager_commit (cfg->domain->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
7412         mono_domain_unlock (cfg->domain);
7413         
7414         mono_arch_flush_icache (cfg->native_code, cfg->code_len);
7415
7416         mono_debug_close_method (cfg);
7417 }
7418
7419 static void
7420 mono_cprop_copy_values (MonoCompile *cfg, MonoInst *tree, MonoInst **acp)
7421 {
7422         MonoInst *cp;
7423         int arity;
7424
7425         if (tree->ssa_op == MONO_SSA_LOAD && (tree->inst_i0->opcode == OP_LOCAL || tree->inst_i0->opcode == OP_ARG) && 
7426             (cp = acp [tree->inst_i0->inst_c0]) && !tree->inst_i0->flags) {
7427
7428                 if (cp->opcode == OP_ICONST) {
7429                         if (cfg->opt & MONO_OPT_CONSPROP) {
7430                                 //{ static int c = 0; printf ("CCOPY %d %d %s\n", c++, cp->inst_c0, mono_method_full_name (cfg->method, TRUE)); }
7431                                 *tree = *cp;
7432                         }
7433                 } else {
7434                         if (tree->inst_i0->inst_vtype->type == cp->inst_vtype->type) {
7435                                 if (cfg->opt & MONO_OPT_COPYPROP) {
7436                                         //{ static int c = 0; printf ("VCOPY %d\n", ++c); }
7437                                         tree->inst_i0 = cp;
7438                                 } 
7439                         }
7440                 } 
7441         } else {
7442                 arity = mono_burg_arity [tree->opcode];
7443
7444                 if (arity) {
7445                         mono_cprop_copy_values (cfg, tree->inst_i0, acp);
7446                         if (cfg->opt & MONO_OPT_CFOLD)
7447                                 mono_constant_fold_inst (tree, NULL); 
7448                         /* The opcode may have changed */
7449                         if (mono_burg_arity [tree->opcode] > 1) {
7450                                 mono_cprop_copy_values (cfg, tree->inst_i1, acp);
7451                                 if (cfg->opt & MONO_OPT_CFOLD)
7452                                         mono_constant_fold_inst (tree, NULL); 
7453                         }
7454                         mono_constant_fold_inst (tree, NULL); 
7455                 }
7456         }
7457 }
7458
7459 static void
7460 mono_cprop_invalidate_values (MonoInst *tree, MonoInst **acp, int acp_size)
7461 {
7462         int arity;
7463
7464         switch (tree->opcode) {
7465         case CEE_STIND_I:
7466         case CEE_STIND_I1:
7467         case CEE_STIND_I2:
7468         case CEE_STIND_I4:
7469         case CEE_STIND_REF:
7470         case CEE_STIND_I8:
7471         case CEE_STIND_R4:
7472         case CEE_STIND_R8:
7473         case CEE_STOBJ:
7474                 if (tree->ssa_op == MONO_SSA_NOP) {
7475                         memset (acp, 0, sizeof (MonoInst *) * acp_size);
7476                         return;
7477                 }
7478
7479                 break;
7480         case CEE_CALL:
7481         case OP_CALL_REG:
7482         case CEE_CALLVIRT:
7483         case OP_LCALL_REG:
7484         case OP_LCALLVIRT:
7485         case OP_LCALL:
7486         case OP_FCALL_REG:
7487         case OP_FCALLVIRT:
7488         case OP_FCALL:
7489         case OP_VCALL_REG:
7490         case OP_VCALLVIRT:
7491         case OP_VCALL:
7492         case OP_VOIDCALL_REG:
7493         case OP_VOIDCALLVIRT:
7494         case OP_VOIDCALL: {
7495                 MonoCallInst *call = (MonoCallInst *)tree;
7496                 MonoMethodSignature *sig = call->signature;
7497                 int i, byref = FALSE;
7498
7499                 for (i = 0; i < sig->param_count; i++) {
7500                         if (sig->params [i]->byref) {
7501                                 byref = TRUE;
7502                                 break;
7503                         }
7504                 }
7505
7506                 if (byref)
7507                         memset (acp, 0, sizeof (MonoInst *) * acp_size);
7508
7509                 return;
7510         }
7511         default:
7512                 break;
7513         }
7514
7515         arity = mono_burg_arity [tree->opcode];
7516
7517         switch (arity) {
7518         case 0:
7519                 break;
7520         case 1:
7521                 mono_cprop_invalidate_values (tree->inst_i0, acp, acp_size);
7522                 break;
7523         case 2:
7524                 mono_cprop_invalidate_values (tree->inst_i0, acp, acp_size);
7525                 mono_cprop_invalidate_values (tree->inst_i1, acp, acp_size);
7526                 break;
7527         default:
7528                 g_assert_not_reached ();
7529         }
7530 }
7531
7532 static void
7533 mono_local_cprop_bb (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst **acp, int acp_size)
7534 {
7535         MonoInst *tree = bb->code;      
7536         int i;
7537
7538         if (!tree)
7539                 return;
7540
7541         for (; tree; tree = tree->next) {
7542
7543                 mono_cprop_copy_values (cfg, tree, acp);
7544
7545                 mono_cprop_invalidate_values (tree, acp, acp_size);
7546
7547                 if (tree->ssa_op == MONO_SSA_STORE  && 
7548                     (tree->inst_i0->opcode == OP_LOCAL || tree->inst_i0->opcode == OP_ARG)) {
7549                         MonoInst *i1 = tree->inst_i1;
7550
7551                         acp [tree->inst_i0->inst_c0] = NULL;
7552
7553                         for (i = 0; i < acp_size; i++) {
7554                                 if (acp [i] && acp [i]->opcode != OP_ICONST && 
7555                                     acp [i]->inst_c0 == tree->inst_i0->inst_c0) {
7556                                         acp [i] = NULL;
7557                                 }
7558                         }
7559
7560                         if (i1->opcode == OP_ICONST) {
7561                                 acp [tree->inst_i0->inst_c0] = i1;
7562                                 //printf ("DEF1 BB%d %d\n", bb->block_num,tree->inst_i0->inst_c0);
7563                         }
7564                         if (i1->ssa_op == MONO_SSA_LOAD && 
7565                             (i1->inst_i0->opcode == OP_LOCAL || i1->inst_i0->opcode == OP_ARG) &&
7566                             (i1->inst_i0->inst_c0 != tree->inst_i0->inst_c0)) {
7567                                 acp [tree->inst_i0->inst_c0] = i1->inst_i0;
7568                                 //printf ("DEF2 BB%d %d %d\n", bb->block_num,tree->inst_i0->inst_c0,i1->inst_i0->inst_c0);
7569                         }
7570                 }
7571
7572                 /*
7573                   if (tree->opcode == CEE_BEQ) {
7574                   g_assert (tree->inst_i0->opcode == OP_COMPARE);
7575                   if (tree->inst_i0->inst_i0->opcode == OP_ICONST &&
7576                   tree->inst_i0->inst_i1->opcode == OP_ICONST) {
7577                   
7578                   tree->opcode = CEE_BR;
7579                   if (tree->inst_i0->inst_i0->opcode == tree->inst_i0->inst_i1->opcode) {
7580                   tree->inst_target_bb = tree->inst_true_bb;
7581                   } else {
7582                   tree->inst_target_bb = tree->inst_false_bb;
7583                   }
7584                   }
7585                   }
7586                 */
7587         }
7588 }
7589
7590 static void
7591 mono_local_cprop (MonoCompile *cfg)
7592 {
7593         MonoBasicBlock *bb;
7594         MonoInst **acp;
7595
7596         acp = alloca (sizeof (MonoInst *) * cfg->num_varinfo);
7597
7598         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7599                 memset (acp, 0, sizeof (MonoInst *) * cfg->num_varinfo);
7600                 mono_local_cprop_bb (cfg, bb, acp, cfg->num_varinfo);
7601         }
7602 }
7603
7604 MonoCompile*
7605 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gboolean run_cctors, int parts)
7606 {
7607         MonoMethodHeader *header = ((MonoMethodNormal *)method)->header;
7608         guint8 *ip = (guint8 *)header->code;
7609         MonoCompile *cfg;
7610         MonoJitInfo *jinfo;
7611         int dfn = 0, i, code_size_ratio;
7612
7613         mono_jit_stats.methods_compiled++;
7614         if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)
7615                 mono_profiler_method_jit (method);
7616
7617         cfg = g_new0 (MonoCompile, 1);
7618         cfg->method = method;
7619         cfg->mempool = mono_mempool_new ();
7620         cfg->opt = opts;
7621         cfg->prof_options = mono_profiler_get_events ();
7622         cfg->run_cctors = run_cctors;
7623         cfg->bb_hash = g_hash_table_new (NULL, NULL);
7624         cfg->domain = domain;
7625         cfg->verbose_level = mini_verbose;
7626         cfg->intvars = mono_mempool_alloc0 (cfg->mempool, sizeof (guint16) * STACK_MAX * 
7627                                             ((MonoMethodNormal *)method)->header->max_stack);
7628
7629         if (cfg->verbose_level > 2)
7630                 g_print ("converting method %s\n", mono_method_full_name (method, TRUE));
7631
7632         /*
7633          * create MonoInst* which represents arguments and local variables
7634          */
7635         mono_compile_create_vars (cfg);
7636
7637         if ((i = mono_method_to_ir (cfg, method, NULL, NULL, cfg->locals_start, NULL, NULL, NULL, 0, FALSE)) < 0) {
7638                 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
7639                         mono_profiler_method_end_jit (method, MONO_PROFILE_FAILED);
7640                 mono_destroy_compile (cfg);
7641                 return NULL;
7642         }
7643
7644         mono_jit_stats.basic_blocks += cfg->num_bblocks;
7645         mono_jit_stats.max_basic_blocks = MAX (cfg->num_bblocks, mono_jit_stats.max_basic_blocks);
7646
7647         if (cfg->num_varinfo > 2000) {
7648                 /* 
7649                  * we disable some optimizations if there are too many variables
7650                  * because JIT time may become too expensive. The actual number needs 
7651                  * to be tweaked and eventually the non-linear algorithms should be fixed.
7652                  */
7653                 cfg->opt &= ~ (MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP);
7654                 cfg->disable_ssa = TRUE;
7655         }
7656         /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/
7657
7658         /* Depth-first ordering on basic blocks */
7659         cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
7660
7661         if (cfg->opt & MONO_OPT_BRANCH)
7662                 optimize_branches (cfg);
7663
7664         df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
7665         if (cfg->num_bblocks != dfn + 1) {
7666                 MonoBasicBlock *bb;
7667
7668                 cfg->num_bblocks = dfn + 1;
7669
7670                 if (!header->clauses) {
7671                         /* remove unreachable code, because the code in them may be 
7672                          * inconsistent  (access to dead variables for example) */
7673                         for (bb = cfg->bb_entry; bb;) {
7674                                 MonoBasicBlock *bbn = bb->next_bb;
7675
7676                                 if (bbn && bbn->region == -1 && !bbn->dfn) {
7677                                         if (cfg->verbose_level > 1)
7678                                                 g_print ("found unreachabel code in BB%d\n", bbn->block_num);
7679                                         bb->next_bb = bbn->next_bb;
7680                                         nullify_basic_block (bbn);                      
7681                                 } else {
7682                                         bb = bb->next_bb;
7683                                 }
7684                         }
7685                 }
7686         }
7687
7688         if (cfg->opt & MONO_OPT_LOOP) {
7689                 mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM);
7690                 mono_compute_natural_loops (cfg);
7691         }
7692
7693         /* after method_to_ir */
7694         if (parts == 1)
7695                 return cfg;
7696
7697 //#define DEBUGSSA "logic_run"
7698 #define DEBUGSSA_CLASS "Tests"
7699 #ifdef DEBUGSSA
7700
7701         if (!header->num_clauses && !cfg->disable_ssa) {
7702                 mono_local_cprop (cfg);
7703                 mono_ssa_compute (cfg);
7704         }
7705 #else 
7706
7707         /* fixme: add all optimizations which requires SSA */
7708         if (cfg->opt & (MONO_OPT_DEADCE)) {
7709                 if (!(cfg->comp_done & MONO_COMP_SSA) && !header->num_clauses && !cfg->disable_ssa) {
7710                         mono_local_cprop (cfg);
7711                         mono_ssa_compute (cfg);
7712
7713                         if (cfg->verbose_level >= 2) {
7714                                 print_dfn (cfg);
7715                         }
7716                 }
7717         }
7718 #endif
7719
7720         /* after SSA translation */
7721         if (parts == 2)
7722                 return cfg;
7723
7724         if ((cfg->opt & MONO_OPT_CONSPROP) ||  (cfg->opt & MONO_OPT_COPYPROP)) {
7725                 if (cfg->comp_done & MONO_COMP_SSA) {
7726                         mono_ssa_cprop (cfg);
7727                 } else {
7728                         mono_local_cprop (cfg);
7729                 }
7730         }
7731
7732         if (cfg->comp_done & MONO_COMP_SSA) {                   
7733                 mono_ssa_deadce (cfg);
7734
7735                 //mono_ssa_strength_reduction (cfg);
7736
7737                 mono_ssa_remove (cfg);
7738
7739                 if (cfg->opt & MONO_OPT_BRANCH)
7740                         optimize_branches (cfg);
7741         }
7742
7743         /* after SSA removal */
7744         if (parts == 3)
7745                 return cfg;
7746
7747         decompose_pass (cfg);
7748
7749         if (cfg->opt & MONO_OPT_LINEARS) {
7750                 GList *vars, *regs;
7751
7752                 /* fixme: maybe we can avoid to compute livenesss here if already computed ? */
7753                 cfg->comp_done &= ~MONO_COMP_LIVENESS;
7754                 if (!(cfg->comp_done & MONO_COMP_LIVENESS))
7755                         mono_analyze_liveness (cfg);
7756
7757                 if ((vars = mono_arch_get_allocatable_int_vars (cfg))) {
7758                         regs = mono_arch_get_global_int_regs (cfg);
7759                         mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs);
7760                 }
7761         }
7762
7763         //mono_print_code (cfg);
7764
7765        //print_dfn (cfg);
7766         
7767         /* variables are allocated after decompose, since decompose could create temps */
7768         mono_arch_allocate_vars (cfg);
7769
7770         if (cfg->opt & MONO_OPT_CFOLD)
7771                 mono_constant_fold (cfg);
7772
7773         mini_select_instructions (cfg);
7774
7775         mono_codegen (cfg);
7776         if (cfg->verbose_level >= 2) {
7777                 char *id =  mono_method_full_name (cfg->method, FALSE);
7778                 mono_disassemble_code (cfg->native_code, cfg->code_len, id + 3);
7779                 g_free (id);
7780         }
7781         
7782         jinfo = mono_mempool_alloc0 (cfg->domain->mp, sizeof (MonoJitInfo));
7783
7784         jinfo = g_new0 (MonoJitInfo, 1);
7785         jinfo->method = method;
7786         jinfo->code_start = cfg->native_code;
7787         jinfo->code_size = cfg->code_len;
7788         jinfo->used_regs = cfg->used_int_regs;
7789         jinfo->domain_neutral = (cfg->opt & MONO_OPT_SHARED) != 0;
7790
7791         if (header->num_clauses) {
7792                 int i;
7793
7794                 jinfo->exvar_offset = cfg->exvar? cfg->exvar->inst_offset: 0;
7795                 jinfo->num_clauses = header->num_clauses;
7796                 jinfo->clauses = mono_mempool_alloc0 (cfg->domain->mp, 
7797                         sizeof (MonoJitExceptionInfo) * header->num_clauses);
7798
7799                 for (i = 0; i < header->num_clauses; i++) {
7800                         MonoExceptionClause *ec = &header->clauses [i];
7801                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
7802                         MonoBasicBlock *tblock;
7803
7804                         ei->flags = ec->flags;
7805
7806                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
7807                                 tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->token_or_filter);
7808                                 g_assert (tblock);
7809                                 ei->data.filter = cfg->native_code + tblock->native_offset;
7810                         } else {
7811                                 ei->data.token = ec->token_or_filter;
7812                         }
7813
7814                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->try_offset);
7815                         g_assert (tblock);
7816                         ei->try_start = cfg->native_code + tblock->native_offset;
7817                         g_assert (tblock->native_offset);
7818                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->try_offset + ec->try_len);
7819                         g_assert (tblock);
7820                         ei->try_end = cfg->native_code + tblock->native_offset;
7821                         g_assert (tblock->native_offset);
7822                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->handler_offset);
7823                         g_assert (tblock);
7824                         ei->handler_start = cfg->native_code + tblock->native_offset;
7825                 }
7826         }
7827
7828         cfg->jit_info = jinfo;
7829
7830         mono_jit_info_table_add (cfg->domain, jinfo);
7831
7832         /* collect statistics */
7833         mono_jit_stats.allocated_code_size += cfg->code_len;
7834         code_size_ratio = cfg->code_len;
7835         if (code_size_ratio > mono_jit_stats.biggest_method_size) {
7836                         mono_jit_stats.biggest_method_size = code_size_ratio;
7837                         mono_jit_stats.biggest_method = method;
7838         }
7839         code_size_ratio = (code_size_ratio * 100) / ((MonoMethodNormal *)method)->header->code_size;
7840         if (code_size_ratio > mono_jit_stats.max_code_size_ratio) {
7841                 mono_jit_stats.max_code_size_ratio = code_size_ratio;
7842                 mono_jit_stats.max_ratio_method = method;
7843         }
7844         mono_jit_stats.native_code_size += cfg->code_len;
7845
7846         if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
7847                 mono_profiler_method_end_jit (method, MONO_PROFILE_OK);
7848
7849         return cfg;
7850 }
7851
7852 static gpointer
7853 mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain)
7854 {
7855         MonoCompile *cfg;
7856         GHashTable *jit_code_hash;
7857         gpointer code = NULL;
7858         guint32 opt;
7859         MonoJitInfo *info;
7860
7861         opt = default_opt;
7862
7863         jit_code_hash = target_domain->jit_code_hash;
7864
7865 #ifdef MONO_USE_AOT_COMPILER
7866         if (!mono_compile_aot && (opt & MONO_OPT_AOT)) {
7867                 MonoJitInfo *info;
7868                 MonoDomain *domain = mono_domain_get ();
7869
7870                 mono_domain_lock (domain);
7871
7872                 mono_class_init (method->klass);
7873                 if ((info = mono_aot_get_method (domain, method))) {
7874                         g_hash_table_insert (domain->jit_code_hash, method, info);
7875                         mono_domain_unlock (domain);
7876                         mono_runtime_class_init (mono_class_vtable (domain, method->klass));
7877                         return info->code_start;
7878                 }
7879
7880                 mono_domain_unlock (domain);
7881         }
7882 #endif
7883
7884         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
7885             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
7886                 MonoMethod *nm;
7887
7888                 if (!method->addr) {
7889                         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7890                                 method->addr = mono_lookup_internal_call (method);
7891                         else
7892                                 if (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)
7893                                         mono_lookup_pinvoke_call (method, NULL, NULL);
7894                 }
7895 #ifdef MONO_USE_EXC_TABLES
7896                 if (mono_method_blittable (method)) {
7897                         return method->addr;
7898                 } else {
7899 #endif
7900                         nm = mono_marshal_get_native_wrapper (method);
7901                         return mono_compile_method (nm);
7902
7903                         //if (mono_debug_format != MONO_DEBUG_FORMAT_NONE) 
7904                         //mono_debug_add_wrapper (method, nm);
7905 #ifdef MONO_USE_EXC_TABLES
7906                 }
7907 #endif
7908         } else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
7909                 const char *name = method->name;
7910                 MonoMethod *nm;
7911
7912                 if (method->klass->parent == mono_defaults.multicastdelegate_class) {
7913                         if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
7914                                 /* FIXME: uhm, we need a wrapper to handle exceptions? */
7915                                 return (gpointer)mono_delegate_ctor;
7916                         } else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
7917                                 nm = mono_marshal_get_delegate_invoke (method);
7918                                 return mono_jit_compile_method (nm);
7919                         } else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
7920                                 nm = mono_marshal_get_delegate_begin_invoke (method);
7921                                 return mono_jit_compile_method (nm);
7922                         } else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
7923                                 nm = mono_marshal_get_delegate_end_invoke (method);
7924                                 return mono_jit_compile_method (nm);
7925                         }
7926                 }
7927                 return NULL;
7928         }
7929
7930         cfg = mini_method_compile (method, opt, target_domain, TRUE, 0);
7931
7932         mono_domain_lock (target_domain);
7933
7934         /* Check if some other thread already did the job. In this case, we can
7935        discard the code this thread generated. */
7936
7937         if ((info = g_hash_table_lookup (target_domain->jit_code_hash, method))) {
7938                 /* We can't use a domain specific method in another domain */
7939                 if ((target_domain == mono_domain_get ()) || info->domain_neutral) {
7940                         code = info->code_start;
7941 //                      printf("Discarding code for method %s\n", method->name);
7942                 }
7943         }
7944         
7945         if (code == NULL) {
7946                 g_hash_table_insert (jit_code_hash, method, cfg->jit_info);
7947                 code = cfg->native_code;
7948         }
7949
7950         mono_destroy_compile (cfg);
7951
7952         if (target_domain->jump_target_hash) {
7953                 MonoJumpInfo patch_info;
7954                 GSList *list, *tmp;
7955                 list = g_hash_table_lookup (target_domain->jump_target_hash, method);
7956                 if (list) {
7957                         patch_info.next = NULL;
7958                         patch_info.ip.i = 0;
7959                         patch_info.type = MONO_PATCH_INFO_METHOD_JUMP;
7960                         patch_info.data.method = method;
7961                         g_hash_table_remove (target_domain->jump_target_hash, method);
7962                 }
7963                 for (tmp = list; tmp; tmp = tmp->next)
7964                         mono_arch_patch_code (NULL, target_domain, tmp->data, &patch_info, TRUE);
7965                 g_slist_free (list);
7966         }
7967
7968         mono_domain_unlock (target_domain);
7969
7970         mono_runtime_class_init (mono_class_vtable (target_domain, method->klass));
7971         return code;
7972 }
7973
7974 static gpointer
7975 mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt)
7976 {
7977         /* FIXME: later copy the code from mono */
7978         MonoDomain *target_domain, *domain = mono_domain_get ();
7979         MonoJitInfo *info;
7980         gpointer p;
7981
7982         if (default_opt & MONO_OPT_SHARED)
7983                 target_domain = mono_root_domain;
7984         else 
7985                 target_domain = domain;
7986
7987         mono_domain_lock (target_domain);
7988
7989         if ((info = g_hash_table_lookup (target_domain->jit_code_hash, method))) {
7990                 /* We can't use a domain specific method in another domain */
7991                 if (! ((domain != target_domain) && !info->domain_neutral)) {
7992                         mono_domain_unlock (target_domain);
7993                         mono_jit_stats.methods_lookups++;
7994                         mono_runtime_class_init (mono_class_vtable (target_domain, method->klass));
7995                         return info->code_start;
7996                 }
7997         }
7998
7999         mono_domain_unlock (target_domain);
8000         p = mono_jit_compile_method_inner (method, target_domain);
8001         return p;
8002 }
8003
8004 static gpointer
8005 mono_jit_compile_method (MonoMethod *method)
8006 {
8007         return mono_jit_compile_method_with_opt (method, default_opt);
8008 }
8009
8010 static gpointer
8011 mono_jit_find_compiled_method (MonoDomain *domain, MonoMethod *method)
8012 {
8013         MonoDomain *target_domain;
8014         MonoJitInfo *info;
8015
8016         if (default_opt & MONO_OPT_SHARED)
8017                 target_domain = mono_root_domain;
8018         else 
8019                 target_domain = domain;
8020
8021         mono_domain_lock (target_domain);
8022
8023         if ((info = g_hash_table_lookup (target_domain->jit_code_hash, method))) {
8024                 /* We can't use a domain specific method in another domain */
8025                 if (! ((domain != target_domain) && !info->domain_neutral)) {
8026                         mono_domain_unlock (target_domain);
8027                         mono_jit_stats.methods_lookups++;
8028                         return info->code_start;
8029                 }
8030         }
8031
8032         mono_domain_unlock (target_domain);
8033
8034         return NULL;
8035 }
8036
8037 /**
8038  * mono_jit_runtime_invoke:
8039  * @method: the method to invoke
8040  * @obj: this pointer
8041  * @params: array of parameter values.
8042  * @exc: used to catch exceptions objects
8043  */
8044 static MonoObject*
8045 mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
8046 {
8047         MonoMethod *invoke;
8048         MonoObject *(*runtime_invoke) (MonoObject *this, void **params, MonoObject **exc);
8049
8050         if (obj == NULL && !(method->flags & METHOD_ATTRIBUTE_STATIC) && !method->string_ctor && (method->wrapper_type == 0)) {
8051                 g_warning ("Ignoring invocation of an instance method on a NULL instance.\n");
8052                 return NULL;
8053         }
8054
8055         invoke = mono_marshal_get_runtime_invoke (method);
8056         runtime_invoke = mono_jit_compile_method (invoke);
8057         return runtime_invoke (obj, params, exc);
8058 }
8059
8060 #ifdef PLATFORM_WIN32
8061 #define GET_CONTEXT \
8062         struct sigcontext *ctx = (struct sigcontext*)_dummy;
8063 #else
8064 #ifdef __sparc
8065 #define GET_CONTEXT \
8066     void *ctx = context;
8067 #else
8068 #define GET_CONTEXT \
8069         void **_p = (void **)&_dummy; \
8070         struct sigcontext *ctx = (struct sigcontext *)++_p;
8071 #endif
8072 #endif
8073
8074 #ifdef MONO_ARCH_USE_SIGACTION
8075 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy, siginfo_t *info, void *context)
8076 #else
8077 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy)
8078 #endif
8079
8080 static void
8081 SIG_HANDLER_SIGNATURE (sigfpe_signal_handler)
8082 {
8083         MonoException *exc;
8084         GET_CONTEXT
8085
8086         exc = mono_get_exception_divide_by_zero ();
8087         
8088         mono_arch_handle_exception (ctx, exc, FALSE);
8089 }
8090
8091 static void
8092 SIG_HANDLER_SIGNATURE (sigill_signal_handler)
8093 {
8094         MonoException *exc;
8095         GET_CONTEXT
8096         exc = mono_get_exception_execution_engine ("SIGILL");
8097         
8098         mono_arch_handle_exception (ctx, exc, FALSE);
8099 }
8100
8101 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
8102
8103 static void
8104 sigsegv_signal_handler (int _dummy, siginfo_t *info, void *context)
8105 {
8106         MonoException *exc;
8107         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
8108         struct sigcontext *ctx = (struct sigcontext *)&(((ucontext_t*)context)->uc_mcontext);
8109
8110         /* Can't allocate memory using Boehm GC on altstack */
8111         if (jit_tls->stack_size && 
8112                 ((guint8*)info->si_addr >= (guint8*)jit_tls->end_of_stack - jit_tls->stack_size) &&
8113                 ((guint8*)info->si_addr < (guint8*)jit_tls->end_of_stack))
8114                 exc = mono_domain_get ()->stack_overflow_ex;
8115         else
8116                 exc = mono_domain_get ()->null_reference_ex;
8117                         
8118         mono_arch_handle_exception (ctx, exc, FALSE);
8119 }
8120
8121 #else
8122
8123 static void
8124 SIG_HANDLER_SIGNATURE (sigsegv_signal_handler)
8125 {
8126         GET_CONTEXT;
8127
8128         mono_arch_handle_exception (ctx, NULL, FALSE);
8129 }
8130
8131 #endif
8132
8133 static void
8134 SIG_HANDLER_SIGNATURE (sigusr1_signal_handler)
8135 {
8136         MonoThread *thread;
8137         GET_CONTEXT
8138         
8139         thread = mono_thread_current ();
8140
8141         thread->abort_exc = mono_get_exception_thread_abort ();
8142
8143         mono_arch_handle_exception (ctx, thread->abort_exc, FALSE);
8144 }
8145
8146 static void
8147 SIG_HANDLER_SIGNATURE (sigquit_signal_handler)
8148 {
8149        MonoException *exc;
8150        GET_CONTEXT
8151
8152        exc = mono_get_exception_execution_engine ("Interrupted (SIGQUIT).");
8153        
8154        mono_arch_handle_exception (ctx, exc, FALSE);
8155 }
8156
8157 static void
8158 SIG_HANDLER_SIGNATURE (sigint_signal_handler)
8159 {
8160         MonoException *exc;
8161         GET_CONTEXT
8162
8163         exc = mono_get_exception_execution_engine ("Interrupted (SIGINT).");
8164         
8165         mono_arch_handle_exception (ctx, exc, FALSE);
8166 }
8167
8168 #ifndef PLATFORM_WIN32
8169 static void
8170 add_signal_handler (int signo, gpointer handler)
8171 {
8172         struct sigaction sa;
8173
8174 #ifdef MONO_ARCH_USE_SIGACTION
8175         sa.sa_sigaction = handler;
8176         sigemptyset (&sa.sa_mask);
8177         sa.sa_flags = SA_SIGINFO;
8178 #else
8179         sa.sa_handler = handler;
8180         sigemptyset (&sa.sa_mask);
8181         sa.sa_flags = 0;
8182 #endif
8183         g_assert (sigaction (signo, &sa, NULL) != -1);
8184 }
8185 #endif
8186
8187 static void
8188 mono_runtime_install_handlers (void)
8189 {
8190 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
8191         struct sigaction sa;
8192 #endif
8193
8194 #ifdef PLATFORM_WIN32
8195         win32_seh_init();
8196         win32_seh_set_handler(SIGFPE, sigfpe_signal_handler);
8197         win32_seh_set_handler(SIGILL, sigill_signal_handler);
8198         win32_seh_set_handler(SIGSEGV, sigsegv_signal_handler);
8199         if (getenv ("MONO_DEBUG"))
8200                 win32_seh_set_handler(SIGINT, sigint_signal_handler);
8201 #else /* !PLATFORM_WIN32 */
8202
8203         /* libpthreads has its own implementation of sigaction(),
8204          * but it seems to work well with our current exception
8205          * handlers. If not we must call syscall directly instead 
8206          * of sigaction */
8207         
8208         if (getenv ("MONO_DEBUG")) {
8209                 add_signal_handler (SIGINT, sigint_signal_handler);
8210         }
8211
8212         add_signal_handler (SIGFPE, sigfpe_signal_handler);
8213         add_signal_handler (SIGQUIT, sigquit_signal_handler);
8214         add_signal_handler (SIGILL, sigill_signal_handler);
8215         add_signal_handler (mono_thread_get_abort_signal (), sigusr1_signal_handler);
8216
8217         /* catch SIGSEGV */
8218 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
8219         sa.sa_sigaction = sigsegv_signal_handler;
8220         sigemptyset (&sa.sa_mask);
8221         sa.sa_flags = SA_SIGINFO | SA_STACK;
8222         g_assert (sigaction (SIGSEGV, &sa, NULL) != -1);
8223 #else
8224         add_signal_handler (SIGSEGV, sigsegv_signal_handler);
8225 #endif
8226
8227 #endif /* PLATFORM_WIN32 */
8228 }
8229
8230 /* mono_jit_create_remoting_trampoline:
8231  * @method: pointer to the method info
8232  *
8233  * Creates a trampoline which calls the remoting functions. This
8234  * is used in the vtable of transparent proxies.
8235  * 
8236  * Returns: a pointer to the newly created code 
8237  */
8238 static gpointer
8239 mono_jit_create_remoting_trampoline (MonoMethod *method)
8240 {
8241         MonoMethod *nm;
8242         guint8 *addr = NULL;
8243
8244         if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) || 
8245             (method->signature->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class))) {
8246                 nm = mono_marshal_get_remoting_invoke (method);
8247                 addr = mono_compile_method (nm);
8248         } else {
8249                 addr = mono_compile_method (method);
8250         }
8251         return addr;
8252 }
8253
8254 MonoDomain *
8255 mini_init (const char *filename)
8256 {
8257         MonoDomain *domain;
8258
8259         mono_arch_cpu_init ();
8260
8261         if (!g_thread_supported ())
8262                 g_thread_init (NULL);
8263
8264         mono_jit_tls_id = TlsAlloc ();
8265         setup_jit_tls_data ((gpointer)-1, mono_thread_abort);
8266
8267         InitializeCriticalSection (&trampoline_hash_mutex);
8268
8269         mono_burg_init ();
8270
8271         if (default_opt & MONO_OPT_AOT)
8272                 mono_aot_init ();
8273
8274         mono_runtime_install_handlers ();
8275         mono_threads_install_cleanup (mini_thread_cleanup);
8276
8277 #define JIT_TRAMPOLINES_WORK
8278 #ifdef JIT_TRAMPOLINES_WORK
8279         mono_install_compile_method (mono_jit_compile_method);
8280         mono_install_trampoline (mono_arch_create_jit_trampoline);
8281         mono_install_remoting_trampoline (mono_jit_create_remoting_trampoline);
8282 #endif
8283 #define JIT_INVOKE_WORKS
8284 #ifdef JIT_INVOKE_WORKS
8285         mono_install_runtime_invoke (mono_jit_runtime_invoke);
8286         mono_install_handler (mono_arch_get_throw_exception ());
8287 #endif
8288         mono_install_stack_walk (mono_jit_walk_stack);
8289         mono_install_get_config_dir ();
8290
8291         domain = mono_init (filename);
8292         mono_init_icall ();
8293
8294         mono_add_internal_call ("System.Diagnostics.StackFrame::get_frame_info", 
8295                                 ves_icall_get_frame_info);
8296         mono_add_internal_call ("System.Diagnostics.StackTrace::get_trace", 
8297                                 ves_icall_get_trace);
8298         mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers", 
8299                                 mono_runtime_install_handlers);
8300
8301
8302         create_helper_signature ();
8303
8304 #define JIT_CALLS_WORK
8305 #ifdef JIT_CALLS_WORK
8306         /* Needs to be called here since register_jit_icall depends on it */
8307         mono_marshal_init ();
8308
8309         mono_arch_register_lowlevel_calls ();
8310         mono_register_jit_icall (mono_profiler_method_enter, "mono_profiler_method_enter", NULL, TRUE);
8311         mono_register_jit_icall (mono_profiler_method_leave, "mono_profiler_method_leave", NULL, TRUE);
8312         mono_register_jit_icall (mono_trace_enter_method, "mono_trace_enter_method", NULL, TRUE);
8313         mono_register_jit_icall (mono_trace_leave_method, "mono_trace_leave_method", NULL, TRUE);
8314
8315         mono_register_jit_icall (mono_get_lmf_addr, "mono_get_lmf_addr", helper_sig_ptr_void, TRUE);
8316         mono_register_jit_icall (mono_domain_get, "mono_domain_get", helper_sig_domain_get, TRUE);
8317
8318         /* fixme: we cant hanlde vararg methods this way, because the signature is not constant */
8319         //mono_register_jit_icall (ves_array_element_address, "ves_array_element_address", NULL);
8320         //mono_register_jit_icall (mono_array_new_va, "mono_array_new_va", NULL);
8321
8322         mono_register_jit_icall (mono_arch_get_throw_exception (), "mono_arch_throw_exception", helper_sig_void_obj, TRUE);
8323         mono_register_jit_icall (mono_arch_get_throw_exception_by_name (), "mono_arch_throw_exception_by_name", 
8324                                  helper_sig_void_ptr, TRUE);
8325         mono_register_jit_icall (mono_thread_get_pending_exception, "mono_thread_get_pending_exception", helper_sig_obj_void, FALSE);
8326
8327         /* 
8328          * NOTE, NOTE, NOTE, NOTE:
8329          * when adding emulation for some opcodes, remember to also add a dummy
8330          * rule to the burg files, because we need the arity information to be correct.
8331          */
8332         mono_register_opcode_emulation (OP_LMUL, "__emul_lmul", helper_sig_long_long_long, mono_llmult, TRUE);
8333         mono_register_opcode_emulation (OP_LMUL_OVF_UN, "__emul_lmul_ovf_un", helper_sig_long_long_long, mono_llmult_ovf_un, FALSE);
8334         mono_register_opcode_emulation (OP_LMUL_OVF, "__emul_lmul_ovf", helper_sig_long_long_long, mono_llmult_ovf, FALSE);
8335         mono_register_opcode_emulation (OP_LDIV, "__emul_ldiv", helper_sig_long_long_long, mono_lldiv, FALSE);
8336         mono_register_opcode_emulation (OP_LDIV_UN, "__emul_ldiv_un", helper_sig_long_long_long, mono_lldiv_un, FALSE);
8337         mono_register_opcode_emulation (OP_LREM, "__emul_lrem", helper_sig_long_long_long, mono_llrem, FALSE);
8338         mono_register_opcode_emulation (OP_LREM_UN, "__emul_lrem_un", helper_sig_long_long_long, mono_llrem_un, FALSE);
8339
8340         mono_register_opcode_emulation (OP_LSHL, "__emul_lshl", helper_sig_long_long_int, mono_lshl, TRUE);
8341         mono_register_opcode_emulation (OP_LSHR, "__emul_lshr", helper_sig_long_long_int, mono_lshr, TRUE);
8342         mono_register_opcode_emulation (OP_LSHR_UN, "__emul_lshr_un", helper_sig_long_long_int, mono_lshr_un, TRUE);
8343
8344         mono_register_opcode_emulation (OP_FCONV_TO_U8, "__emul_fconv_to_u8", helper_sig_ulong_double, mono_fconv_u8, FALSE);
8345         mono_register_opcode_emulation (OP_FCONV_TO_U4, "__emul_fconv_to_u4", helper_sig_uint_double, mono_fconv_u4, FALSE);
8346         mono_register_opcode_emulation (OP_FCONV_TO_OVF_I8, "__emul_fconv_to_ovf_i8", helper_sig_long_double, mono_fconv_ovf_i8, FALSE);
8347         mono_register_opcode_emulation (OP_FCONV_TO_OVF_U8, "__emul_fconv_to_ovf_u8", helper_sig_ulong_double, mono_fconv_ovf_u8, FALSE);
8348
8349 #ifdef MONO_ARCH_EMULATE_FCONV_TO_I8
8350         mono_register_opcode_emulation (OP_FCONV_TO_I8, "__emul_fconv_to_i8", helper_sig_long_double, mono_fconv_i8, FALSE);
8351 #endif
8352 #ifdef MONO_ARCH_EMULATE_CONV_R8_UN
8353         mono_register_opcode_emulation (CEE_CONV_R_UN, "__emul_conv_r_un", helper_sig_double_int, mono_conv_to_r8_un, FALSE);
8354 #endif
8355 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8
8356         mono_register_opcode_emulation (OP_LCONV_TO_R8, "__emul_lconv_to_r8", helper_sig_double_long, mono_lconv_to_r8, FALSE);
8357 #endif
8358 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R4
8359         mono_register_opcode_emulation (OP_LCONV_TO_R4, "__emul_lconv_to_r4", helper_sig_float_long, mono_lconv_to_r4, FALSE);
8360 #endif
8361 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8_UN
8362         mono_register_opcode_emulation (OP_LCONV_TO_R_UN, "__emul_lconv_to_r8_un", helper_sig_double_long, mono_lconv_to_r8_un, FALSE);
8363 #endif
8364 #ifdef MONO_ARCH_EMULATE_FREM
8365         mono_register_opcode_emulation (OP_FREM, "__emul_frem", helper_sig_double_double_double, fmod, FALSE);
8366 #endif
8367
8368 #if SIZEOF_VOID_P == 4
8369         mono_register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", helper_sig_uint_double, mono_fconv_u4, TRUE);
8370 #else
8371 #ifdef __GNUC__
8372 #warning "fixme: add opcode emulation"
8373 #endif
8374 #endif
8375
8376         /* other jit icalls */
8377         mono_register_jit_icall (mono_class_static_field_address , "mono_class_static_field_address", 
8378                                  helper_sig_ptr_ptr_ptr, FALSE);
8379         mono_register_jit_icall (mono_ldtoken_wrapper, "mono_ldtoken_wrapper", helper_sig_ptr_ptr_ptr, FALSE);
8380         mono_register_jit_icall (mono_get_special_static_data, "mono_get_special_static_data", helper_sig_ptr_int, FALSE);
8381         mono_register_jit_icall (mono_ldstr, "mono_ldstr", helper_sig_ldstr, FALSE);
8382         mono_register_jit_icall (helper_memcpy, "helper_memcpy", helper_sig_memcpy, FALSE);
8383         mono_register_jit_icall (helper_memset, "helper_memset", helper_sig_memset, FALSE);
8384         mono_register_jit_icall (helper_initobj, "helper_initobj", helper_sig_initobj, FALSE);
8385         mono_register_jit_icall (helper_stelem_ref, "helper_stelem_ref", helper_sig_stelem_ref, FALSE);
8386         mono_register_jit_icall (helper_stelem_ref_check, "helper_stelem_ref_check", helper_sig_stelem_ref_check, FALSE);
8387         mono_register_jit_icall (mono_object_new, "mono_object_new", helper_sig_object_new, FALSE);
8388         mono_register_jit_icall (mono_object_new_specific, "mono_object_new_specific", helper_sig_object_new_specific, FALSE);
8389         mono_register_jit_icall (mono_object_new_fast, "mono_object_new_fast", helper_sig_object_new_specific, FALSE);
8390         mono_register_jit_icall (mono_array_new, "mono_array_new", helper_sig_newarr, FALSE);
8391         mono_register_jit_icall (mono_array_new_specific, "mono_array_new_specific", helper_sig_newarr_specific, FALSE);
8392         mono_register_jit_icall (mono_string_to_utf16, "mono_string_to_utf16", helper_sig_ptr_obj, FALSE);
8393         mono_register_jit_icall (mono_string_from_utf16, "mono_string_from_utf16", helper_sig_obj_ptr, FALSE);
8394         mono_register_jit_icall (mono_string_new_wrapper, "mono_string_new_wrapper", helper_sig_obj_ptr, FALSE);
8395         mono_register_jit_icall (mono_string_to_utf8, "mono_string_to_utf8", helper_sig_ptr_obj, FALSE);
8396         mono_register_jit_icall (mono_string_to_bstr, "mono_string_to_bstr", helper_sig_ptr_obj, FALSE);
8397         mono_register_jit_icall (mono_string_to_ansibstr, "mono_string_to_ansibstr", helper_sig_ptr_obj, FALSE);
8398         mono_register_jit_icall (mono_string_builder_to_utf8, "mono_string_builder_to_utf8", helper_sig_ptr_obj, FALSE);
8399         mono_register_jit_icall (mono_string_builder_to_utf16, "mono_string_builder_to_utf16", helper_sig_ptr_obj, FALSE);
8400         mono_register_jit_icall (mono_array_to_savearray, "mono_array_to_savearray", helper_sig_ptr_obj, FALSE);
8401         mono_register_jit_icall (mono_array_to_lparray, "mono_array_to_lparray", helper_sig_ptr_obj, FALSE);
8402         mono_register_jit_icall (mono_delegate_to_ftnptr, "mono_delegate_to_ftnptr", helper_sig_ptr_obj, FALSE);
8403         mono_register_jit_icall (mono_marshal_string_array, "mono_marshal_string_array", helper_sig_ptr_obj, FALSE);
8404         mono_register_jit_icall (mono_string_utf8_to_builder, "mono_string_utf8_to_builder", helper_sig_void_ptr_ptr, FALSE);
8405         mono_register_jit_icall (mono_string_utf16_to_builder, "mono_string_utf16_to_builder", helper_sig_void_ptr_ptr, FALSE);
8406         mono_register_jit_icall (mono_marshal_free_array, "mono_marshal_free_array", helper_sig_void_ptr_ptr, FALSE);
8407         mono_register_jit_icall (mono_string_to_byvalstr, "mono_string_to_byvalstr", helper_sig_void_ptr_ptr_ptr, FALSE);
8408         mono_register_jit_icall (mono_string_to_byvalwstr, "mono_string_to_byvalwstr", helper_sig_void_ptr_ptr_ptr, FALSE);
8409         mono_register_jit_icall (g_free, "g_free", helper_sig_void_ptr, FALSE);
8410         mono_register_jit_icall (mono_runtime_class_init, "mono_runtime_class_init", helper_sig_void_ptr, FALSE);
8411         mono_register_jit_icall (mono_ldftn, "mono_ldftn", helper_sig_compile, FALSE);
8412         mono_register_jit_icall (mono_ldftn_nosync, "mono_ldftn_nosync", helper_sig_compile, FALSE);
8413         mono_register_jit_icall (mono_ldvirtfn, "mono_ldvirtfn", helper_sig_compile_virt, FALSE);
8414 #endif
8415
8416 #define JIT_RUNTIME_WORKS
8417 #ifdef JIT_RUNTIME_WORKS
8418         mono_runtime_install_cleanup ((MonoDomainFunc)mini_cleanup);
8419         mono_runtime_init (domain, mono_thread_start_cb, mono_thread_attach_cb);
8420 #endif
8421
8422         mono_thread_attach (domain);
8423         return domain;
8424 }
8425
8426 MonoJitStats mono_jit_stats = {0};
8427
8428 static void 
8429 print_jit_stats (void)
8430 {
8431         if (mono_jit_stats.enabled) {
8432                 g_print ("Mono Jit statistics\n");
8433                 g_print ("Compiled methods:       %ld\n", mono_jit_stats.methods_compiled);
8434                 g_print ("Methods from AOT:       %ld\n", mono_jit_stats.methods_aot);
8435                 g_print ("Methods cache lookup:   %ld\n", mono_jit_stats.methods_lookups);
8436                 g_print ("Method trampolines:     %ld\n", mono_jit_stats.method_trampolines);
8437                 g_print ("Basic blocks:           %ld\n", mono_jit_stats.basic_blocks);
8438                 g_print ("Max basic blocks:       %ld\n", mono_jit_stats.max_basic_blocks);
8439                 g_print ("Allocated vars:         %ld\n", mono_jit_stats.allocate_var);
8440                 g_print ("Analyze stack repeat:   %ld\n", mono_jit_stats.analyze_stack_repeat);
8441                 g_print ("Compiled CIL code size: %ld\n", mono_jit_stats.cil_code_size);
8442                 g_print ("Native code size:       %ld\n", mono_jit_stats.native_code_size);
8443                 g_print ("Max code size ratio:    %.2f (%s::%s)\n", mono_jit_stats.max_code_size_ratio/100.0,
8444                                 mono_jit_stats.max_ratio_method->klass->name, mono_jit_stats.max_ratio_method->name);
8445                 g_print ("Biggest method:         %ld (%s::%s)\n", mono_jit_stats.biggest_method_size,
8446                                 mono_jit_stats.biggest_method->klass->name, mono_jit_stats.biggest_method->name);
8447                 g_print ("Code reallocs:          %ld\n", mono_jit_stats.code_reallocs);
8448                 g_print ("Allocated code size:    %ld\n", mono_jit_stats.allocated_code_size);
8449                 g_print ("Inlineable methods:     %ld\n", mono_jit_stats.inlineable_methods);
8450                 g_print ("Inlined methods:        %ld\n", mono_jit_stats.inlined_methods);
8451                 
8452                 g_print ("\nCreated object count:   %ld\n", mono_stats.new_object_count);
8453                 g_print ("Initialized classes:    %ld\n", mono_stats.initialized_class_count);
8454                 g_print ("Used classes:           %ld\n", mono_stats.used_class_count);
8455                 g_print ("Static data size:       %ld\n", mono_stats.class_static_data_size);
8456                 g_print ("VTable data size:       %ld\n", mono_stats.class_vtable_size);
8457
8458                 g_print ("\nGeneric instances:      %ld\n", mono_stats.generic_instance_count);
8459                 g_print ("Inflated methods:       %ld\n", mono_stats.inflated_method_count);
8460                 g_print ("Inflated types:         %ld\n", mono_stats.inflated_type_count);
8461                 g_print ("Generics metadata size: %ld\n", mono_stats.generics_metadata_size);
8462         }
8463 }
8464
8465 void
8466 mini_cleanup (MonoDomain *domain)
8467 {
8468         /* 
8469          * mono_runtime_cleanup() and mono_domain_finalize () need to
8470          * be called early since they need the execution engine still
8471          * fully working (mono_domain_finalize may invoke managed finalizers
8472          * and mono_runtime_cleanup will wait for other threads to finish).
8473          */
8474         mono_domain_finalize (domain, 2000);
8475
8476         mono_runtime_cleanup (domain);
8477
8478         mono_profiler_shutdown ();
8479
8480         mono_debug_cleanup ();
8481
8482 #ifdef PLATFORM_WIN32
8483         win32_seh_cleanup();
8484 #endif
8485
8486         mono_domain_free (domain, TRUE);
8487
8488         print_jit_stats ();
8489 }
8490
8491 void
8492 mono_set_defaults (int verbose_level, guint32 opts)
8493 {
8494         mini_verbose = verbose_level;
8495         default_opt = opts;
8496 }
8497
8498 static void
8499 mono_precompile_assembly (MonoAssembly *ass, void *user_data)
8500 {
8501         MonoImage *image = ass->image;
8502         MonoMethod *method;
8503         int i, count = 0;
8504
8505         if (mini_verbose > 0)
8506                 printf ("PRECOMPILE: %s.\n", ass->image->name);
8507
8508         for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8509                 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
8510                 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
8511                         continue;
8512                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
8513                         continue;
8514
8515                 count++;
8516                 if (mini_verbose > 1) {
8517                         char * desc = mono_method_full_name (method, TRUE);
8518                         g_print ("Compiling %d %s\n", count, desc);
8519                         g_free (desc);
8520                 }
8521                 mono_compile_method (method);
8522         }
8523 }
8524
8525 void mono_precompile_assemblies ()
8526 {
8527         mono_assembly_foreach ((GFunc)mono_precompile_assembly, NULL);
8528 }