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