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