2004-05-16 Patrik Torstensson <totte@hiddenpeaks.com>
[mono.git] / mono / mini / mini.c
1 /*
2  * mini.c: The new Mono code generator.
3  *
4  * Author:
5  *   Paolo Molaro (lupus@ximian.com)
6  *   Dietmar Maurer (dietmar@ximian.com)
7  *
8  * (C) 2002 Ximian, Inc.
9  */
10
11 #include <config.h>
12 #include <signal.h>
13 #include <unistd.h>
14 #include <math.h>
15
16 #ifdef HAVE_VALGRIND_MEMCHECK_H
17 #include <valgrind/memcheck.h>
18 #endif
19
20 #include <mono/metadata/assembly.h>
21 #include <mono/metadata/loader.h>
22 #include <mono/metadata/cil-coff.h>
23 #include <mono/metadata/tabledefs.h>
24 #include <mono/metadata/class.h>
25 #include <mono/metadata/object.h>
26 #include <mono/metadata/exception.h>
27 #include <mono/metadata/opcodes.h>
28 #include <mono/metadata/mono-endian.h>
29 #include <mono/metadata/tokentype.h>
30 #include <mono/metadata/tabledefs.h>
31 #include <mono/metadata/threads.h>
32 #include <mono/metadata/marshal.h>
33 #include <mono/metadata/socket-io.h>
34 #include <mono/metadata/appdomain.h>
35 #include <mono/metadata/debug-helpers.h>
36 #include <mono/io-layer/io-layer.h>
37 #include "mono/metadata/profiler.h"
38 #include <mono/metadata/profiler-private.h>
39 #include <mono/metadata/mono-config.h>
40 #include <mono/metadata/environment.h>
41 #include <mono/metadata/mono-debug.h>
42 #include <mono/metadata/mono-debug-debugger.h>
43 #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                                 /* spill it to reduce the expression complexity
5413                                  * and workaround bug 54209 
5414                                  */
5415                                 if (cmp->inst_left->type == STACK_I8) {
5416                                         MonoInst *store, *temp, *load;
5417                                         --sp;
5418                                         temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
5419                                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
5420                                         store->cil_code = ins->cil_code;
5421                                         MONO_ADD_INS (bblock, store);
5422                                         NEW_TEMPLOAD (cfg, load, temp->inst_c0);
5423                                         load->cil_code = ins->cil_code;
5424                                         *sp++ = load;
5425                                 }
5426                                 ip += 2;
5427                                 break;
5428                         }
5429                         case CEE_LDFTN: {
5430                                 MonoInst *argconst;
5431                                 int temp;
5432
5433                                 CHECK_STACK_OVF (1);
5434                                 CHECK_OPSIZE (6);
5435                                 n = read32 (ip + 2);
5436                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
5437                                         cmethod = mono_method_get_wrapper_data (method, n);
5438                                 else {
5439                                         cmethod = mono_get_method_full (image, n, NULL, generic_context);
5440                                 }
5441
5442                                 mono_class_init (cmethod->klass);
5443                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
5444
5445                                 NEW_METHODCONST (cfg, argconst, cmethod);
5446                                 if (method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED)
5447                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn, &argconst, ip);
5448                                 else
5449                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn_nosync, &argconst, ip);
5450                                 NEW_TEMPLOAD (cfg, *sp, temp);
5451                                 sp ++;
5452                                 
5453                                 ip += 6;
5454                                 inline_costs += 10 * num_calls++;
5455                                 break;
5456                         }
5457                         case CEE_LDVIRTFTN: {
5458                                 MonoInst *args [2];
5459                                 int temp;
5460
5461                                 CHECK_STACK (1);
5462                                 CHECK_OPSIZE (6);
5463                                 n = read32 (ip + 2);
5464                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
5465                                         cmethod = mono_method_get_wrapper_data (method, n);
5466                                 else
5467                                         cmethod = mono_get_method_full (image, n, NULL, generic_context);
5468
5469                                 mono_class_init (cmethod->klass);
5470                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
5471
5472                                 --sp;
5473                                 args [0] = *sp;
5474                                 NEW_METHODCONST (cfg, args [1], cmethod);
5475                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldvirtfn, args, ip);
5476                                 NEW_TEMPLOAD (cfg, *sp, temp);
5477                                 sp ++;
5478
5479                                 ip += 6;
5480                                 inline_costs += 10 * num_calls++;
5481                                 break;
5482                         }
5483                         case CEE_LDARG:
5484                                 CHECK_STACK_OVF (1);
5485                                 CHECK_OPSIZE (4);
5486                                 n = read16 (ip + 2);
5487                                 CHECK_ARG (n);
5488                                 NEW_ARGLOAD (cfg, ins, n);
5489                                 ins->cil_code = ip;
5490                                 *sp++ = ins;
5491                                 ip += 4;
5492                                 break;
5493                         case CEE_LDARGA:
5494                                 CHECK_STACK_OVF (1);
5495                                 CHECK_OPSIZE (4);
5496                                 n = read16 (ip + 2);
5497                                 CHECK_ARG (n);
5498                                 NEW_ARGLOADA (cfg, ins, n);
5499                                 ins->cil_code = ip;
5500                                 *sp++ = ins;
5501                                 ip += 4;
5502                                 break;
5503                         case CEE_STARG:
5504                                 CHECK_STACK (1);
5505                                 --sp;
5506                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
5507                                 CHECK_OPSIZE (4);
5508                                 n = read16 (ip + 2);
5509                                 CHECK_ARG (n);
5510                                 NEW_ARGSTORE (cfg, ins, n, *sp);
5511                                 ins->cil_code = ip;
5512                                 if (ins->opcode == CEE_STOBJ) {
5513                                         NEW_ARGLOADA (cfg, ins, n);
5514                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
5515                                 } else
5516                                         MONO_ADD_INS (bblock, ins);
5517                                 ip += 4;
5518                                 break;
5519                         case CEE_LDLOC:
5520                                 CHECK_STACK_OVF (1);
5521                                 CHECK_OPSIZE (4);
5522                                 n = read16 (ip + 2);
5523                                 CHECK_LOCAL (n);
5524                                 NEW_LOCLOAD (cfg, ins, n);
5525                                 ins->cil_code = ip;
5526                                 *sp++ = ins;
5527                                 ip += 4;
5528                                 break;
5529                         case CEE_LDLOCA:
5530                                 CHECK_STACK_OVF (1);
5531                                 CHECK_OPSIZE (4);
5532                                 n = read16 (ip + 2);
5533                                 CHECK_LOCAL (n);
5534                                 NEW_LOCLOADA (cfg, ins, n);
5535                                 ins->cil_code = ip;
5536                                 *sp++ = ins;
5537                                 ip += 4;
5538                                 break;
5539                         case CEE_STLOC:
5540                                 CHECK_STACK (1);
5541                                 --sp;
5542                                 CHECK_OPSIZE (4);
5543                                 n = read16 (ip + 2);
5544                                 CHECK_LOCAL (n);
5545                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
5546                                 NEW_LOCSTORE (cfg, ins, n, *sp);
5547                                 ins->cil_code = ip;
5548                                 if (ins->opcode == CEE_STOBJ) {
5549                                         NEW_LOCLOADA (cfg, ins, n);
5550                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
5551                                 } else
5552                                         MONO_ADD_INS (bblock, ins);
5553                                 ip += 4;
5554                                 inline_costs += 1;
5555                                 break;
5556                         case CEE_LOCALLOC:
5557                                 CHECK_STACK (1);
5558                                 --sp;
5559                                 if (sp != stack_start) 
5560                                         goto unverified;
5561                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
5562                                 ins->inst_left = *sp;
5563                                 ins->cil_code = ip;
5564
5565                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
5566                                 if (header->init_locals)
5567                                         ins->flags |= MONO_INST_INIT;
5568
5569                                 *sp++ = ins;
5570                                 ip += 2;
5571                                 /* FIXME: set init flag if locals init is set in this method */
5572                                 break;
5573                         case CEE_ENDFILTER: {
5574                                 MonoExceptionClause *clause, *nearest;
5575                                 int cc, nearest_num;
5576
5577                                 CHECK_STACK (1);
5578                                 --sp;
5579                                 if ((sp != stack_start) || (sp [0]->type != STACK_I4)) 
5580                                         goto unverified;
5581                                 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
5582                                 ins->inst_left = *sp;
5583                                 ins->cil_code = ip;
5584                                 MONO_ADD_INS (bblock, ins);
5585                                 start_new_bblock = 1;
5586                                 ip += 2;
5587
5588                                 nearest = NULL;
5589                                 nearest_num = 0;
5590                                 for (cc = 0; cc < header->num_clauses; ++cc) {
5591                                         clause = &header->clauses [cc];
5592                                         if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
5593                                             (!nearest || (clause->token_or_filter > nearest->token_or_filter))) {
5594                                                 nearest = clause;
5595                                                 nearest_num = cc;
5596                                         }
5597                                 }
5598                                 g_assert (nearest);
5599                                 filter_lengths [nearest_num] = (ip - header->code) -  nearest->token_or_filter;
5600
5601                                 break;
5602                         }
5603                         case CEE_UNALIGNED_:
5604                                 ins_flag |= MONO_INST_UNALIGNED;
5605                                 /* FIXME: record alignment? we can assume 1 for now */
5606                                 CHECK_OPSIZE (3);
5607                                 ip += 3;
5608                                 break;
5609                         case CEE_VOLATILE_:
5610                                 ins_flag |= MONO_INST_VOLATILE;
5611                                 ip += 2;
5612                                 break;
5613                         case CEE_TAIL_:
5614                                 ins_flag |= MONO_INST_TAILCALL;
5615                                 /* Can't inline tail calls at this time */
5616                                 inline_costs += 100000;
5617                                 ip += 2;
5618                                 break;
5619                         case CEE_INITOBJ:
5620                                 CHECK_STACK (1);
5621                                 --sp;
5622                                 CHECK_OPSIZE (6);
5623                                 token = read32 (ip + 2);
5624                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
5625                                         klass = mono_method_get_wrapper_data (method, token);
5626                                 else
5627                                         klass = mono_class_get_full (image, token, generic_context);
5628                                 if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
5629                                         MonoInst *store, *load;
5630                                         NEW_PCONST (cfg, load, NULL);
5631                                         load->cil_code = ip;
5632                                         load->type = STACK_OBJ;
5633                                         MONO_INST_NEW (cfg, store, CEE_STIND_REF);
5634                                         store->cil_code = ip;
5635                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5636                                         MONO_ADD_INS (bblock, store);
5637                                         store->inst_i0 = sp [0];
5638                                         store->inst_i1 = load;
5639                                 } else {
5640                                         handle_initobj (cfg, bblock, *sp, NULL, klass, stack_start, sp);
5641                                 }
5642                                 ip += 6;
5643                                 inline_costs += 1;
5644                                 break;
5645                         case CEE_CONSTRAINED_:
5646                                 /* FIXME: implement */
5647                                 CHECK_OPSIZE (6);
5648                                 token = read32 (ip + 2);
5649                                 constrained_call = mono_class_get_full (image, token, generic_context);
5650                                 ip += 6;
5651                                 break;
5652                         case CEE_CPBLK:
5653                         case CEE_INITBLK: {
5654                                 MonoInst *iargs [3];
5655                                 CHECK_STACK (3);
5656                                 sp -= 3;
5657                                 if ((cfg->opt & MONO_OPT_INTRINS) && (ip [1] == CEE_CPBLK) && (sp [2]->opcode == OP_ICONST) && ((n = sp [2]->inst_c0) <= sizeof (gpointer) * 5)) {
5658                                         MonoInst *copy;
5659                                         MONO_INST_NEW (cfg, copy, OP_MEMCPY);
5660                                         copy->inst_left = sp [0];
5661                                         copy->inst_right = sp [1];
5662                                         copy->cil_code = ip;
5663                                         copy->unused = n;
5664                                         MONO_ADD_INS (bblock, copy);
5665                                         ip += 2;
5666                                         break;
5667                                 }
5668                                 iargs [0] = sp [0];
5669                                 iargs [1] = sp [1];
5670                                 iargs [2] = sp [2];
5671                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
5672                                 if (ip [1] == CEE_CPBLK) {
5673                                         mono_emit_jit_icall (cfg, bblock, helper_memcpy, iargs, ip);
5674                                 } else {
5675                                         mono_emit_jit_icall (cfg, bblock, helper_memset, iargs, ip);
5676                                 }
5677                                 ip += 2;
5678                                 inline_costs += 1;
5679                                 break;
5680                         }
5681                         case CEE_NO_:
5682                                 CHECK_OPSIZE (3);
5683                                 if (ip [2] & 0x1)
5684                                         ins_flag |= MONO_INST_NOTYPECHECK;
5685                                 if (ip [2] & 0x2)
5686                                         ins_flag |= MONO_INST_NORANGECHECK;
5687                                 /* we ignore the no-nullcheck for now since we
5688                                  * really do it explicitly only when doing callvirt->call
5689                                  */
5690                                 ip += 3;
5691                                 break;
5692                         case CEE_RETHROW: {
5693                                 MonoInst *load;
5694                                 /* FIXME: check we are in a catch handler */
5695                                 NEW_TEMPLOAD (cfg, load, cfg->exvar->inst_c0);
5696                                 load->cil_code = ip;
5697                                 MONO_INST_NEW (cfg, ins, CEE_THROW);
5698                                 ins->inst_left = load;
5699                                 ins->cil_code = ip;
5700                                 MONO_ADD_INS (bblock, ins);
5701                                 sp = stack_start;
5702                                 start_new_bblock = 1;
5703                                 ip += 2;
5704                                 break;
5705                         }
5706                         case CEE_SIZEOF:
5707                                 CHECK_STACK_OVF (1);
5708                                 CHECK_OPSIZE (6);
5709                                 token = read32 (ip + 2);
5710                                 /* FIXXME: handle generics. */
5711                                 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC) {
5712                                         MonoType *type = mono_type_create_from_typespec (image, token);
5713                                         token = mono_type_size (type, &align);
5714                                 } else {
5715                                         MonoClass *szclass = mono_class_get_full (image, token, generic_context);
5716                                         mono_class_init (szclass);
5717                                         token = mono_class_value_size (szclass, &align);
5718                                 }
5719                                 NEW_ICONST (cfg, ins, token);
5720                                 ins->cil_code = ip;
5721                                 *sp++= ins;
5722                                 ip += 6;
5723                                 break;
5724                         case CEE_REFANYTYPE:
5725                                 CHECK_STACK (1);
5726                                 MONO_INST_NEW (cfg, ins, OP_REFANYTYPE);
5727                                 --sp;
5728                                 ins->type = STACK_MP;
5729                                 ins->inst_left = *sp;
5730                                 ins->type = STACK_VTYPE;
5731                                 ins->klass = mono_defaults.typehandle_class;
5732                                 ins->cil_code = ip;
5733                                 ip += 2;
5734                                 *sp++ = ins;
5735                                 break;
5736                         case CEE_READONLY_:
5737                                 ip += 2;
5738                                 break;
5739                         default:
5740                                 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
5741                         }
5742                         break;
5743                 }
5744                 default:
5745                         g_error ("opcode 0x%02x not handled", *ip);
5746                 }
5747         }
5748         if (start_new_bblock != 1)
5749                 goto unverified;
5750
5751         bblock->cil_length = ip - bblock->cil_code;
5752         bblock->next_bb = end_bblock;
5753         link_bblock (cfg, bblock, end_bblock);
5754
5755         if (cfg->method == method && cfg->domainvar) {
5756                 MonoCallInst *call;
5757                 MonoInst *store;
5758
5759                 MONO_INST_NEW_CALL (cfg, call, CEE_CALL);
5760                 call->signature = helper_sig_domain_get;
5761                 call->inst.type = STACK_PTR;
5762                 call->fptr = mono_domain_get;
5763                 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, (MonoInst*)call);
5764                 
5765                 MONO_ADD_INS (init_localsbb, store);
5766         }
5767
5768         if (header->init_locals) {
5769                 MonoInst *store;
5770                 for (i = 0; i < header->num_locals; ++i) {
5771                         int t = header->locals [i]->type;
5772                         if (t == MONO_TYPE_VALUETYPE && header->locals [i]->data.klass->enumtype)
5773                                 t = header->locals [i]->data.klass->enum_basetype->type;
5774                         /* FIXME: use initobj for valuetypes, handle pointers, long, float. */
5775                         if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
5776                                 NEW_ICONST (cfg, ins, 0);
5777                                 NEW_LOCSTORE (cfg, store, i, ins);
5778                                 MONO_ADD_INS (init_localsbb, store);
5779                         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
5780                                 MONO_INST_NEW (cfg, ins, OP_I8CONST);
5781                                 ins->type = STACK_I8;
5782                                 ins->inst_l = 0;
5783                                 NEW_LOCSTORE (cfg, store, i, ins);
5784                                 MONO_ADD_INS (init_localsbb, store);
5785                         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
5786                                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
5787                                 ins->type = STACK_R8;
5788                                 ins->inst_p0 = (void*)&r8_0;
5789                                 NEW_LOCSTORE (cfg, store, i, ins);
5790                                 MONO_ADD_INS (init_localsbb, store);
5791                         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF)) {
5792                                 NEW_LOCLOADA (cfg, ins, i);
5793                                 handle_initobj (cfg, init_localsbb, ins, NULL, mono_class_from_mono_type (header->locals [i]), NULL, NULL);
5794                                 break;
5795                         } else {
5796                                 NEW_PCONST (cfg, ins, NULL);
5797                                 NEW_LOCSTORE (cfg, store, i, ins);
5798                                 MONO_ADD_INS (init_localsbb, store);
5799                         }
5800                 }
5801         }
5802
5803         
5804         /* resolve backward branches in the middle of an existing basic block */
5805         for (tmp = bb_recheck; tmp; tmp = tmp->next) {
5806                 bblock = tmp->data;
5807                 /*g_print ("need recheck in %s at IL_%04x\n", method->name, bblock->cil_code - header->code);*/
5808                 tblock = find_previous (bbhash, start_bblock, bblock->cil_code);
5809                 if (tblock != start_bblock) {
5810                         int l;
5811                         split_bblock (cfg, tblock, bblock);
5812                         l = bblock->cil_code - header->code;
5813                         bblock->cil_length = tblock->cil_length - l;
5814                         tblock->cil_length = l;
5815                 } else {
5816                         g_print ("recheck failed.\n");
5817                 }
5818         }
5819
5820         /*
5821          * we compute regions here, because the length of filter clauses is not known in advance.
5822          * It is computed in the CEE_ENDFILTER case in the above switch statement
5823          */
5824         if (cfg->method == method) {
5825                 MonoBasicBlock *bb;
5826                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5827                         bb->region = mono_find_block_region (cfg, bb->real_offset, filter_lengths);
5828                         if (cfg->spvars)
5829                                 mono_create_spvar_for_region (cfg, bb->region);
5830                         if (cfg->verbose_level > 2)
5831                                 g_print ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
5832                 }
5833         } else {
5834                 g_hash_table_destroy (bbhash);
5835         }
5836
5837         dont_inline = g_list_remove (dont_inline, method);
5838         return inline_costs;
5839
5840  inline_failure:
5841         if (cfg->method != method) 
5842                 g_hash_table_destroy (bbhash);
5843         dont_inline = g_list_remove (dont_inline, method);
5844         return -1;
5845
5846  unverified:
5847         if (cfg->method != method) 
5848                 g_hash_table_destroy (bbhash);
5849         g_error ("Invalid IL code at IL%04x in %s: %s\n", ip - header->code, 
5850                  mono_method_full_name (method, TRUE), mono_disasm_code_one (NULL, method, ip, NULL));
5851         dont_inline = g_list_remove (dont_inline, method);
5852         return -1;
5853 }
5854
5855 void
5856 mono_print_tree (MonoInst *tree) {
5857         int arity;
5858
5859         if (!tree)
5860                 return;
5861
5862         arity = mono_burg_arity [tree->opcode];
5863
5864         printf (" %s%s", arity?"(":"",  mono_inst_name (tree->opcode));
5865
5866         switch (tree->opcode) {
5867         case OP_ICONST:
5868                 printf ("[%d]", tree->inst_c0);
5869                 break;
5870         case OP_I8CONST:
5871                 printf ("[%lld]", tree->inst_l);
5872                 break;
5873         case OP_R8CONST:
5874                 printf ("[%f]", *(double*)tree->inst_p0);
5875                 break;
5876         case OP_R4CONST:
5877                 printf ("[%f]", *(float*)tree->inst_p0);
5878                 break;
5879         case OP_ARG:
5880         case OP_LOCAL:
5881                 printf ("[%d]", tree->inst_c0);
5882                 break;
5883         case OP_REGOFFSET:
5884                 if (tree->inst_offset < 0)
5885                         printf ("[-0x%x(%s)]", -tree->inst_offset, mono_arch_regname (tree->inst_basereg));
5886                 else
5887                         printf ("[0x%x(%s)]", tree->inst_offset, mono_arch_regname (tree->inst_basereg));
5888                 break;
5889         case OP_REGVAR:
5890                 printf ("[%s]", mono_arch_regname (tree->dreg));
5891                 break;
5892         case CEE_NEWARR:
5893                 printf ("[%s]",  tree->inst_newa_class->name);
5894                 mono_print_tree (tree->inst_newa_len);
5895                 break;
5896         case CEE_CALL:
5897         case CEE_CALLVIRT:
5898         case OP_FCALL:
5899         case OP_FCALLVIRT:
5900         case OP_LCALL:
5901         case OP_LCALLVIRT:
5902         case OP_VCALL:
5903         case OP_VCALLVIRT:
5904         case OP_VOIDCALL:
5905         case OP_VOIDCALLVIRT: {
5906                 MonoCallInst *call = (MonoCallInst*)tree;
5907                 if (call->method)
5908                         printf ("[%s]", call->method->name);
5909                 break;
5910         }
5911         case OP_PHI: {
5912                 int i;
5913                 printf ("[%d (", tree->inst_c0);
5914                 for (i = 0; i < tree->inst_phi_args [0]; i++) {
5915                         if (i)
5916                                 printf (", ");
5917                         printf ("%d", tree->inst_phi_args [i + 1]);
5918                 }
5919                 printf (")]");
5920                 break;
5921         }
5922         case OP_RENAME:
5923         case OP_RETARG:
5924         case CEE_NOP:
5925         case CEE_JMP:
5926         case CEE_BREAK:
5927                 break;
5928         case OP_LOAD_MEMBASE:
5929         case OP_LOADI4_MEMBASE:
5930         case OP_LOADU4_MEMBASE:
5931         case OP_LOADU1_MEMBASE:
5932         case OP_LOADI1_MEMBASE:
5933         case OP_LOADU2_MEMBASE:
5934         case OP_LOADI2_MEMBASE:
5935                 printf ("[%s] <- [%s + 0x%x]", mono_arch_regname (tree->dreg), mono_arch_regname (tree->inst_basereg), tree->inst_offset);
5936                 break;
5937         case CEE_BR:
5938                 printf ("[B%d]", tree->inst_target_bb->block_num);
5939                 break;
5940         case CEE_SWITCH:
5941         case CEE_ISINST:
5942         case CEE_CASTCLASS:
5943         case OP_OUTARG:
5944         case OP_CALL_REG:
5945         case OP_FCALL_REG:
5946         case OP_LCALL_REG:
5947         case OP_VCALL_REG:
5948         case OP_VOIDCALL_REG:
5949                 mono_print_tree (tree->inst_left);
5950                 break;
5951         case CEE_BNE_UN:
5952         case CEE_BEQ:
5953         case CEE_BLT:
5954         case CEE_BLT_UN:
5955         case CEE_BGT:
5956         case CEE_BGT_UN:
5957         case CEE_BGE:
5958         case CEE_BGE_UN:
5959         case CEE_BLE:
5960         case CEE_BLE_UN:
5961                 printf ("[B%dB%d]", tree->inst_true_bb->block_num, tree->inst_false_bb->block_num);
5962                 mono_print_tree (tree->inst_left);
5963                 break;
5964         default:
5965                 if (!mono_arch_print_tree(tree, arity)) {
5966                         if (arity) {
5967                                 mono_print_tree (tree->inst_left);
5968                                 if (arity > 1)
5969                                         mono_print_tree (tree->inst_right);
5970                         }
5971                 }
5972                 break;
5973         }
5974
5975         if (arity)
5976                 printf (")");
5977 }
5978
5979 void
5980 mono_print_tree_nl (MonoInst *tree)
5981 {
5982         mono_print_tree (tree);
5983         printf ("\n");
5984 }
5985
5986 static void
5987 create_helper_signature (void)
5988 {
5989         /* FIXME: set call conv */
5990         /* MonoArray * mono_array_new (MonoDomain *domain, MonoClass *klass, gint32 len) */
5991         helper_sig_newarr = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
5992         helper_sig_newarr->params [0] = helper_sig_newarr->params [1] = &mono_defaults.int_class->byval_arg;
5993         helper_sig_newarr->ret = &mono_defaults.object_class->byval_arg;
5994         helper_sig_newarr->params [2] = &mono_defaults.int32_class->byval_arg;
5995         helper_sig_newarr->pinvoke = 1;
5996
5997         /* MonoArray * mono_array_new_specific (MonoVTable *vtable, guint32 len) */
5998         helper_sig_newarr_specific = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
5999         helper_sig_newarr_specific->params [0] = &mono_defaults.int_class->byval_arg;
6000         helper_sig_newarr_specific->params [1] = &mono_defaults.int32_class->byval_arg;
6001         helper_sig_newarr_specific->ret = &mono_defaults.object_class->byval_arg;
6002         helper_sig_newarr_specific->pinvoke = 1;
6003
6004         /* MonoObject * mono_object_new (MonoDomain *domain, MonoClass *klass) */
6005         helper_sig_object_new = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
6006         helper_sig_object_new->params [0] = helper_sig_object_new->params [1] = &mono_defaults.int_class->byval_arg;
6007         helper_sig_object_new->ret = &mono_defaults.object_class->byval_arg;
6008         helper_sig_object_new->pinvoke = 1;
6009
6010         /* MonoObject * mono_object_new_specific (MonoVTable *vtable) */
6011         helper_sig_object_new_specific = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6012         helper_sig_object_new_specific->params [0] = &mono_defaults.int_class->byval_arg;
6013         helper_sig_object_new_specific->ret = &mono_defaults.object_class->byval_arg;
6014         helper_sig_object_new_specific->pinvoke = 1;
6015
6016         /* void* mono_method_compile (MonoMethod*) */
6017         helper_sig_compile = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6018         helper_sig_compile->params [0] = helper_sig_compile->ret = &mono_defaults.int_class->byval_arg;
6019         helper_sig_compile->pinvoke = 1;
6020
6021         /* void* mono_ldvirtfn (MonoObject *, MonoMethod*) */
6022         helper_sig_compile_virt = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
6023         helper_sig_compile_virt->params [0] = &mono_defaults.object_class->byval_arg;
6024         helper_sig_compile_virt->params [1] = helper_sig_compile_virt->ret = &mono_defaults.int_class->byval_arg;
6025         helper_sig_compile_virt->pinvoke = 1;
6026
6027         /* MonoString* mono_ldstr (MonoDomain *domain, MonoImage *image, guint32 str_index) */
6028         helper_sig_ldstr = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
6029         helper_sig_ldstr->params [0] = helper_sig_ldstr->params [1] = &mono_defaults.int_class->byval_arg;
6030         helper_sig_ldstr->params [2] = &mono_defaults.int32_class->byval_arg;
6031         helper_sig_ldstr->ret = &mono_defaults.object_class->byval_arg;
6032         helper_sig_ldstr->pinvoke = 1;
6033
6034         /* MonoDomain *mono_domain_get (void) */
6035         helper_sig_domain_get = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
6036         helper_sig_domain_get->ret = &mono_defaults.int_class->byval_arg;
6037         helper_sig_domain_get->pinvoke = 1;
6038
6039         /* void* stelem_ref (MonoArray *, int index, MonoObject *) */
6040         helper_sig_stelem_ref = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
6041         helper_sig_stelem_ref->params [0] = &mono_defaults.array_class->byval_arg;
6042         helper_sig_stelem_ref->params [1] = &mono_defaults.int32_class->byval_arg;
6043         helper_sig_stelem_ref->params [2] = &mono_defaults.object_class->byval_arg;
6044         helper_sig_stelem_ref->ret = &mono_defaults.void_class->byval_arg;
6045         helper_sig_stelem_ref->pinvoke = 1;
6046
6047         /* void* stelem_ref_check (MonoArray *, MonoObject *) */
6048         helper_sig_stelem_ref_check = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
6049         helper_sig_stelem_ref_check->params [0] = &mono_defaults.array_class->byval_arg;
6050         helper_sig_stelem_ref_check->params [1] = &mono_defaults.object_class->byval_arg;
6051         helper_sig_stelem_ref_check->ret = &mono_defaults.void_class->byval_arg;
6052         helper_sig_stelem_ref_check->pinvoke = 1;
6053
6054         /* long amethod (long, long) */
6055         helper_sig_long_long_long = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
6056         helper_sig_long_long_long->params [0] = helper_sig_long_long_long->params [1] = 
6057                 &mono_defaults.int64_class->byval_arg;
6058         helper_sig_long_long_long->ret = &mono_defaults.int64_class->byval_arg;
6059         helper_sig_long_long_long->pinvoke = 1;
6060
6061         /* object  amethod (intptr) */
6062         helper_sig_obj_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6063         helper_sig_obj_ptr->params [0] = &mono_defaults.int_class->byval_arg;
6064         helper_sig_obj_ptr->ret = &mono_defaults.object_class->byval_arg;
6065         helper_sig_obj_ptr->pinvoke = 1;
6066
6067         /* void amethod (intptr) */
6068         helper_sig_void_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6069         helper_sig_void_ptr->params [0] = &mono_defaults.int_class->byval_arg;
6070         helper_sig_void_ptr->ret = &mono_defaults.void_class->byval_arg;
6071         helper_sig_void_ptr->pinvoke = 1;
6072
6073         /* void amethod (MonoObject *obj) */
6074         helper_sig_void_obj = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6075         helper_sig_void_obj->params [0] = &mono_defaults.object_class->byval_arg;
6076         helper_sig_void_obj->ret = &mono_defaults.void_class->byval_arg;
6077         helper_sig_void_obj->pinvoke = 1;
6078
6079         /* void amethod (MonoObject *obj, void *ptr, int i) */
6080         helper_sig_void_obj_ptr_int = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
6081         helper_sig_void_obj_ptr_int->params [0] = &mono_defaults.object_class->byval_arg;
6082         helper_sig_void_obj_ptr_int->params [1] = &mono_defaults.int_class->byval_arg;
6083         helper_sig_void_obj_ptr_int->params [2] = &mono_defaults.int_class->byval_arg;
6084         helper_sig_void_obj_ptr_int->ret = &mono_defaults.void_class->byval_arg;
6085         helper_sig_void_obj_ptr_int->pinvoke = 1;
6086
6087         /* intptr amethod (void) */
6088         helper_sig_ptr_void = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
6089         helper_sig_ptr_void->ret = &mono_defaults.int_class->byval_arg;
6090         helper_sig_ptr_void->pinvoke = 1;
6091
6092         /* object amethod (void) */
6093         helper_sig_obj_void = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
6094         helper_sig_obj_void->ret = &mono_defaults.object_class->byval_arg;
6095         helper_sig_obj_void->pinvoke = 1;
6096
6097         /* void  amethod (intptr, intptr) */
6098         helper_sig_void_ptr_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
6099         helper_sig_void_ptr_ptr->params [0] = &mono_defaults.int_class->byval_arg;
6100         helper_sig_void_ptr_ptr->params [1] = &mono_defaults.int_class->byval_arg;
6101         helper_sig_void_ptr_ptr->ret = &mono_defaults.void_class->byval_arg;
6102         helper_sig_void_ptr_ptr->pinvoke = 1;
6103
6104         /* void  amethod (intptr, intptr, intptr) */
6105         helper_sig_void_ptr_ptr_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
6106         helper_sig_void_ptr_ptr_ptr->params [0] = &mono_defaults.int_class->byval_arg;
6107         helper_sig_void_ptr_ptr_ptr->params [1] = &mono_defaults.int_class->byval_arg;
6108         helper_sig_void_ptr_ptr_ptr->params [2] = &mono_defaults.int_class->byval_arg;
6109         helper_sig_void_ptr_ptr_ptr->ret = &mono_defaults.void_class->byval_arg;
6110         helper_sig_void_ptr_ptr_ptr->pinvoke = 1;
6111
6112         /* intptr  amethod (intptr, intptr) */
6113         helper_sig_ptr_ptr_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
6114         helper_sig_ptr_ptr_ptr->params [0] = &mono_defaults.int_class->byval_arg;
6115         helper_sig_ptr_ptr_ptr->params [1] = &mono_defaults.int_class->byval_arg;
6116         helper_sig_ptr_ptr_ptr->ret = &mono_defaults.int_class->byval_arg;
6117         helper_sig_ptr_ptr_ptr->pinvoke = 1;
6118
6119         /* IntPtr  amethod (object) */
6120         helper_sig_ptr_obj = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6121         helper_sig_ptr_obj->params [0] = &mono_defaults.object_class->byval_arg;
6122         helper_sig_ptr_obj->ret = &mono_defaults.int_class->byval_arg;
6123         helper_sig_ptr_obj->pinvoke = 1;
6124
6125         /* IntPtr  amethod (object, int) */
6126         helper_sig_ptr_obj_int = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
6127         helper_sig_ptr_obj_int->params [0] = &mono_defaults.object_class->byval_arg;
6128         helper_sig_ptr_obj_int->params [1] = &mono_defaults.int_class->byval_arg;
6129         helper_sig_ptr_obj_int->ret = &mono_defaults.int_class->byval_arg;
6130         helper_sig_ptr_obj_int->pinvoke = 1;
6131
6132         /* IntPtr  amethod (int) */
6133         helper_sig_ptr_int = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6134         helper_sig_ptr_int->params [0] = &mono_defaults.int32_class->byval_arg;
6135         helper_sig_ptr_int->ret = &mono_defaults.int_class->byval_arg;
6136         helper_sig_ptr_int->pinvoke = 1;
6137
6138         /* long amethod (long, guint32) */
6139         helper_sig_long_long_int = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
6140         helper_sig_long_long_int->params [0] = &mono_defaults.int64_class->byval_arg;
6141         helper_sig_long_long_int->params [1] = &mono_defaults.int32_class->byval_arg;
6142         helper_sig_long_long_int->ret = &mono_defaults.int64_class->byval_arg;
6143         helper_sig_long_long_int->pinvoke = 1;
6144
6145         /* ulong amethod (double) */
6146         helper_sig_ulong_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6147         helper_sig_ulong_double->params [0] = &mono_defaults.double_class->byval_arg;
6148         helper_sig_ulong_double->ret = &mono_defaults.uint64_class->byval_arg;
6149         helper_sig_ulong_double->pinvoke = 1;
6150
6151         /* long amethod (double) */
6152         helper_sig_long_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6153         helper_sig_long_double->params [0] = &mono_defaults.double_class->byval_arg;
6154         helper_sig_long_double->ret = &mono_defaults.int64_class->byval_arg;
6155         helper_sig_long_double->pinvoke = 1;
6156
6157         /* double amethod (long) */
6158         helper_sig_double_long = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6159         helper_sig_double_long->params [0] = &mono_defaults.int64_class->byval_arg;
6160         helper_sig_double_long->ret = &mono_defaults.double_class->byval_arg;
6161         helper_sig_double_long->pinvoke = 1;
6162
6163         /* double amethod (int) */
6164         helper_sig_double_int = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6165         helper_sig_double_int->params [0] = &mono_defaults.int32_class->byval_arg;
6166         helper_sig_double_int->ret = &mono_defaults.double_class->byval_arg;
6167         helper_sig_double_int->pinvoke = 1;
6168
6169         /* float amethod (long) */
6170         helper_sig_float_long = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6171         helper_sig_float_long->params [0] = &mono_defaults.int64_class->byval_arg;
6172         helper_sig_float_long->ret = &mono_defaults.single_class->byval_arg;
6173         helper_sig_float_long->pinvoke = 1;
6174
6175         /* double amethod (double, double) */
6176         helper_sig_double_double_double = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
6177         helper_sig_double_double_double->params [0] = &mono_defaults.double_class->byval_arg;
6178         helper_sig_double_double_double->params [1] = &mono_defaults.double_class->byval_arg;
6179         helper_sig_double_double_double->ret = &mono_defaults.double_class->byval_arg;
6180         helper_sig_double_double_double->pinvoke = 1;
6181
6182         /* uint amethod (double) */
6183         helper_sig_uint_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6184         helper_sig_uint_double->params [0] = &mono_defaults.double_class->byval_arg;
6185         helper_sig_uint_double->ret = &mono_defaults.uint32_class->byval_arg;
6186         helper_sig_uint_double->pinvoke = 1;
6187
6188         /* int amethod (double) */
6189         helper_sig_int_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
6190         helper_sig_int_double->params [0] = &mono_defaults.double_class->byval_arg;
6191         helper_sig_int_double->ret = &mono_defaults.int32_class->byval_arg;
6192         helper_sig_int_double->pinvoke = 1;
6193
6194         /* void  initobj (intptr, int size) */
6195         helper_sig_initobj = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
6196         helper_sig_initobj->params [0] = &mono_defaults.int_class->byval_arg;
6197         helper_sig_initobj->params [1] = &mono_defaults.int32_class->byval_arg;
6198         helper_sig_initobj->ret = &mono_defaults.void_class->byval_arg;
6199         helper_sig_initobj->pinvoke = 1;
6200
6201         /* void  memcpy (intptr, intptr, int size) */
6202         helper_sig_memcpy = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
6203         helper_sig_memcpy->params [0] = &mono_defaults.int_class->byval_arg;
6204         helper_sig_memcpy->params [1] = &mono_defaults.int_class->byval_arg;
6205         helper_sig_memcpy->params [2] = &mono_defaults.int32_class->byval_arg;
6206         helper_sig_memcpy->ret = &mono_defaults.void_class->byval_arg;
6207         helper_sig_memcpy->pinvoke = 1;
6208
6209         /* void  memset (intptr, int val, int size) */
6210         helper_sig_memset = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
6211         helper_sig_memset->params [0] = &mono_defaults.int_class->byval_arg;
6212         helper_sig_memset->params [1] = &mono_defaults.int32_class->byval_arg;
6213         helper_sig_memset->params [2] = &mono_defaults.int32_class->byval_arg;
6214         helper_sig_memset->ret = &mono_defaults.void_class->byval_arg;
6215         helper_sig_memset->pinvoke = 1;
6216
6217         helper_sig_class_init_trampoline = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
6218         helper_sig_class_init_trampoline->ret = &mono_defaults.void_class->byval_arg;
6219         helper_sig_class_init_trampoline->pinvoke = 1;  
6220 }
6221
6222 static GHashTable *jit_icall_hash_name = NULL;
6223 static GHashTable *jit_icall_hash_addr = NULL;
6224
6225 MonoJitICallInfo *
6226 mono_find_jit_icall_by_name (const char *name)
6227 {
6228         MonoJitICallInfo *info;
6229         g_assert (jit_icall_hash_name);
6230
6231         //printf ("lookup addr %s %p\n", name, g_hash_table_lookup (jit_icall_hash_name, name));
6232         EnterCriticalSection (&trampoline_hash_mutex);
6233         info = g_hash_table_lookup (jit_icall_hash_name, name);
6234         LeaveCriticalSection (&trampoline_hash_mutex);
6235         return info;
6236 }
6237
6238 MonoJitICallInfo *
6239 mono_find_jit_icall_by_addr (gconstpointer addr)
6240 {
6241         MonoJitICallInfo *info;
6242         g_assert (jit_icall_hash_addr);
6243
6244         EnterCriticalSection (&trampoline_hash_mutex);
6245         info = g_hash_table_lookup (jit_icall_hash_addr, (gpointer)addr);
6246         LeaveCriticalSection (&trampoline_hash_mutex);
6247
6248         return info;
6249 }
6250
6251 gconstpointer
6252 mono_icall_get_wrapper (MonoJitICallInfo* callinfo)
6253 {
6254         char *name;
6255         MonoMethod *wrapper;
6256         gconstpointer code;
6257         
6258         if (callinfo->wrapper)
6259                 return callinfo->wrapper;
6260         
6261         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
6262         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func);
6263         /* Must be domain neutral since there is only one copy */
6264         code = mono_jit_compile_method_with_opt (wrapper, default_opt | MONO_OPT_SHARED);
6265
6266         EnterCriticalSection (&trampoline_hash_mutex);
6267         if (!callinfo->wrapper) {
6268                 callinfo->wrapper = code;
6269                 g_hash_table_insert (jit_icall_hash_addr, (gpointer)callinfo->wrapper, callinfo);
6270         }
6271         LeaveCriticalSection (&trampoline_hash_mutex);
6272
6273         g_free (name);
6274         return callinfo->wrapper;
6275 }
6276
6277 MonoJitICallInfo *
6278 mono_register_jit_icall (gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean is_save)
6279 {
6280         MonoJitICallInfo *info;
6281         
6282         g_assert (func);
6283         g_assert (name);
6284
6285         EnterCriticalSection (&trampoline_hash_mutex);
6286
6287         if (!jit_icall_hash_name) {
6288                 jit_icall_hash_name = g_hash_table_new (g_str_hash, g_str_equal);
6289                 jit_icall_hash_addr = g_hash_table_new (NULL, NULL);
6290         }
6291
6292         if (g_hash_table_lookup (jit_icall_hash_name, name)) {
6293                 g_warning ("jit icall already defined \"%s\"\n", name);
6294                 g_assert_not_reached ();
6295         }
6296
6297         info = g_new (MonoJitICallInfo, 1);
6298         
6299         info->name = name;
6300         info->func = func;
6301         info->sig = sig;
6302
6303         if (is_save
6304 #ifdef MONO_USE_EXC_TABLES
6305             || mono_arch_has_unwind_info (func)
6306 #endif
6307             ) {
6308                 info->wrapper = func;
6309         } else {
6310                 info->wrapper = NULL;
6311         }
6312
6313         g_hash_table_insert (jit_icall_hash_name, (gpointer)info->name, info);
6314         g_hash_table_insert (jit_icall_hash_addr, (gpointer)func, info);
6315
6316         LeaveCriticalSection (&trampoline_hash_mutex);
6317         return info;
6318 }
6319
6320 gpointer
6321 mono_create_class_init_trampoline (MonoVTable *vtable)
6322 {
6323         gpointer code;
6324
6325         /* previously created trampoline code */
6326         mono_domain_lock (vtable->domain);
6327         code = 
6328                 mono_g_hash_table_lookup (vtable->domain->class_init_trampoline_hash,
6329                                                                   vtable);
6330         mono_domain_unlock (vtable->domain);
6331         if (code)
6332                 return code;
6333
6334         code = mono_arch_create_class_init_trampoline (vtable);
6335
6336         /* store trampoline address */
6337         mono_domain_lock (vtable->domain);
6338         mono_g_hash_table_insert (vtable->domain->class_init_trampoline_hash,
6339                                                           vtable, code);
6340         mono_domain_unlock (vtable->domain);
6341
6342         EnterCriticalSection (&trampoline_hash_mutex);
6343         if (!class_init_hash_addr)
6344                 class_init_hash_addr = g_hash_table_new (NULL, NULL);
6345         g_hash_table_insert (class_init_hash_addr, code, vtable);
6346         LeaveCriticalSection (&trampoline_hash_mutex);
6347
6348         return code;
6349 }
6350
6351 gpointer
6352 mono_create_jump_trampoline (MonoDomain *domain, MonoMethod *method, 
6353                                                          gboolean add_sync_wrapper)
6354 {
6355         MonoJitInfo *ji;
6356         gpointer code;
6357
6358         if (add_sync_wrapper && method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
6359                 return mono_create_jump_trampoline (domain, mono_marshal_get_synchronized_wrapper (method), FALSE);
6360
6361         code = mono_jit_find_compiled_method (domain, method);
6362         if (code)
6363                 return code;
6364
6365         EnterCriticalSection (&trampoline_hash_mutex);
6366
6367         if (jump_trampoline_hash) {
6368                 code = g_hash_table_lookup (jump_trampoline_hash, method);
6369                 if (code) {
6370                         LeaveCriticalSection (&trampoline_hash_mutex);
6371                         return code;
6372                 }
6373         }
6374
6375         ji = mono_arch_create_jump_trampoline (method);
6376
6377         /*
6378          * mono_delegate_ctor needs to find the method metadata from the 
6379          * trampoline address, so we save it here.
6380          */
6381
6382         mono_jit_info_table_add (mono_root_domain, ji);
6383
6384         if (!jump_trampoline_hash)
6385                 jump_trampoline_hash = g_hash_table_new (NULL, NULL);
6386         g_hash_table_insert (jump_trampoline_hash, method, ji->code_start);
6387
6388         LeaveCriticalSection (&trampoline_hash_mutex);
6389
6390         return ji->code_start;
6391 }
6392
6393 MonoVTable*
6394 mono_find_class_init_trampoline_by_addr (gconstpointer addr)
6395 {
6396         MonoVTable *res;
6397
6398         EnterCriticalSection (&trampoline_hash_mutex);
6399         if (class_init_hash_addr)
6400                 res = g_hash_table_lookup (class_init_hash_addr, addr);
6401         else
6402                 res = NULL;
6403         LeaveCriticalSection (&trampoline_hash_mutex);
6404         return res;
6405 }
6406
6407 void
6408 mono_register_opcode_emulation (int opcode, const char *name, MonoMethodSignature *sig, gpointer func, gboolean no_throw)
6409 {
6410         MonoJitICallInfo *info;
6411
6412         if (!emul_opcode_map)
6413                 emul_opcode_map = g_new0 (MonoJitICallInfo*, OP_LAST + 1);
6414
6415         g_assert (!sig->hasthis);
6416         g_assert (sig->param_count < 3);
6417
6418         info = mono_register_jit_icall (func, name, sig, no_throw);
6419
6420         emul_opcode_map [opcode] = info;
6421 }
6422
6423 static void
6424 decompose_foreach (MonoInst *tree, gpointer data) 
6425 {
6426         static MonoJitICallInfo *newarr_info = NULL;
6427         static MonoJitICallInfo *newarr_specific_info = NULL;
6428         MonoJitICallInfo *info;
6429         int i;
6430
6431         switch (tree->opcode) {
6432         case CEE_NEWARR: {
6433                 MonoCompile *cfg = data;
6434                 MonoInst *iargs [3];
6435
6436                 if (!newarr_info) {
6437                         newarr_info = mono_find_jit_icall_by_addr (mono_array_new);
6438                         g_assert (newarr_info);
6439                         newarr_specific_info = mono_find_jit_icall_by_addr (mono_array_new_specific);
6440                         g_assert (newarr_specific_info);
6441                 }
6442
6443                 if (cfg->opt & MONO_OPT_SHARED) {
6444                         NEW_DOMAINCONST (cfg, iargs [0]);
6445                         NEW_CLASSCONST (cfg, iargs [1], tree->inst_newa_class);
6446                         iargs [2] = tree->inst_newa_len;
6447
6448                         info = newarr_info;
6449                 }
6450                 else {
6451                         MonoVTable *vtable = mono_class_vtable (cfg->domain, mono_array_class_get (tree->inst_newa_class, 1));
6452
6453                         NEW_VTABLECONST (cfg, iargs [0], vtable);
6454                         iargs [1] = tree->inst_newa_len;
6455
6456                         info = newarr_specific_info;
6457                 }
6458
6459                 mono_emulate_opcode (cfg, tree, iargs, info);
6460
6461                 /* Need to decompose arguments after the the opcode is decomposed */
6462                 for (i = 0; i < info->sig->param_count; ++i)
6463                         dec_foreach (iargs [i], cfg);
6464                 break;
6465         }
6466
6467         default:
6468                 break;
6469         }
6470 }
6471
6472 void
6473 mono_inst_foreach (MonoInst *tree, MonoInstFunc func, gpointer data) {
6474
6475         switch (mono_burg_arity [tree->opcode]) {
6476         case 0: break;
6477         case 1: 
6478                 mono_inst_foreach (tree->inst_left, func, data);
6479                 break;
6480         case 2: 
6481                 mono_inst_foreach (tree->inst_left, func, data);
6482                 mono_inst_foreach (tree->inst_right, func, data);
6483                 break;
6484         default:
6485                 g_assert_not_reached ();
6486         }
6487         func (tree, data);
6488 }
6489
6490 G_GNUC_UNUSED
6491 static void
6492 mono_print_bb_code (MonoBasicBlock *bb) {
6493         if (bb->code) {
6494                 MonoInst *c = bb->code;
6495                 while (c) {
6496                         mono_print_tree (c);
6497                         g_print ("\n");
6498                         c = c->next;
6499                 }
6500         }
6501 }
6502
6503 static void
6504 print_dfn (MonoCompile *cfg) {
6505         int i, j;
6506         char *code;
6507         MonoBasicBlock *bb;
6508
6509         g_print ("IR code for method %s\n", mono_method_full_name (cfg->method, TRUE));
6510
6511         for (i = 0; i < cfg->num_bblocks; ++i) {
6512                 bb = cfg->bblocks [i];
6513                 if (bb->cil_code) {
6514                         char* code1, *code2;
6515                         code1 = mono_disasm_code_one (NULL, cfg->method, bb->cil_code, NULL);
6516                         if (bb->last_ins->cil_code)
6517                                 code2 = mono_disasm_code_one (NULL, cfg->method, bb->last_ins->cil_code, NULL);
6518                         else
6519                                 code2 = g_strdup ("");
6520
6521                         code1 [strlen (code1) - 1] = 0;
6522                         code = g_strdup_printf ("%s -> %s", code1, code2);
6523                         g_free (code1);
6524                         g_free (code2);
6525                 } else
6526                         code = g_strdup ("\n");
6527                 g_print ("\nBB%d DFN%d (len: %d): %s", bb->block_num, i, bb->cil_length, code);
6528                 if (bb->code) {
6529                         MonoInst *c = bb->code;
6530                         while (c) {
6531                                 mono_print_tree (c);
6532                                 g_print ("\n");
6533                                 c = c->next;
6534                         }
6535                 } else {
6536
6537                 }
6538
6539                 g_print ("\tprev:");
6540                 for (j = 0; j < bb->in_count; ++j) {
6541                         g_print (" BB%d", bb->in_bb [j]->block_num);
6542                 }
6543                 g_print ("\t\tsucc:");
6544                 for (j = 0; j < bb->out_count; ++j) {
6545                         g_print (" BB%d", bb->out_bb [j]->block_num);
6546                 }
6547                 g_print ("\n\tidom: BB%d\n", bb->idom? bb->idom->block_num: -1);
6548
6549                 if (bb->idom)
6550                         g_assert (mono_bitset_test_fast (bb->dominators, bb->idom->dfn));
6551
6552                 if (bb->dominators)
6553                         mono_blockset_print (cfg, bb->dominators, "\tdominators", bb->idom? bb->idom->dfn: -1);
6554                 if (bb->dfrontier)
6555                         mono_blockset_print (cfg, bb->dfrontier, "\tdfrontier", -1);
6556                 g_free (code);
6557         }
6558
6559         g_print ("\n");
6560 }
6561
6562 void
6563 mono_bblock_add_inst (MonoBasicBlock *bb, MonoInst *inst)
6564 {
6565         inst->next = NULL;
6566         if (bb->last_ins) {
6567                 g_assert (bb->code);
6568                 bb->last_ins->next = inst;
6569                 bb->last_ins = inst;
6570         } else {
6571                 bb->last_ins = bb->code = inst;
6572         }
6573 }
6574
6575 void
6576 mono_destroy_compile (MonoCompile *cfg)
6577 {
6578         //mono_mempool_stats (cfg->mempool);
6579         g_hash_table_destroy (cfg->bb_hash);
6580         mono_free_loop_info (cfg);
6581         if (cfg->rs)
6582                 mono_regstate_free (cfg->rs);
6583         if (cfg->spvars)
6584                 g_hash_table_destroy (cfg->spvars);
6585         mono_mempool_destroy (cfg->mempool);
6586         g_list_free (cfg->ldstr_list);
6587
6588         g_free (cfg->varinfo);
6589         g_free (cfg->vars);
6590         g_free (cfg);
6591 }
6592
6593 MonoLMF **
6594 mono_get_lmf_addr (void)
6595 {
6596         MonoJitTlsData *jit_tls;
6597
6598         if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
6599                 return &jit_tls->lmf;
6600
6601         g_assert_not_reached ();
6602         return NULL;
6603 }
6604
6605 /**
6606  * mono_thread_abort:
6607  * @obj: exception object
6608  *
6609  * abort the thread, print exception information and stack trace
6610  */
6611 static void
6612 mono_thread_abort (MonoObject *obj)
6613 {
6614         /* MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id); */
6615         
6616         /* handle_remove should be eventually called for this thread, too
6617         g_free (jit_tls);*/
6618
6619         ExitThread (-1);
6620 }
6621
6622 static void*
6623 setup_jit_tls_data (gpointer stack_start, gpointer abort_func)
6624 {
6625         MonoJitTlsData *jit_tls;
6626         MonoLMF *lmf;
6627
6628         jit_tls = TlsGetValue (mono_jit_tls_id);
6629         if (jit_tls)
6630                 return jit_tls;
6631
6632         jit_tls = g_new0 (MonoJitTlsData, 1);
6633
6634         TlsSetValue (mono_jit_tls_id, jit_tls);
6635
6636         jit_tls->abort_func = abort_func;
6637         jit_tls->end_of_stack = stack_start;
6638
6639         lmf = g_new0 (MonoLMF, 1);
6640         lmf->ebp = -1;
6641
6642         jit_tls->lmf = jit_tls->first_lmf = lmf;
6643
6644         mono_arch_setup_jit_tls_data (jit_tls);
6645
6646         return jit_tls;
6647 }
6648
6649 static void
6650 mono_thread_start_cb (guint32 tid, gpointer stack_start, gpointer func)
6651 {
6652         MonoThread *thread;
6653         void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort);
6654         thread = mono_thread_current ();
6655         if (thread)
6656                 thread->jit_data = jit_tls;
6657 }
6658
6659 void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
6660
6661 static void
6662 mono_thread_abort_dummy (MonoObject *obj)
6663 {
6664   if (mono_thread_attach_aborted_cb)
6665     mono_thread_attach_aborted_cb (obj);
6666   else
6667     mono_thread_abort (obj);
6668 }
6669
6670 static void
6671 mono_thread_attach_cb (guint32 tid, gpointer stack_start)
6672 {
6673         MonoThread *thread;
6674         void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort_dummy);
6675         thread = mono_thread_current ();
6676         if (thread)
6677                 thread->jit_data = jit_tls;
6678 }
6679
6680 static void
6681 mini_thread_cleanup (MonoThread *thread)
6682 {
6683         MonoJitTlsData *jit_tls = thread->jit_data;
6684
6685         if (jit_tls) {
6686                 mono_arch_free_jit_tls_data (jit_tls);
6687                 g_free (jit_tls->first_lmf);
6688                 g_free (jit_tls);
6689                 thread->jit_data = NULL;
6690         }
6691 }
6692
6693 void
6694 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
6695 {
6696         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
6697
6698         ji->ip.i = ip;
6699         ji->type = type;
6700         ji->data.target = target;
6701         ji->next = cfg->patch_info;
6702
6703         cfg->patch_info = ji;
6704 }
6705
6706 void
6707 mono_remove_patch_info (MonoCompile *cfg, int ip)
6708 {
6709         MonoJumpInfo **ji = &cfg->patch_info;
6710
6711         while (*ji) {
6712                 if ((*ji)->ip.i == ip)
6713                         *ji = (*ji)->next;
6714                 else
6715                         ji = &((*ji)->next);
6716         }
6717 }
6718
6719 gpointer
6720 mono_resolve_patch_target (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors)
6721 {
6722         unsigned char *ip = patch_info->ip.i + code;
6723         gconstpointer target = NULL;
6724
6725         switch (patch_info->type) {
6726         case MONO_PATCH_INFO_BB:
6727                 target = patch_info->data.bb->native_offset + code;
6728                 break;
6729         case MONO_PATCH_INFO_ABS:
6730                 target = patch_info->data.target;
6731                 break;
6732         case MONO_PATCH_INFO_LABEL:
6733                 target = patch_info->data.inst->inst_c0 + code;
6734                 break;
6735         case MONO_PATCH_INFO_IP:
6736                 target = ip;
6737                 break;
6738         case MONO_PATCH_INFO_METHOD_REL:
6739                 target = code + patch_info->data.offset;
6740                 break;
6741         case MONO_PATCH_INFO_INTERNAL_METHOD: {
6742                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
6743                 if (!mi) {
6744                         g_warning ("unknown MONO_PATCH_INFO_INTERNAL_METHOD %s", patch_info->data.name);
6745                         g_assert_not_reached ();
6746                 }
6747                 target = mono_icall_get_wrapper (mi);
6748                 break;
6749         }
6750         case MONO_PATCH_INFO_METHOD_JUMP: {
6751                 GSList *list;
6752
6753                 /* get the trampoline to the method from the domain */
6754                 target = mono_create_jump_trampoline (domain, patch_info->data.method, TRUE);
6755                 if (!domain->jump_target_hash)
6756                         domain->jump_target_hash = g_hash_table_new (NULL, NULL);
6757                 list = g_hash_table_lookup (domain->jump_target_hash, patch_info->data.method);
6758                 list = g_slist_prepend (list, ip);
6759                 g_hash_table_insert (domain->jump_target_hash, patch_info->data.method, list);
6760                 break;
6761         }
6762         case MONO_PATCH_INFO_METHOD:
6763                 if (patch_info->data.method == method) {
6764                         target = code;
6765                 } else
6766                         /* get the trampoline to the method from the domain */
6767                         target = mono_arch_create_jit_trampoline (patch_info->data.method);
6768                 break;
6769         case MONO_PATCH_INFO_SWITCH: {
6770                 gpointer *jump_table;
6771                 int i;
6772         
6773                 mono_domain_lock (domain);
6774                 jump_table = mono_code_manager_reserve (domain->code_mp, sizeof (gpointer) * patch_info->table_size);
6775                 mono_domain_unlock (domain);
6776
6777                 for (i = 0; i < patch_info->table_size; i++) {
6778                         jump_table [i] = code + (int)patch_info->data.table [i];
6779                 }
6780                 target = jump_table;
6781                 break;
6782         }
6783         case MONO_PATCH_INFO_METHODCONST:
6784         case MONO_PATCH_INFO_CLASS:
6785         case MONO_PATCH_INFO_IMAGE:
6786         case MONO_PATCH_INFO_FIELD:
6787                 target = patch_info->data.target;
6788                 break;
6789         case MONO_PATCH_INFO_IID:
6790                 mono_class_init (patch_info->data.klass);
6791                 target = (gpointer)patch_info->data.klass->interface_id;
6792                 break;
6793         case MONO_PATCH_INFO_VTABLE:
6794                 target = mono_class_vtable (domain, patch_info->data.klass);
6795                 break;
6796         case MONO_PATCH_INFO_CLASS_INIT:
6797                 target = mono_create_class_init_trampoline (mono_class_vtable (domain, patch_info->data.klass));
6798                 break;
6799         case MONO_PATCH_INFO_SFLDA: {
6800                 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.field->parent);
6801                 if (!vtable->initialized && !(vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) && mono_class_needs_cctor_run (vtable->klass, method))
6802                         /* Done by the generated code */
6803                         ;
6804                 else {
6805                         if (run_cctors)
6806                                 mono_runtime_class_init (vtable);
6807                 }
6808                 target = (char*)vtable->data + patch_info->data.field->offset;
6809                 break;
6810         }
6811         case MONO_PATCH_INFO_R4:
6812         case MONO_PATCH_INFO_R8:
6813                 target = patch_info->data.target;
6814                 break;
6815         case MONO_PATCH_INFO_EXC_NAME:
6816                 target = patch_info->data.name;
6817                 break;
6818         case MONO_PATCH_INFO_LDSTR:
6819                 target =
6820                         mono_ldstr (domain, patch_info->data.token->image, 
6821                                                 mono_metadata_token_index (patch_info->data.token->token));
6822                 break;
6823         case MONO_PATCH_INFO_TYPE_FROM_HANDLE: {
6824                 gpointer handle;
6825                 MonoClass *handle_class;
6826
6827                 handle = mono_ldtoken (patch_info->data.token->image, 
6828                                        patch_info->data.token->token, &handle_class, NULL);
6829                 mono_class_init (handle_class);
6830                 mono_class_init (mono_class_from_mono_type (handle));
6831
6832                 target =
6833                         mono_type_get_object (domain, handle);
6834                 break;
6835         }
6836         case MONO_PATCH_INFO_LDTOKEN: {
6837                 gpointer handle;
6838                 MonoClass *handle_class;
6839                 
6840                 handle = mono_ldtoken (patch_info->data.token->image,
6841                                        patch_info->data.token->token, &handle_class, NULL);
6842                 mono_class_init (handle_class);
6843                 
6844                 target = handle;
6845                 break;
6846         }
6847         case MONO_PATCH_INFO_BB_OVF:
6848         case MONO_PATCH_INFO_EXC_OVF:
6849                 break;
6850         default:
6851                 g_assert_not_reached ();
6852         }
6853
6854         return (gpointer)target;
6855 }
6856
6857 static void
6858 dec_foreach (MonoInst *tree, MonoCompile *cfg) {
6859         MonoJitICallInfo *info;
6860
6861         decompose_foreach (tree, cfg);
6862
6863         switch (mono_burg_arity [tree->opcode]) {
6864         case 0: break;
6865         case 1: 
6866                 dec_foreach (tree->inst_left, cfg);
6867
6868                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
6869                         MonoInst *iargs [2];
6870                 
6871                         iargs [0] = tree->inst_left;
6872
6873                         mono_emulate_opcode (cfg, tree, iargs, info);
6874                         return;
6875                 }
6876
6877                 break;
6878         case 2:
6879 #ifdef MONO_ARCH_BIGMUL_INTRINS
6880                 if (tree->opcode == OP_LMUL
6881                                 && (cfg->opt & MONO_OPT_INTRINS)
6882                                 && (tree->inst_left->opcode == CEE_CONV_I8 
6883                                         || tree->inst_left->opcode == CEE_CONV_U8)
6884                                 && tree->inst_left->inst_left->type == STACK_I4
6885                                 && (tree->inst_right->opcode == CEE_CONV_I8 
6886                                         || tree->inst_right->opcode == CEE_CONV_U8)
6887                                 && tree->inst_right->inst_left->type == STACK_I4) {
6888                         tree->opcode = (tree->inst_left->opcode == CEE_CONV_I8 ? OP_BIGMUL: OP_BIGMUL_UN);
6889                         tree->inst_left = tree->inst_left->inst_left;
6890                         tree->inst_right = tree->inst_right->inst_left;
6891                         dec_foreach (tree, cfg);
6892                 } else 
6893 #endif
6894                         if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
6895                         MonoInst *iargs [2];
6896                 
6897                         iargs [0] = tree->inst_i0;
6898                         iargs [1] = tree->inst_i1;
6899                 
6900                         mono_emulate_opcode (cfg, tree, iargs, info);
6901
6902                         dec_foreach (iargs [0], cfg);
6903                         dec_foreach (iargs [1], cfg);
6904                         return;
6905                 } else {
6906                         dec_foreach (tree->inst_left, cfg);
6907                         dec_foreach (tree->inst_right, cfg);
6908                 }
6909                 break;
6910         default:
6911                 g_assert_not_reached ();
6912         }
6913 }
6914
6915 static void
6916 decompose_pass (MonoCompile *cfg) {
6917         MonoBasicBlock *bb;
6918
6919         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
6920                 MonoInst *tree;
6921                 cfg->cbb = bb;
6922                 cfg->prev_ins = NULL;
6923                 for (tree = cfg->cbb->code; tree; tree = tree->next) {
6924                         dec_foreach (tree, cfg);
6925                         cfg->prev_ins = tree;
6926                 }
6927         }
6928 }
6929
6930 static void
6931 nullify_basic_block (MonoBasicBlock *bb) 
6932 {
6933         bb->in_count = 0;
6934         bb->out_count = 0;
6935         bb->in_bb = NULL;
6936         bb->out_bb = NULL;
6937         bb->next_bb = NULL;
6938         bb->code = bb->last_ins = NULL;
6939         bb->cil_code = NULL;
6940 }
6941
6942 static void 
6943 replace_out_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
6944 {
6945         int i;
6946
6947         for (i = 0; i < bb->out_count; i++) {
6948                 MonoBasicBlock *ob = bb->out_bb [i];
6949                 if (ob == orig) {
6950                         if (!repl) {
6951                                 if (bb->out_count > 1) {
6952                                         bb->out_bb [i] = bb->out_bb [bb->out_count - 1];
6953                                 }
6954                                 bb->out_count--;
6955                         } else {
6956                                 bb->out_bb [i] = repl;
6957                         }
6958                 }
6959         }
6960 }
6961
6962 static void 
6963 replace_in_block (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl)
6964 {
6965         int i;
6966
6967         for (i = 0; i < bb->in_count; i++) {
6968                 MonoBasicBlock *ib = bb->in_bb [i];
6969                 if (ib == orig) {
6970                         if (!repl) {
6971                                 if (bb->in_count > 1) {
6972                                         bb->in_bb [i] = bb->in_bb [bb->in_count - 1];
6973                                 }
6974                                 bb->in_count--;
6975                         } else {
6976                                 bb->in_bb [i] = repl;
6977                         }
6978                 }
6979         }
6980 }
6981
6982 static void 
6983 replace_basic_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
6984 {
6985         int i, j;
6986
6987         for (i = 0; i < bb->out_count; i++) {
6988                 MonoBasicBlock *ob = bb->out_bb [i];
6989                 for (j = 0; j < ob->in_count; j++) {
6990                         if (ob->in_bb [j] == orig) {
6991                                 ob->in_bb [j] = repl;
6992                         }
6993                 }
6994         }
6995
6996 }
6997
6998
6999 static void
7000 merge_basic_blocks (MonoBasicBlock *bb, MonoBasicBlock *bbn) 
7001 {
7002         bb->out_count = bbn->out_count;
7003         bb->out_bb = bbn->out_bb;
7004
7005         replace_basic_block (bb, bbn, bb);
7006
7007         if (bb->last_ins) {
7008                 if (bbn->code) {
7009                         bb->last_ins->next = bbn->code;
7010                         bb->last_ins = bbn->last_ins;
7011                 }
7012         } else {
7013                 bb->code = bbn->code;
7014                 bb->last_ins = bbn->last_ins;
7015         }
7016         bb->next_bb = bbn->next_bb;
7017         nullify_basic_block (bbn);
7018 }
7019
7020 /*
7021  * Optimizes the branches on the Control Flow Graph
7022  *
7023  */
7024 static void
7025 optimize_branches (MonoCompile *cfg)
7026 {
7027         int i, changed = FALSE;
7028         MonoBasicBlock *bb, *bbn;
7029         guint32 niterations;
7030
7031         /*
7032          * Some crazy loops could cause the code below to go into an infinite
7033          * loop, see bug #53003 for an example. To prevent this, we put an upper
7034          * bound on the number of iterations.
7035          */
7036         niterations = 1000;
7037         do {
7038                 changed = FALSE;
7039                 niterations --;
7040
7041                 /* we skip the entry block (exit is handled specially instead ) */
7042                 for (bb = cfg->bb_entry->next_bb; bb; bb = bb->next_bb) {
7043
7044                         /* dont touch code inside exception clauses */
7045                         if (bb->region != -1)
7046                                 continue;
7047
7048                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
7049                                 if (cfg->verbose_level > 2)
7050                                         g_print ("nullify block triggered %d\n", bbn->block_num);
7051
7052                                 bb->next_bb = bbn->next_bb;
7053
7054                                 for (i = 0; i < bbn->out_count; i++)
7055                                         replace_in_block (bbn->out_bb [i], bbn, NULL);
7056
7057                                 nullify_basic_block (bbn);                      
7058                                 changed = TRUE;
7059                         }
7060
7061                         if (bb->out_count == 1) {
7062                                 bbn = bb->out_bb [0];
7063
7064                                 /* conditional branches where true and false targets are the same can be also replaced with CEE_BR */
7065                                 if (bb->last_ins && MONO_IS_COND_BRANCH (bb->last_ins->opcode)) {
7066                                         bb->last_ins->opcode = CEE_BR;
7067                                         bb->last_ins->inst_target_bb = bb->last_ins->inst_true_bb;
7068                                         changed = TRUE;
7069                                         if (cfg->verbose_level > 2)
7070                                                 g_print ("cond branch removal triggered in %d %d\n", bb->block_num, bb->out_count);
7071                                 }
7072
7073                                 if (bb->region == bbn->region && bb->next_bb == bbn) {
7074                                         /* the block are in sequence anyway ... */
7075
7076                                         /* branches to the following block can be removed */
7077                                         if (bb->last_ins && bb->last_ins->opcode == CEE_BR) {
7078                                                 bb->last_ins->opcode = CEE_NOP;
7079                                                 changed = TRUE;
7080                                                 if (cfg->verbose_level > 2)
7081                                                         g_print ("br removal triggered %d -> %d\n", bb->block_num, bbn->block_num);
7082                                         }
7083
7084                                         if (bbn->in_count == 1) {
7085
7086                                                 if (bbn != cfg->bb_exit) {
7087                                                         if (cfg->verbose_level > 2)
7088                                                                 g_print ("block merge triggered %d -> %d\n", bb->block_num, bbn->block_num);
7089                                                         merge_basic_blocks (bb, bbn);
7090                                                         changed = TRUE;
7091                                                 }
7092
7093                                                 //mono_print_bb_code (bb);
7094                                         }
7095                                 }                               
7096                         }
7097                 }
7098         } while (changed && (niterations > 0));
7099
7100         niterations = 1000;
7101         do {
7102                 changed = FALSE;
7103                 niterations --;
7104
7105                 /* we skip the entry block (exit is handled specially instead ) */
7106                 for (bb = cfg->bb_entry->next_bb; bb; bb = bb->next_bb) {
7107
7108                         /* dont touch code inside exception clauses */
7109                         if (bb->region != -1)
7110                                 continue;
7111
7112                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
7113                                 if (cfg->verbose_level > 2) {
7114                                         g_print ("nullify block triggered %d\n", bbn->block_num);
7115                                 }
7116                                 bb->next_bb = bbn->next_bb;
7117
7118                                 for (i = 0; i < bbn->out_count; i++)
7119                                         replace_in_block (bbn->out_bb [i], bbn, NULL);
7120
7121                                 nullify_basic_block (bbn);                      
7122                                 changed = TRUE;
7123                                 break;
7124                         }
7125
7126
7127                         if (bb->out_count == 1) {
7128                                 bbn = bb->out_bb [0];
7129
7130                                 if (bb->last_ins && bb->last_ins->opcode == CEE_BR) {
7131                                         bbn = bb->last_ins->inst_target_bb;
7132                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR &&
7133                                             bbn->code->inst_target_bb->region == bb->region) {
7134                                                 
7135                                                 if (cfg->verbose_level > 2)
7136                                                         g_print ("in %s branch to branch triggered %d -> %d\n", cfg->method->name, 
7137                                                                  bb->block_num, bbn->block_num);
7138                                                 
7139                                                 replace_basic_block (bb, bb->out_bb [0], bbn->code->inst_target_bb);
7140                                                 bb->last_ins->inst_target_bb = bbn->code->inst_target_bb;
7141                                                 changed = TRUE;
7142                                                 break;
7143                                         }
7144                                 }
7145                         } else if (bb->out_count == 2) {
7146                                 if (bb->last_ins && MONO_IS_COND_BRANCH (bb->last_ins->opcode)) {
7147                                         bbn = bb->last_ins->inst_true_bb;
7148                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR &&
7149                                             bbn->code->inst_target_bb->region == bb->region) {
7150                                                 if (cfg->verbose_level > 2)             
7151                                                         g_print ("cbranch1 to branch triggered %d -> (%d) %d (0x%02x)\n", 
7152                                                                  bb->block_num, bbn->block_num, bbn->code->inst_target_bb->block_num, 
7153                                                                  bbn->code->opcode);
7154
7155                                                 bb->last_ins->inst_true_bb = bbn->code->inst_target_bb;
7156
7157                                                 replace_in_block (bbn, bb, NULL);
7158                                                 if (!bbn->in_count)
7159                                                         replace_in_block (bbn->code->inst_target_bb, bbn, bb);
7160                                                 replace_out_block (bb, bbn, bbn->code->inst_target_bb);
7161
7162                                                 link_bblock (cfg, bb, bbn->code->inst_target_bb);
7163
7164                                                 changed = TRUE;
7165                                                 break;
7166                                         }
7167
7168                                         bbn = bb->last_ins->inst_false_bb;
7169                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR &&
7170                                             bbn->code->inst_target_bb->region == bb->region) {
7171                                                 if (cfg->verbose_level > 2)
7172                                                         g_print ("cbranch2 to branch triggered %d -> (%d) %d (0x%02x)\n", 
7173                                                                  bb->block_num, bbn->block_num, bbn->code->inst_target_bb->block_num, 
7174                                                                  bbn->code->opcode);
7175
7176                                                 bb->last_ins->inst_false_bb = bbn->code->inst_target_bb;
7177
7178                                                 replace_in_block (bbn, bb, NULL);
7179                                                 if (!bbn->in_count)
7180                                                         replace_in_block (bbn->code->inst_target_bb, bbn, bb);
7181                                                 replace_out_block (bb, bbn, bbn->code->inst_target_bb);
7182
7183                                                 link_bblock (cfg, bb, bbn->code->inst_target_bb);
7184
7185                                                 changed = TRUE;
7186                                                 break;
7187                                         }
7188                                 }
7189                         }
7190                 }
7191         } while (changed && (niterations > 0));
7192
7193 }
7194
7195 static void
7196 mono_compile_create_vars (MonoCompile *cfg)
7197 {
7198         MonoMethodSignature *sig;
7199         MonoMethodHeader *header;
7200         int i;
7201
7202         header = ((MonoMethodNormal *)cfg->method)->header;
7203
7204         sig = cfg->method->signature;
7205         
7206         if (!MONO_TYPE_IS_VOID (sig->ret)) {
7207                 cfg->ret = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
7208                 cfg->ret->opcode = OP_RETARG;
7209                 cfg->ret->inst_vtype = sig->ret;
7210                 cfg->ret->klass = mono_class_from_mono_type (sig->ret);
7211         }
7212         if (cfg->verbose_level > 2)
7213                 g_print ("creating vars\n");
7214
7215         if (sig->hasthis)
7216                 mono_compile_create_var (cfg, &cfg->method->klass->this_arg, OP_ARG);
7217
7218         for (i = 0; i < sig->param_count; ++i)
7219                 mono_compile_create_var (cfg, sig->params [i], OP_ARG);
7220
7221         cfg->locals_start = cfg->num_varinfo;
7222
7223         if (cfg->verbose_level > 2)
7224                 g_print ("creating locals\n");
7225         for (i = 0; i < header->num_locals; ++i)
7226                 mono_compile_create_var (cfg, header->locals [i], OP_LOCAL);
7227         if (cfg->verbose_level > 2)
7228                 g_print ("locals done\n");
7229 }
7230
7231 void
7232 mono_print_code (MonoCompile *cfg)
7233 {
7234         MonoBasicBlock *bb;
7235         
7236         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7237                 MonoInst *tree = bb->code;      
7238
7239                 if (!tree)
7240                         continue;
7241                 
7242                 g_print ("CODE BLOCK %d (nesting %d):\n", bb->block_num, bb->nesting);
7243
7244                 for (; tree; tree = tree->next) {
7245                         mono_print_tree (tree);
7246                         g_print ("\n");
7247                 }
7248
7249                 if (bb->last_ins)
7250                         bb->last_ins->next = NULL;
7251         }
7252 }
7253
7254 extern const char * const mono_burg_rule_string [];
7255
7256 static void
7257 emit_state (MonoCompile *cfg, MBState *state, int goal)
7258 {
7259         MBState *kids [10];
7260         int ern = mono_burg_rule (state, goal);
7261         const guint16 *nts = mono_burg_nts [ern];
7262         MBEmitFunc emit;
7263
7264         //g_print ("rule: %s\n", mono_burg_rule_string [ern]);
7265         switch (goal) {
7266         case MB_NTERM_reg:
7267                 //if (state->reg2)
7268                 //      state->reg1 = state->reg2; /* chain rule */
7269                 //else
7270                 state->reg1 = mono_regstate_next_int (cfg->rs);
7271                 //g_print ("alloc symbolic R%d (reg2: R%d) in block %d\n", state->reg1, state->reg2, cfg->cbb->block_num);
7272                 break;
7273         case MB_NTERM_lreg:
7274                 state->reg1 = mono_regstate_next_int (cfg->rs);
7275                 state->reg2 = mono_regstate_next_int (cfg->rs);
7276                 break;
7277         case MB_NTERM_freg:
7278                 state->reg1 = mono_regstate_next_float (cfg->rs);
7279                 break;
7280         default:
7281                 /* do nothing */
7282                 break;
7283         }
7284         if (nts [0]) {
7285                 mono_burg_kids (state, ern, kids);
7286
7287                 emit_state (cfg, kids [0], nts [0]);
7288                 if (nts [1]) {
7289                         emit_state (cfg, kids [1], nts [1]);
7290                         if (nts [2]) {
7291                                 g_assert (!nts [3]);
7292                                 emit_state (cfg, kids [2], nts [2]);
7293                         }
7294                 }
7295         }
7296
7297 //      g_print ("emit: %s (%p)\n", mono_burg_rule_string [ern], state);
7298         if ((emit = mono_burg_func [ern]))
7299                 emit (state, state->tree, cfg); 
7300 }
7301
7302 #define DEBUG_SELECTION
7303
7304 static void 
7305 mini_select_instructions (MonoCompile *cfg)
7306 {
7307         static const int reverse_map [] = {
7308                 CEE_BNE_UN, CEE_BLT, CEE_BLE, CEE_BGT, CEE_BGE,
7309                 CEE_BEQ, CEE_BLT_UN, CEE_BLE_UN, CEE_BGT_UN, CEE_BGE_UN
7310         };
7311         static const int reverse_fmap [] = {
7312                 OP_FBNE_UN, OP_FBLT, OP_FBLE, OP_FBGT, OP_FBGE,
7313                 OP_FBEQ, OP_FBLT_UN, OP_FBLE_UN, OP_FBGT_UN, OP_FBGE_UN
7314         };
7315         static const int reverse_lmap [] = {
7316                 OP_LBNE_UN, OP_LBLT, OP_LBLE, OP_LBGT, OP_LBGE,
7317                 OP_LBEQ, OP_LBLT_UN, OP_LBLE_UN, OP_LBGT_UN, OP_LBGE_UN
7318         };
7319
7320         MonoBasicBlock *bb;
7321         
7322         cfg->state_pool = mono_mempool_new ();
7323         cfg->rs = mono_regstate_new ();
7324
7325         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7326                 if (bb->last_ins && MONO_IS_COND_BRANCH (bb->last_ins->opcode) &&
7327                     bb->next_bb != bb->last_ins->inst_false_bb) {
7328
7329                         if (bb->next_bb ==  bb->last_ins->inst_true_bb) {
7330                                 MonoBasicBlock *tmp =  bb->last_ins->inst_true_bb;
7331                                 bb->last_ins->inst_true_bb = bb->last_ins->inst_false_bb;
7332                                 bb->last_ins->inst_false_bb = tmp;
7333                                 
7334                                 if (bb->last_ins->opcode >= CEE_BEQ && bb->last_ins->opcode <= CEE_BLT_UN) {
7335                                         bb->last_ins->opcode = reverse_map [bb->last_ins->opcode - CEE_BEQ];
7336                                 } else if (bb->last_ins->opcode >= OP_FBEQ && bb->last_ins->opcode <= OP_FBLT_UN) {
7337                                         bb->last_ins->opcode = reverse_fmap [bb->last_ins->opcode - OP_FBEQ];
7338                                 } else if (bb->last_ins->opcode >= OP_LBEQ && bb->last_ins->opcode <= OP_LBLT_UN) {
7339                                         bb->last_ins->opcode = reverse_lmap [bb->last_ins->opcode - OP_LBEQ];
7340                                 }
7341                         } else {                        
7342                                 MonoInst *inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
7343                                 inst->opcode = CEE_BR;
7344                                 inst->inst_target_bb = bb->last_ins->inst_false_bb;
7345                                 mono_bblock_add_inst (bb, inst);
7346                         }
7347                 }
7348         }
7349
7350 #ifdef DEBUG_SELECTION
7351         if (cfg->verbose_level >= 4) {
7352         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7353                 MonoInst *tree = bb->code;      
7354                 g_print ("DUMP BLOCK %d:\n", bb->block_num);
7355                 if (!tree)
7356                         continue;
7357                 for (; tree; tree = tree->next) {
7358                         mono_print_tree (tree);
7359                         g_print ("\n");
7360                 }
7361         }
7362         }
7363 #endif
7364
7365         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7366                 MonoInst *tree = bb->code, *next;       
7367                 MBState *mbstate;
7368
7369                 if (!tree)
7370                         continue;
7371                 bb->code = NULL;
7372                 bb->last_ins = NULL;
7373                 
7374                 cfg->cbb = bb;
7375                 mono_regstate_reset (cfg->rs);
7376
7377 #ifdef DEBUG_SELECTION
7378                 if (cfg->verbose_level >= 3)
7379                         g_print ("LABEL BLOCK %d:\n", bb->block_num);
7380 #endif
7381                 for (; tree; tree = next) {
7382                         next = tree->next;
7383 #ifdef DEBUG_SELECTION
7384                         if (cfg->verbose_level >= 3) {
7385                                 mono_print_tree (tree);
7386                                 g_print ("\n");
7387                         }
7388 #endif
7389
7390                         if (!(mbstate = mono_burg_label (tree, cfg))) {
7391                                 g_warning ("unable to label tree %p", tree);
7392                                 mono_print_tree (tree);
7393                                 g_print ("\n");                         
7394                                 g_assert_not_reached ();
7395                         }
7396                         emit_state (cfg, mbstate, MB_NTERM_stmt);
7397                 }
7398                 bb->max_ireg = cfg->rs->next_vireg;
7399                 bb->max_freg = cfg->rs->next_vfreg;
7400
7401                 if (bb->last_ins)
7402                         bb->last_ins->next = NULL;
7403
7404                 mono_mempool_empty (cfg->state_pool); 
7405         }
7406         mono_mempool_destroy (cfg->state_pool); 
7407 }
7408
7409 void
7410 mono_codegen (MonoCompile *cfg)
7411 {
7412         MonoJumpInfo *patch_info;
7413         MonoBasicBlock *bb;
7414         int i, max_epilog_size;
7415         guint8 *code;
7416
7417         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7418                 cfg->spill_count = 0;
7419                 /* we reuse dfn here */
7420                 /* bb->dfn = bb_count++; */
7421                 mono_arch_local_regalloc (cfg, bb);
7422         }
7423
7424         if (cfg->prof_options & MONO_PROFILE_COVERAGE)
7425                 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, cfg->num_bblocks);
7426
7427         code = mono_arch_emit_prolog (cfg);
7428
7429         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
7430                 code = mono_arch_instrument_prolog (cfg, mono_profiler_method_enter, code, FALSE);
7431
7432         cfg->code_len = code - cfg->native_code;
7433         cfg->prolog_end = cfg->code_len;
7434
7435         mono_debug_open_method (cfg);
7436
7437         /* emit code all basic blocks */
7438         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7439                 bb->native_offset = cfg->code_len;
7440                 mono_arch_output_basic_block (cfg, bb);
7441         }
7442         cfg->bb_exit->native_offset = cfg->code_len;
7443
7444         code = cfg->native_code + cfg->code_len;
7445
7446         max_epilog_size = mono_arch_max_epilog_size (cfg);
7447
7448         /* we always allocate code in cfg->domain->code_mp to increase locality */
7449         cfg->code_size = cfg->code_len + max_epilog_size;
7450         /* fixme: align to MONO_ARCH_CODE_ALIGNMENT */
7451
7452         mono_domain_lock (cfg->domain);
7453         code = mono_code_manager_reserve (cfg->domain->code_mp, cfg->code_size);
7454         mono_domain_unlock (cfg->domain);
7455
7456         memcpy (code, cfg->native_code, cfg->code_len);
7457         g_free (cfg->native_code);
7458         cfg->native_code = code;
7459         code = cfg->native_code + cfg->code_len;
7460   
7461         /* g_assert (((int)cfg->native_code & (MONO_ARCH_CODE_ALIGNMENT - 1)) == 0); */
7462
7463         cfg->epilog_begin = cfg->code_len;
7464
7465         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
7466                 code = mono_arch_instrument_epilog (cfg, mono_profiler_method_leave, code, FALSE);
7467
7468         cfg->code_len = code - cfg->native_code;
7469
7470         mono_arch_emit_epilog (cfg);
7471
7472         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7473                 switch (patch_info->type) {
7474                 case MONO_PATCH_INFO_ABS: {
7475                         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (patch_info->data.target);
7476                         if (info) {
7477                                 //printf ("TEST %s %p\n", info->name, patch_info->data.target);
7478                                 if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && 
7479                                         strstr (cfg->method->name, info->name))
7480                                         /*
7481                                          * This is an icall wrapper, and this is a call to the
7482                                          * wrapped function.
7483                                          */
7484                                         ;
7485                                 else {
7486                                         patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
7487                                         patch_info->data.name = info->name;
7488                                 }
7489                         }
7490                         else {
7491                                 MonoVTable *vtable = mono_find_class_init_trampoline_by_addr (patch_info->data.target);
7492                                 if (vtable) {
7493                                         patch_info->type = MONO_PATCH_INFO_CLASS_INIT;
7494                                         patch_info->data.klass = vtable->klass;
7495                                 }
7496                         }
7497                         break;
7498                 }
7499                 case MONO_PATCH_INFO_SWITCH: {
7500                         gpointer *table;
7501                         mono_domain_lock (cfg->domain);
7502                         table = mono_code_manager_reserve (cfg->domain->code_mp, sizeof (gpointer) * patch_info->table_size);
7503                         mono_domain_unlock (cfg->domain);
7504                 
7505                         patch_info->ip.i = patch_info->ip.label->inst_c0;
7506                         for (i = 0; i < patch_info->table_size; i++) {
7507                                 table [i] = (gpointer)patch_info->data.table [i]->native_offset;
7508                         }
7509                         patch_info->data.target = table;
7510                         break;
7511                 }
7512                 default:
7513                         /* do nothing */
7514                         break;
7515                 }
7516         }
7517        
7518         if (cfg->verbose_level > 0)
7519                 g_print ("Method %s emitted at %p to %p [%s]\n", 
7520                                  mono_method_full_name (cfg->method, TRUE), 
7521                                  cfg->native_code, cfg->native_code + cfg->code_len, cfg->domain->friendly_name);
7522
7523         mono_arch_patch_code (cfg->method, cfg->domain, cfg->native_code, cfg->patch_info, cfg->run_cctors);
7524
7525         mono_domain_lock (cfg->domain);
7526         mono_code_manager_commit (cfg->domain->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
7527         mono_domain_unlock (cfg->domain);
7528         
7529         mono_arch_flush_icache (cfg->native_code, cfg->code_len);
7530
7531         mono_debug_close_method (cfg);
7532 }
7533
7534 static void
7535 mono_cprop_copy_values (MonoCompile *cfg, MonoInst *tree, MonoInst **acp)
7536 {
7537         MonoInst *cp;
7538         int arity;
7539
7540         if (tree->ssa_op == MONO_SSA_LOAD && (tree->inst_i0->opcode == OP_LOCAL || tree->inst_i0->opcode == OP_ARG) && 
7541             (cp = acp [tree->inst_i0->inst_c0]) && !tree->inst_i0->flags) {
7542
7543                 if (cp->opcode == OP_ICONST) {
7544                         if (cfg->opt & MONO_OPT_CONSPROP) {
7545                                 //{ static int c = 0; printf ("CCOPY %d %d %s\n", c++, cp->inst_c0, mono_method_full_name (cfg->method, TRUE)); }
7546                                 *tree = *cp;
7547                         }
7548                 } else {
7549                         if (tree->inst_i0->inst_vtype->type == cp->inst_vtype->type) {
7550                                 if (cfg->opt & MONO_OPT_COPYPROP) {
7551                                         //{ static int c = 0; printf ("VCOPY %d\n", ++c); }
7552                                         tree->inst_i0 = cp;
7553                                 } 
7554                         }
7555                 } 
7556         } else {
7557                 arity = mono_burg_arity [tree->opcode];
7558
7559                 if (arity) {
7560                         mono_cprop_copy_values (cfg, tree->inst_i0, acp);
7561                         if (cfg->opt & MONO_OPT_CFOLD)
7562                                 mono_constant_fold_inst (tree, NULL); 
7563                         /* The opcode may have changed */
7564                         if (mono_burg_arity [tree->opcode] > 1) {
7565                                 mono_cprop_copy_values (cfg, tree->inst_i1, acp);
7566                                 if (cfg->opt & MONO_OPT_CFOLD)
7567                                         mono_constant_fold_inst (tree, NULL); 
7568                         }
7569                         mono_constant_fold_inst (tree, NULL); 
7570                 }
7571         }
7572 }
7573
7574 static void
7575 mono_cprop_invalidate_values (MonoInst *tree, MonoInst **acp, int acp_size)
7576 {
7577         int arity;
7578
7579         switch (tree->opcode) {
7580         case CEE_STIND_I:
7581         case CEE_STIND_I1:
7582         case CEE_STIND_I2:
7583         case CEE_STIND_I4:
7584         case CEE_STIND_REF:
7585         case CEE_STIND_I8:
7586         case CEE_STIND_R4:
7587         case CEE_STIND_R8:
7588         case CEE_STOBJ:
7589                 if (tree->ssa_op == MONO_SSA_NOP) {
7590                         memset (acp, 0, sizeof (MonoInst *) * acp_size);
7591                         return;
7592                 }
7593
7594                 break;
7595         case CEE_CALL:
7596         case OP_CALL_REG:
7597         case CEE_CALLVIRT:
7598         case OP_LCALL_REG:
7599         case OP_LCALLVIRT:
7600         case OP_LCALL:
7601         case OP_FCALL_REG:
7602         case OP_FCALLVIRT:
7603         case OP_FCALL:
7604         case OP_VCALL_REG:
7605         case OP_VCALLVIRT:
7606         case OP_VCALL:
7607         case OP_VOIDCALL_REG:
7608         case OP_VOIDCALLVIRT:
7609         case OP_VOIDCALL: {
7610                 MonoCallInst *call = (MonoCallInst *)tree;
7611                 MonoMethodSignature *sig = call->signature;
7612                 int i, byref = FALSE;
7613
7614                 for (i = 0; i < sig->param_count; i++) {
7615                         if (sig->params [i]->byref) {
7616                                 byref = TRUE;
7617                                 break;
7618                         }
7619                 }
7620
7621                 if (byref)
7622                         memset (acp, 0, sizeof (MonoInst *) * acp_size);
7623
7624                 return;
7625         }
7626         default:
7627                 break;
7628         }
7629
7630         arity = mono_burg_arity [tree->opcode];
7631
7632         switch (arity) {
7633         case 0:
7634                 break;
7635         case 1:
7636                 mono_cprop_invalidate_values (tree->inst_i0, acp, acp_size);
7637                 break;
7638         case 2:
7639                 mono_cprop_invalidate_values (tree->inst_i0, acp, acp_size);
7640                 mono_cprop_invalidate_values (tree->inst_i1, acp, acp_size);
7641                 break;
7642         default:
7643                 g_assert_not_reached ();
7644         }
7645 }
7646
7647 static void
7648 mono_local_cprop_bb (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst **acp, int acp_size)
7649 {
7650         MonoInst *tree = bb->code;      
7651         int i;
7652
7653         if (!tree)
7654                 return;
7655
7656         for (; tree; tree = tree->next) {
7657
7658                 mono_cprop_copy_values (cfg, tree, acp);
7659
7660                 mono_cprop_invalidate_values (tree, acp, acp_size);
7661
7662                 if (tree->ssa_op == MONO_SSA_STORE  && 
7663                     (tree->inst_i0->opcode == OP_LOCAL || tree->inst_i0->opcode == OP_ARG)) {
7664                         MonoInst *i1 = tree->inst_i1;
7665
7666                         acp [tree->inst_i0->inst_c0] = NULL;
7667
7668                         for (i = 0; i < acp_size; i++) {
7669                                 if (acp [i] && acp [i]->opcode != OP_ICONST && 
7670                                     acp [i]->inst_c0 == tree->inst_i0->inst_c0) {
7671                                         acp [i] = NULL;
7672                                 }
7673                         }
7674
7675                         if (i1->opcode == OP_ICONST) {
7676                                 acp [tree->inst_i0->inst_c0] = i1;
7677                                 //printf ("DEF1 BB%d %d\n", bb->block_num,tree->inst_i0->inst_c0);
7678                         }
7679                         if (i1->ssa_op == MONO_SSA_LOAD && 
7680                             (i1->inst_i0->opcode == OP_LOCAL || i1->inst_i0->opcode == OP_ARG) &&
7681                             (i1->inst_i0->inst_c0 != tree->inst_i0->inst_c0)) {
7682                                 acp [tree->inst_i0->inst_c0] = i1->inst_i0;
7683                                 //printf ("DEF2 BB%d %d %d\n", bb->block_num,tree->inst_i0->inst_c0,i1->inst_i0->inst_c0);
7684                         }
7685                 }
7686
7687                 /*
7688                   if (tree->opcode == CEE_BEQ) {
7689                   g_assert (tree->inst_i0->opcode == OP_COMPARE);
7690                   if (tree->inst_i0->inst_i0->opcode == OP_ICONST &&
7691                   tree->inst_i0->inst_i1->opcode == OP_ICONST) {
7692                   
7693                   tree->opcode = CEE_BR;
7694                   if (tree->inst_i0->inst_i0->opcode == tree->inst_i0->inst_i1->opcode) {
7695                   tree->inst_target_bb = tree->inst_true_bb;
7696                   } else {
7697                   tree->inst_target_bb = tree->inst_false_bb;
7698                   }
7699                   }
7700                   }
7701                 */
7702         }
7703 }
7704
7705 static void
7706 mono_local_cprop (MonoCompile *cfg)
7707 {
7708         MonoBasicBlock *bb;
7709         MonoInst **acp;
7710
7711         acp = alloca (sizeof (MonoInst *) * cfg->num_varinfo);
7712
7713         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7714                 memset (acp, 0, sizeof (MonoInst *) * cfg->num_varinfo);
7715                 mono_local_cprop_bb (cfg, bb, acp, cfg->num_varinfo);
7716         }
7717 }
7718
7719 MonoCompile*
7720 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gboolean run_cctors, int parts)
7721 {
7722         MonoMethodHeader *header = ((MonoMethodNormal *)method)->header;
7723         guint8 *ip = (guint8 *)header->code;
7724         MonoCompile *cfg;
7725         MonoJitInfo *jinfo;
7726         int dfn = 0, i, code_size_ratio;
7727
7728         mono_jit_stats.methods_compiled++;
7729         if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)
7730                 mono_profiler_method_jit (method);
7731
7732         cfg = g_new0 (MonoCompile, 1);
7733         cfg->method = method;
7734         cfg->mempool = mono_mempool_new ();
7735         cfg->opt = opts;
7736         cfg->prof_options = mono_profiler_get_events ();
7737         cfg->run_cctors = run_cctors;
7738         cfg->bb_hash = g_hash_table_new (NULL, NULL);
7739         cfg->domain = domain;
7740         cfg->verbose_level = mini_verbose;
7741         cfg->intvars = mono_mempool_alloc0 (cfg->mempool, sizeof (guint16) * STACK_MAX * 
7742                                             ((MonoMethodNormal *)method)->header->max_stack);
7743
7744         if (cfg->verbose_level > 2)
7745                 g_print ("converting method %s\n", mono_method_full_name (method, TRUE));
7746
7747         /*
7748          * create MonoInst* which represents arguments and local variables
7749          */
7750         mono_compile_create_vars (cfg);
7751
7752         if ((i = mono_method_to_ir (cfg, method, NULL, NULL, cfg->locals_start, NULL, NULL, NULL, 0, FALSE)) < 0) {
7753                 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
7754                         mono_profiler_method_end_jit (method, MONO_PROFILE_FAILED);
7755                 mono_destroy_compile (cfg);
7756                 return NULL;
7757         }
7758
7759         mono_jit_stats.basic_blocks += cfg->num_bblocks;
7760         mono_jit_stats.max_basic_blocks = MAX (cfg->num_bblocks, mono_jit_stats.max_basic_blocks);
7761
7762         if (cfg->num_varinfo > 2000) {
7763                 /* 
7764                  * we disable some optimizations if there are too many variables
7765                  * because JIT time may become too expensive. The actual number needs 
7766                  * to be tweaked and eventually the non-linear algorithms should be fixed.
7767                  */
7768                 cfg->opt &= ~ (MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP);
7769                 cfg->disable_ssa = TRUE;
7770         }
7771         /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/
7772
7773         /* Depth-first ordering on basic blocks */
7774         cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
7775
7776         if (cfg->opt & MONO_OPT_BRANCH)
7777                 optimize_branches (cfg);
7778
7779         df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
7780         if (cfg->num_bblocks != dfn + 1) {
7781                 MonoBasicBlock *bb;
7782
7783                 cfg->num_bblocks = dfn + 1;
7784
7785                 if (!header->clauses) {
7786                         /* remove unreachable code, because the code in them may be 
7787                          * inconsistent  (access to dead variables for example) */
7788                         for (bb = cfg->bb_entry; bb;) {
7789                                 MonoBasicBlock *bbn = bb->next_bb;
7790
7791                                 if (bbn && bbn->region == -1 && !bbn->dfn) {
7792                                         if (cfg->verbose_level > 1)
7793                                                 g_print ("found unreachabel code in BB%d\n", bbn->block_num);
7794                                         bb->next_bb = bbn->next_bb;
7795                                         nullify_basic_block (bbn);                      
7796                                 } else {
7797                                         bb = bb->next_bb;
7798                                 }
7799                         }
7800                 }
7801         }
7802
7803         if (cfg->opt & MONO_OPT_LOOP) {
7804                 mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM);
7805                 mono_compute_natural_loops (cfg);
7806         }
7807
7808         /* after method_to_ir */
7809         if (parts == 1)
7810                 return cfg;
7811
7812 //#define DEBUGSSA "logic_run"
7813 #define DEBUGSSA_CLASS "Tests"
7814 #ifdef DEBUGSSA
7815
7816         if (!header->num_clauses && !cfg->disable_ssa) {
7817                 mono_local_cprop (cfg);
7818                 mono_ssa_compute (cfg);
7819         }
7820 #else 
7821
7822         /* fixme: add all optimizations which requires SSA */
7823         if (cfg->opt & (MONO_OPT_DEADCE | MONO_OPT_ABCREM)) {
7824                 if (!(cfg->comp_done & MONO_COMP_SSA) && !header->num_clauses && !cfg->disable_ssa) {
7825                         mono_local_cprop (cfg);
7826                         mono_ssa_compute (cfg);
7827
7828                         if (cfg->verbose_level >= 2) {
7829                                 print_dfn (cfg);
7830                         }
7831                 }
7832         }
7833 #endif
7834
7835         /* after SSA translation */
7836         if (parts == 2)
7837                 return cfg;
7838
7839         if ((cfg->opt & MONO_OPT_CONSPROP) ||  (cfg->opt & MONO_OPT_COPYPROP)) {
7840                 if (cfg->comp_done & MONO_COMP_SSA) {
7841                         mono_ssa_cprop (cfg);
7842                 } else {
7843                         mono_local_cprop (cfg);
7844                 }
7845         }
7846
7847         if (cfg->comp_done & MONO_COMP_SSA) {                   
7848                 mono_ssa_deadce (cfg);
7849
7850                 //mono_ssa_strength_reduction (cfg);
7851
7852                 if (cfg->opt & MONO_OPT_ABCREM)
7853                         mono_perform_abc_removal (cfg);
7854
7855                 mono_ssa_remove (cfg);
7856
7857                 if (cfg->opt & MONO_OPT_BRANCH)
7858                         optimize_branches (cfg);
7859         }
7860
7861         /* after SSA removal */
7862         if (parts == 3)
7863                 return cfg;
7864
7865         decompose_pass (cfg);
7866
7867         if (cfg->opt & MONO_OPT_LINEARS) {
7868                 GList *vars, *regs;
7869
7870                 /* fixme: maybe we can avoid to compute livenesss here if already computed ? */
7871                 cfg->comp_done &= ~MONO_COMP_LIVENESS;
7872                 if (!(cfg->comp_done & MONO_COMP_LIVENESS))
7873                         mono_analyze_liveness (cfg);
7874
7875                 if ((vars = mono_arch_get_allocatable_int_vars (cfg))) {
7876                         regs = mono_arch_get_global_int_regs (cfg);
7877                         mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs);
7878                 }
7879         }
7880
7881         //mono_print_code (cfg);
7882
7883        //print_dfn (cfg);
7884         
7885         /* variables are allocated after decompose, since decompose could create temps */
7886         mono_arch_allocate_vars (cfg);
7887
7888         if (cfg->opt & MONO_OPT_CFOLD)
7889                 mono_constant_fold (cfg);
7890
7891         mini_select_instructions (cfg);
7892
7893         mono_codegen (cfg);
7894         if (cfg->verbose_level >= 2) {
7895                 char *id =  mono_method_full_name (cfg->method, FALSE);
7896                 mono_disassemble_code (cfg->native_code, cfg->code_len, id + 3);
7897                 g_free (id);
7898         }
7899         
7900         jinfo = mono_mempool_alloc0 (cfg->domain->mp, sizeof (MonoJitInfo));
7901
7902         jinfo = g_new0 (MonoJitInfo, 1);
7903         jinfo->method = method;
7904         jinfo->code_start = cfg->native_code;
7905         jinfo->code_size = cfg->code_len;
7906         jinfo->used_regs = cfg->used_int_regs;
7907         jinfo->domain_neutral = (cfg->opt & MONO_OPT_SHARED) != 0;
7908
7909         if (header->num_clauses) {
7910                 int i;
7911
7912                 jinfo->exvar_offset = cfg->exvar? cfg->exvar->inst_offset: 0;
7913                 jinfo->num_clauses = header->num_clauses;
7914                 jinfo->clauses = mono_mempool_alloc0 (cfg->domain->mp, 
7915                         sizeof (MonoJitExceptionInfo) * header->num_clauses);
7916
7917                 for (i = 0; i < header->num_clauses; i++) {
7918                         MonoExceptionClause *ec = &header->clauses [i];
7919                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
7920                         MonoBasicBlock *tblock;
7921
7922                         ei->flags = ec->flags;
7923
7924                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
7925                                 tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->token_or_filter);
7926                                 g_assert (tblock);
7927                                 ei->data.filter = cfg->native_code + tblock->native_offset;
7928                         } else {
7929                                 ei->data.token = ec->token_or_filter;
7930                         }
7931
7932                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->try_offset);
7933                         g_assert (tblock);
7934                         ei->try_start = cfg->native_code + tblock->native_offset;
7935                         g_assert (tblock->native_offset);
7936                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->try_offset + ec->try_len);
7937                         g_assert (tblock);
7938                         ei->try_end = cfg->native_code + tblock->native_offset;
7939                         g_assert (tblock->native_offset);
7940                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->handler_offset);
7941                         g_assert (tblock);
7942                         ei->handler_start = cfg->native_code + tblock->native_offset;
7943                 }
7944         }
7945
7946         cfg->jit_info = jinfo;
7947
7948         mono_jit_info_table_add (cfg->domain, jinfo);
7949
7950         /* collect statistics */
7951         mono_jit_stats.allocated_code_size += cfg->code_len;
7952         code_size_ratio = cfg->code_len;
7953         if (code_size_ratio > mono_jit_stats.biggest_method_size) {
7954                         mono_jit_stats.biggest_method_size = code_size_ratio;
7955                         mono_jit_stats.biggest_method = method;
7956         }
7957         code_size_ratio = (code_size_ratio * 100) / ((MonoMethodNormal *)method)->header->code_size;
7958         if (code_size_ratio > mono_jit_stats.max_code_size_ratio) {
7959                 mono_jit_stats.max_code_size_ratio = code_size_ratio;
7960                 mono_jit_stats.max_ratio_method = method;
7961         }
7962         mono_jit_stats.native_code_size += cfg->code_len;
7963
7964         if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
7965                 mono_profiler_method_end_jit (method, MONO_PROFILE_OK);
7966
7967         return cfg;
7968 }
7969
7970 static gpointer
7971 mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain)
7972 {
7973         MonoCompile *cfg;
7974         GHashTable *jit_code_hash;
7975         gpointer code = NULL;
7976         guint32 opt;
7977         MonoJitInfo *info;
7978
7979         opt = default_opt;
7980
7981         jit_code_hash = target_domain->jit_code_hash;
7982
7983 #ifdef MONO_USE_AOT_COMPILER
7984         if (!mono_compile_aot && (opt & MONO_OPT_AOT)) {
7985                 MonoJitInfo *info;
7986                 MonoDomain *domain = mono_domain_get ();
7987
7988                 mono_domain_lock (domain);
7989
7990                 mono_class_init (method->klass);
7991                 if ((info = mono_aot_get_method (domain, method))) {
7992                         g_hash_table_insert (domain->jit_code_hash, method, info);
7993                         mono_domain_unlock (domain);
7994                         mono_runtime_class_init (mono_class_vtable (domain, method->klass));
7995                         return info->code_start;
7996                 }
7997
7998                 mono_domain_unlock (domain);
7999         }
8000 #endif
8001
8002         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
8003             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
8004                 MonoMethod *nm;
8005
8006                 if (!method->addr) {
8007                         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
8008                                 method->addr = mono_lookup_internal_call (method);
8009                         else
8010                                 if (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)
8011                                         mono_lookup_pinvoke_call (method, NULL, NULL);
8012                 }
8013 #ifdef MONO_USE_EXC_TABLES
8014                 if (mono_method_blittable (method)) {
8015                         return method->addr;
8016                 } else {
8017 #endif
8018                         nm = mono_marshal_get_native_wrapper (method);
8019                         return mono_compile_method (nm);
8020
8021                         //if (mono_debug_format != MONO_DEBUG_FORMAT_NONE) 
8022                         //mono_debug_add_wrapper (method, nm);
8023 #ifdef MONO_USE_EXC_TABLES
8024                 }
8025 #endif
8026         } else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
8027                 const char *name = method->name;
8028                 MonoMethod *nm;
8029
8030                 if (method->klass->parent == mono_defaults.multicastdelegate_class) {
8031                         if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
8032                                 /* FIXME: uhm, we need a wrapper to handle exceptions? */
8033                                 return (gpointer)mono_delegate_ctor;
8034                         } else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
8035                                 nm = mono_marshal_get_delegate_invoke (method);
8036                                 return mono_jit_compile_method (nm);
8037                         } else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
8038                                 nm = mono_marshal_get_delegate_begin_invoke (method);
8039                                 return mono_jit_compile_method (nm);
8040                         } else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
8041                                 nm = mono_marshal_get_delegate_end_invoke (method);
8042                                 return mono_jit_compile_method (nm);
8043                         }
8044                 }
8045                 return NULL;
8046         }
8047
8048         cfg = mini_method_compile (method, opt, target_domain, TRUE, 0);
8049
8050         mono_domain_lock (target_domain);
8051
8052         /* Check if some other thread already did the job. In this case, we can
8053        discard the code this thread generated. */
8054
8055         if ((info = g_hash_table_lookup (target_domain->jit_code_hash, method))) {
8056                 /* We can't use a domain specific method in another domain */
8057                 if ((target_domain == mono_domain_get ()) || info->domain_neutral) {
8058                         code = info->code_start;
8059 //                      printf("Discarding code for method %s\n", method->name);
8060                 }
8061         }
8062         
8063         if (code == NULL) {
8064                 g_hash_table_insert (jit_code_hash, method, cfg->jit_info);
8065                 code = cfg->native_code;
8066         }
8067
8068         mono_destroy_compile (cfg);
8069
8070         if (target_domain->jump_target_hash) {
8071                 MonoJumpInfo patch_info;
8072                 GSList *list, *tmp;
8073                 list = g_hash_table_lookup (target_domain->jump_target_hash, method);
8074                 if (list) {
8075                         patch_info.next = NULL;
8076                         patch_info.ip.i = 0;
8077                         patch_info.type = MONO_PATCH_INFO_METHOD_JUMP;
8078                         patch_info.data.method = method;
8079                         g_hash_table_remove (target_domain->jump_target_hash, method);
8080                 }
8081                 for (tmp = list; tmp; tmp = tmp->next)
8082                         mono_arch_patch_code (NULL, target_domain, tmp->data, &patch_info, TRUE);
8083                 g_slist_free (list);
8084         }
8085
8086         mono_domain_unlock (target_domain);
8087
8088         mono_runtime_class_init (mono_class_vtable (target_domain, method->klass));
8089         return code;
8090 }
8091
8092 static gpointer
8093 mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt)
8094 {
8095         /* FIXME: later copy the code from mono */
8096         MonoDomain *target_domain, *domain = mono_domain_get ();
8097         MonoJitInfo *info;
8098         gpointer p;
8099
8100         if (default_opt & MONO_OPT_SHARED)
8101                 target_domain = mono_root_domain;
8102         else 
8103                 target_domain = domain;
8104
8105         mono_domain_lock (target_domain);
8106
8107         if ((info = g_hash_table_lookup (target_domain->jit_code_hash, method))) {
8108                 /* We can't use a domain specific method in another domain */
8109                 if (! ((domain != target_domain) && !info->domain_neutral)) {
8110                         mono_domain_unlock (target_domain);
8111                         mono_jit_stats.methods_lookups++;
8112                         mono_runtime_class_init (mono_class_vtable (target_domain, method->klass));
8113                         return info->code_start;
8114                 }
8115         }
8116
8117         mono_domain_unlock (target_domain);
8118         p = mono_jit_compile_method_inner (method, target_domain);
8119         return p;
8120 }
8121
8122 static gpointer
8123 mono_jit_compile_method (MonoMethod *method)
8124 {
8125         return mono_jit_compile_method_with_opt (method, default_opt);
8126 }
8127
8128 static gpointer
8129 mono_jit_find_compiled_method (MonoDomain *domain, MonoMethod *method)
8130 {
8131         MonoDomain *target_domain;
8132         MonoJitInfo *info;
8133
8134         if (default_opt & MONO_OPT_SHARED)
8135                 target_domain = mono_root_domain;
8136         else 
8137                 target_domain = domain;
8138
8139         mono_domain_lock (target_domain);
8140
8141         if ((info = g_hash_table_lookup (target_domain->jit_code_hash, method))) {
8142                 /* We can't use a domain specific method in another domain */
8143                 if (! ((domain != target_domain) && !info->domain_neutral)) {
8144                         mono_domain_unlock (target_domain);
8145                         mono_jit_stats.methods_lookups++;
8146                         return info->code_start;
8147                 }
8148         }
8149
8150         mono_domain_unlock (target_domain);
8151
8152         return NULL;
8153 }
8154
8155 /**
8156  * mono_jit_runtime_invoke:
8157  * @method: the method to invoke
8158  * @obj: this pointer
8159  * @params: array of parameter values.
8160  * @exc: used to catch exceptions objects
8161  */
8162 static MonoObject*
8163 mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
8164 {
8165         MonoMethod *invoke;
8166         MonoObject *(*runtime_invoke) (MonoObject *this, void **params, MonoObject **exc, void* compiled_method);
8167         void* compiled_method;
8168
8169         if (obj == NULL && !(method->flags & METHOD_ATTRIBUTE_STATIC) && !method->string_ctor && (method->wrapper_type == 0)) {
8170                 g_warning ("Ignoring invocation of an instance method on a NULL instance.\n");
8171                 return NULL;
8172         }
8173
8174         invoke = mono_marshal_get_runtime_invoke (method);
8175         runtime_invoke = mono_jit_compile_method (invoke);
8176         compiled_method = mono_jit_compile_method (method);
8177         return runtime_invoke (obj, params, exc, compiled_method);
8178 }
8179
8180 #ifdef PLATFORM_WIN32
8181 #define GET_CONTEXT \
8182         struct sigcontext *ctx = (struct sigcontext*)_dummy;
8183 #else
8184 #ifdef __sparc
8185 #define GET_CONTEXT \
8186     void *ctx = context;
8187 #elif defined(__ppc__) || defined (__powerpc__) || defined (__s390__)
8188 #define GET_CONTEXT \
8189     void *ctx = context;
8190 #else
8191 #define GET_CONTEXT \
8192         void **_p = (void **)&_dummy; \
8193         struct sigcontext *ctx = (struct sigcontext *)++_p;
8194 #endif
8195 #endif
8196
8197 #ifdef MONO_ARCH_USE_SIGACTION
8198 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy, siginfo_t *info, void *context)
8199 #else
8200 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy)
8201 #endif
8202
8203 static void
8204 SIG_HANDLER_SIGNATURE (sigfpe_signal_handler)
8205 {
8206         MonoException *exc;
8207         GET_CONTEXT
8208
8209         exc = mono_get_exception_divide_by_zero ();
8210         
8211         mono_arch_handle_exception (ctx, exc, FALSE);
8212 }
8213
8214 static void
8215 SIG_HANDLER_SIGNATURE (sigill_signal_handler)
8216 {
8217         MonoException *exc;
8218         GET_CONTEXT
8219         exc = mono_get_exception_execution_engine ("SIGILL");
8220         
8221         mono_arch_handle_exception (ctx, exc, FALSE);
8222 }
8223
8224 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
8225
8226 static void
8227 sigsegv_signal_handler (int _dummy, siginfo_t *info, void *context)
8228 {
8229         MonoException *exc;
8230         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
8231         struct sigcontext *ctx = (struct sigcontext *)&(((ucontext_t*)context)->uc_mcontext);
8232                 
8233         /* Can't allocate memory using Boehm GC on altstack */
8234         if (jit_tls->stack_size && 
8235                 ((guint8*)info->si_addr >= (guint8*)jit_tls->end_of_stack - jit_tls->stack_size) &&
8236                 ((guint8*)info->si_addr < (guint8*)jit_tls->end_of_stack))
8237                 exc = mono_domain_get ()->stack_overflow_ex;
8238         else
8239                 exc = mono_domain_get ()->null_reference_ex;
8240                         
8241         mono_arch_handle_exception (ctx, exc, FALSE);
8242 }
8243
8244 #else
8245
8246 static void
8247 SIG_HANDLER_SIGNATURE (sigsegv_signal_handler)
8248 {
8249         GET_CONTEXT;
8250
8251         mono_arch_handle_exception (ctx, NULL, FALSE);
8252 }
8253
8254 #endif
8255
8256 static void
8257 SIG_HANDLER_SIGNATURE (sigusr1_signal_handler)
8258 {
8259         MonoThread *thread;
8260         gboolean stopRequested = FALSE;
8261
8262         GET_CONTEXT
8263
8264         thread = mono_thread_current ();
8265
8266         mono_monitor_try_enter ((MonoObject *)thread, INFINITE);
8267         stopRequested = (thread->state & ThreadState_StopRequested) != 0;
8268         mono_monitor_exit ((MonoObject *)thread);
8269
8270         thread->abort_exc = mono_get_exception_thread_abort ();
8271
8272         if (stopRequested) {
8273                 /* Don't throw the exception, just abort the thread */
8274                 mono_thread_abort ((MonoObject *) thread->abort_exc);
8275         }
8276         else {
8277                 mono_arch_handle_exception (ctx, thread->abort_exc, FALSE);
8278         }
8279 }
8280
8281 static void
8282 SIG_HANDLER_SIGNATURE (sigquit_signal_handler)
8283 {
8284        MonoException *exc;
8285        GET_CONTEXT
8286
8287        exc = mono_get_exception_execution_engine ("Interrupted (SIGQUIT).");
8288        
8289        mono_arch_handle_exception (ctx, exc, FALSE);
8290 }
8291
8292 static void
8293 SIG_HANDLER_SIGNATURE (sigint_signal_handler)
8294 {
8295         MonoException *exc;
8296         GET_CONTEXT
8297
8298         exc = mono_get_exception_execution_engine ("Interrupted (SIGINT).");
8299         
8300         mono_arch_handle_exception (ctx, exc, FALSE);
8301 }
8302
8303 #ifndef PLATFORM_WIN32
8304 static void
8305 add_signal_handler (int signo, gpointer handler)
8306 {
8307         struct sigaction sa;
8308
8309 #ifdef MONO_ARCH_USE_SIGACTION
8310         sa.sa_sigaction = handler;
8311         sigemptyset (&sa.sa_mask);
8312         sa.sa_flags = SA_SIGINFO;
8313 #else
8314         sa.sa_handler = handler;
8315         sigemptyset (&sa.sa_mask);
8316         sa.sa_flags = 0;
8317 #endif
8318         g_assert (sigaction (signo, &sa, NULL) != -1);
8319 }
8320 #endif
8321
8322 static void
8323 mono_runtime_install_handlers (void)
8324 {
8325 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
8326         struct sigaction sa;
8327 #endif
8328
8329 #ifdef PLATFORM_WIN32
8330         win32_seh_init();
8331         win32_seh_set_handler(SIGFPE, sigfpe_signal_handler);
8332         win32_seh_set_handler(SIGILL, sigill_signal_handler);
8333         win32_seh_set_handler(SIGSEGV, sigsegv_signal_handler);
8334         if (getenv ("MONO_DEBUG"))
8335                 win32_seh_set_handler(SIGINT, sigint_signal_handler);
8336 #else /* !PLATFORM_WIN32 */
8337
8338         /* libpthreads has its own implementation of sigaction(),
8339          * but it seems to work well with our current exception
8340          * handlers. If not we must call syscall directly instead 
8341          * of sigaction */
8342
8343         if (getenv ("MONO_DEBUG")) {
8344                 add_signal_handler (SIGINT, sigint_signal_handler);
8345         }
8346
8347         add_signal_handler (SIGFPE, sigfpe_signal_handler);
8348         add_signal_handler (SIGQUIT, sigquit_signal_handler);
8349         add_signal_handler (SIGILL, sigill_signal_handler);
8350         add_signal_handler (SIGBUS, sigsegv_signal_handler);
8351         add_signal_handler (mono_thread_get_abort_signal (), sigusr1_signal_handler);
8352
8353         /* catch SIGSEGV */
8354 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
8355         sa.sa_sigaction = sigsegv_signal_handler;
8356         sigemptyset (&sa.sa_mask);
8357         sa.sa_flags = SA_SIGINFO | SA_ONSTACK;
8358         g_assert (sigaction (SIGSEGV, &sa, NULL) != -1);
8359 #else
8360         add_signal_handler (SIGSEGV, sigsegv_signal_handler);
8361 #endif
8362
8363 #endif /* PLATFORM_WIN32 */
8364 }
8365
8366 /* mono_jit_create_remoting_trampoline:
8367  * @method: pointer to the method info
8368  *
8369  * Creates a trampoline which calls the remoting functions. This
8370  * is used in the vtable of transparent proxies.
8371  * 
8372  * Returns: a pointer to the newly created code 
8373  */
8374 static gpointer
8375 mono_jit_create_remoting_trampoline (MonoMethod *method)
8376 {
8377         MonoMethod *nm;
8378         guint8 *addr = NULL;
8379
8380         if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) || 
8381             (method->signature->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class))) {
8382                 nm = mono_marshal_get_remoting_invoke (method);
8383                 addr = mono_compile_method (nm);
8384         } else {
8385                 addr = mono_compile_method (method);
8386         }
8387         return addr;
8388 }
8389
8390 MonoDomain *
8391 mini_init (const char *filename)
8392 {
8393         MonoDomain *domain;
8394
8395         mono_arch_cpu_init ();
8396
8397         if (!g_thread_supported ())
8398                 g_thread_init (NULL);
8399
8400         mono_jit_tls_id = TlsAlloc ();
8401         setup_jit_tls_data ((gpointer)-1, mono_thread_abort);
8402
8403         InitializeCriticalSection (&trampoline_hash_mutex);
8404
8405         mono_burg_init ();
8406
8407         if (default_opt & MONO_OPT_AOT)
8408                 mono_aot_init ();
8409
8410         mono_runtime_install_handlers ();
8411         mono_threads_install_cleanup (mini_thread_cleanup);
8412
8413 #define JIT_TRAMPOLINES_WORK
8414 #ifdef JIT_TRAMPOLINES_WORK
8415         mono_install_compile_method (mono_jit_compile_method);
8416         mono_install_trampoline (mono_arch_create_jit_trampoline);
8417         mono_install_remoting_trampoline (mono_jit_create_remoting_trampoline);
8418 #endif
8419 #define JIT_INVOKE_WORKS
8420 #ifdef JIT_INVOKE_WORKS
8421         mono_install_runtime_invoke (mono_jit_runtime_invoke);
8422         mono_install_handler (mono_arch_get_throw_exception ());
8423 #endif
8424         mono_install_stack_walk (mono_jit_walk_stack);
8425
8426         domain = mono_init (filename);
8427         mono_init_icall ();
8428
8429         mono_add_internal_call ("System.Diagnostics.StackFrame::get_frame_info", 
8430                                 ves_icall_get_frame_info);
8431         mono_add_internal_call ("System.Diagnostics.StackTrace::get_trace", 
8432                                 ves_icall_get_trace);
8433         mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers", 
8434                                 mono_runtime_install_handlers);
8435
8436
8437         create_helper_signature ();
8438
8439 #define JIT_CALLS_WORK
8440 #ifdef JIT_CALLS_WORK
8441         /* Needs to be called here since register_jit_icall depends on it */
8442         mono_marshal_init ();
8443
8444         mono_arch_register_lowlevel_calls ();
8445         mono_register_jit_icall (mono_profiler_method_enter, "mono_profiler_method_enter", NULL, TRUE);
8446         mono_register_jit_icall (mono_profiler_method_leave, "mono_profiler_method_leave", NULL, TRUE);
8447         mono_register_jit_icall (mono_trace_enter_method, "mono_trace_enter_method", NULL, TRUE);
8448         mono_register_jit_icall (mono_trace_leave_method, "mono_trace_leave_method", NULL, TRUE);
8449
8450         mono_register_jit_icall (mono_get_lmf_addr, "mono_get_lmf_addr", helper_sig_ptr_void, TRUE);
8451         mono_register_jit_icall (mono_domain_get, "mono_domain_get", helper_sig_domain_get, TRUE);
8452
8453         /* fixme: we cant hanlde vararg methods this way, because the signature is not constant */
8454         //mono_register_jit_icall (ves_array_element_address, "ves_array_element_address", NULL);
8455         //mono_register_jit_icall (mono_array_new_va, "mono_array_new_va", NULL);
8456
8457         mono_register_jit_icall (mono_arch_get_throw_exception (), "mono_arch_throw_exception", helper_sig_void_obj, TRUE);
8458         mono_register_jit_icall (mono_arch_get_throw_exception_by_name (), "mono_arch_throw_exception_by_name", 
8459                                  helper_sig_void_ptr, TRUE);
8460         mono_register_jit_icall (mono_thread_get_pending_exception, "mono_thread_get_pending_exception", helper_sig_obj_void, FALSE);
8461
8462         /* 
8463          * NOTE, NOTE, NOTE, NOTE:
8464          * when adding emulation for some opcodes, remember to also add a dummy
8465          * rule to the burg files, because we need the arity information to be correct.
8466          */
8467         mono_register_opcode_emulation (OP_LMUL, "__emul_lmul", helper_sig_long_long_long, mono_llmult, TRUE);
8468         mono_register_opcode_emulation (OP_LMUL_OVF_UN, "__emul_lmul_ovf_un", helper_sig_long_long_long, mono_llmult_ovf_un, FALSE);
8469         mono_register_opcode_emulation (OP_LMUL_OVF, "__emul_lmul_ovf", helper_sig_long_long_long, mono_llmult_ovf, FALSE);
8470         mono_register_opcode_emulation (OP_LDIV, "__emul_ldiv", helper_sig_long_long_long, mono_lldiv, FALSE);
8471         mono_register_opcode_emulation (OP_LDIV_UN, "__emul_ldiv_un", helper_sig_long_long_long, mono_lldiv_un, FALSE);
8472         mono_register_opcode_emulation (OP_LREM, "__emul_lrem", helper_sig_long_long_long, mono_llrem, FALSE);
8473         mono_register_opcode_emulation (OP_LREM_UN, "__emul_lrem_un", helper_sig_long_long_long, mono_llrem_un, FALSE);
8474
8475 #ifndef MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS
8476         mono_register_opcode_emulation (OP_LSHL, "__emul_lshl", helper_sig_long_long_int, mono_lshl, TRUE);
8477         mono_register_opcode_emulation (OP_LSHR, "__emul_lshr", helper_sig_long_long_int, mono_lshr, TRUE);
8478         mono_register_opcode_emulation (OP_LSHR_UN, "__emul_lshr_un", helper_sig_long_long_int, mono_lshr_un, TRUE);
8479 #endif
8480
8481         mono_register_opcode_emulation (OP_FCONV_TO_U8, "__emul_fconv_to_u8", helper_sig_ulong_double, mono_fconv_u8, FALSE);
8482         mono_register_opcode_emulation (OP_FCONV_TO_U4, "__emul_fconv_to_u4", helper_sig_uint_double, mono_fconv_u4, FALSE);
8483         mono_register_opcode_emulation (OP_FCONV_TO_OVF_I8, "__emul_fconv_to_ovf_i8", helper_sig_long_double, mono_fconv_ovf_i8, FALSE);
8484         mono_register_opcode_emulation (OP_FCONV_TO_OVF_U8, "__emul_fconv_to_ovf_u8", helper_sig_ulong_double, mono_fconv_ovf_u8, FALSE);
8485
8486 #ifdef MONO_ARCH_EMULATE_FCONV_TO_I8
8487         mono_register_opcode_emulation (OP_FCONV_TO_I8, "__emul_fconv_to_i8", helper_sig_long_double, mono_fconv_i8, FALSE);
8488 #endif
8489 #ifdef MONO_ARCH_EMULATE_CONV_R8_UN
8490         mono_register_opcode_emulation (CEE_CONV_R_UN, "__emul_conv_r_un", helper_sig_double_int, mono_conv_to_r8_un, FALSE);
8491 #endif
8492 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8
8493         mono_register_opcode_emulation (OP_LCONV_TO_R8, "__emul_lconv_to_r8", helper_sig_double_long, mono_lconv_to_r8, FALSE);
8494 #endif
8495 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R4
8496         mono_register_opcode_emulation (OP_LCONV_TO_R4, "__emul_lconv_to_r4", helper_sig_float_long, mono_lconv_to_r4, FALSE);
8497 #endif
8498 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8_UN
8499         mono_register_opcode_emulation (OP_LCONV_TO_R_UN, "__emul_lconv_to_r8_un", helper_sig_double_long, mono_lconv_to_r8_un, FALSE);
8500 #endif
8501 #ifdef MONO_ARCH_EMULATE_FREM
8502         mono_register_opcode_emulation (OP_FREM, "__emul_frem", helper_sig_double_double_double, fmod, FALSE);
8503 #endif
8504
8505 #if SIZEOF_VOID_P == 4
8506         mono_register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", helper_sig_uint_double, mono_fconv_u4, TRUE);
8507 #else
8508 #ifdef __GNUC__
8509 #warning "fixme: add opcode emulation"
8510 #endif
8511 #endif
8512
8513         /* other jit icalls */
8514         mono_register_jit_icall (mono_class_static_field_address , "mono_class_static_field_address", 
8515                                  helper_sig_ptr_ptr_ptr, FALSE);
8516         mono_register_jit_icall (mono_ldtoken_wrapper, "mono_ldtoken_wrapper", helper_sig_ptr_ptr_ptr, FALSE);
8517         mono_register_jit_icall (mono_get_special_static_data, "mono_get_special_static_data", helper_sig_ptr_int, FALSE);
8518         mono_register_jit_icall (mono_ldstr, "mono_ldstr", helper_sig_ldstr, FALSE);
8519         mono_register_jit_icall (helper_memcpy, "helper_memcpy", helper_sig_memcpy, FALSE);
8520         mono_register_jit_icall (helper_memset, "helper_memset", helper_sig_memset, FALSE);
8521         mono_register_jit_icall (helper_initobj, "helper_initobj", helper_sig_initobj, FALSE);
8522         mono_register_jit_icall (helper_stelem_ref, "helper_stelem_ref", helper_sig_stelem_ref, FALSE);
8523         mono_register_jit_icall (helper_stelem_ref_check, "helper_stelem_ref_check", helper_sig_stelem_ref_check, FALSE);
8524         mono_register_jit_icall (mono_object_new, "mono_object_new", helper_sig_object_new, FALSE);
8525         mono_register_jit_icall (mono_object_new_specific, "mono_object_new_specific", helper_sig_object_new_specific, FALSE);
8526         mono_register_jit_icall (mono_object_new_fast, "mono_object_new_fast", helper_sig_object_new_specific, FALSE);
8527         mono_register_jit_icall (mono_array_new, "mono_array_new", helper_sig_newarr, FALSE);
8528         mono_register_jit_icall (mono_array_new_specific, "mono_array_new_specific", helper_sig_newarr_specific, FALSE);
8529         mono_register_jit_icall (mono_string_to_utf16, "mono_string_to_utf16", helper_sig_ptr_obj, FALSE);
8530         mono_register_jit_icall (mono_string_from_utf16, "mono_string_from_utf16", helper_sig_obj_ptr, FALSE);
8531         mono_register_jit_icall (mono_string_new_wrapper, "mono_string_new_wrapper", helper_sig_obj_ptr, FALSE);
8532         mono_register_jit_icall (mono_string_to_utf8, "mono_string_to_utf8", helper_sig_ptr_obj, FALSE);
8533         mono_register_jit_icall (mono_string_to_bstr, "mono_string_to_bstr", helper_sig_ptr_obj, FALSE);
8534         mono_register_jit_icall (mono_string_to_ansibstr, "mono_string_to_ansibstr", helper_sig_ptr_obj, FALSE);
8535         mono_register_jit_icall (mono_string_builder_to_utf8, "mono_string_builder_to_utf8", helper_sig_ptr_obj, FALSE);
8536         mono_register_jit_icall (mono_string_builder_to_utf16, "mono_string_builder_to_utf16", helper_sig_ptr_obj, FALSE);
8537         mono_register_jit_icall (mono_array_to_savearray, "mono_array_to_savearray", helper_sig_ptr_obj, FALSE);
8538         mono_register_jit_icall (mono_array_to_lparray, "mono_array_to_lparray", helper_sig_ptr_obj, FALSE);
8539         mono_register_jit_icall (mono_delegate_to_ftnptr, "mono_delegate_to_ftnptr", helper_sig_ptr_obj, FALSE);
8540         mono_register_jit_icall (mono_marshal_string_array, "mono_marshal_string_array", helper_sig_ptr_obj, FALSE);
8541         mono_register_jit_icall (mono_marshal_string_array_to_unicode, "mono_marshal_string_array_to_unicode", helper_sig_ptr_obj, FALSE);
8542         mono_register_jit_icall (mono_marshal_asany, "mono_marshal_asany", helper_sig_ptr_obj_int, FALSE);
8543         mono_register_jit_icall (mono_marshal_free_asany, "mono_marshal_free_asany", helper_sig_void_obj_ptr_int, FALSE);
8544         mono_register_jit_icall (mono_string_utf8_to_builder, "mono_string_utf8_to_builder", helper_sig_void_ptr_ptr, FALSE);
8545         mono_register_jit_icall (mono_string_utf16_to_builder, "mono_string_utf16_to_builder", helper_sig_void_ptr_ptr, FALSE);
8546         mono_register_jit_icall (mono_marshal_free_array, "mono_marshal_free_array", helper_sig_void_ptr_ptr, FALSE);
8547         mono_register_jit_icall (mono_string_to_byvalstr, "mono_string_to_byvalstr", helper_sig_void_ptr_ptr_ptr, FALSE);
8548         mono_register_jit_icall (mono_string_to_byvalwstr, "mono_string_to_byvalwstr", helper_sig_void_ptr_ptr_ptr, FALSE);
8549         mono_register_jit_icall (g_free, "g_free", helper_sig_void_ptr, FALSE);
8550         mono_register_jit_icall (mono_runtime_class_init, "mono_runtime_class_init", helper_sig_void_ptr, FALSE);
8551         mono_register_jit_icall (mono_ldftn, "mono_ldftn", helper_sig_compile, FALSE);
8552         mono_register_jit_icall (mono_ldftn_nosync, "mono_ldftn_nosync", helper_sig_compile, FALSE);
8553         mono_register_jit_icall (mono_ldvirtfn, "mono_ldvirtfn", helper_sig_compile_virt, FALSE);
8554 #endif
8555
8556 #define JIT_RUNTIME_WORKS
8557 #ifdef JIT_RUNTIME_WORKS
8558         mono_runtime_install_cleanup ((MonoDomainFunc)mini_cleanup);
8559         mono_runtime_init (domain, mono_thread_start_cb, mono_thread_attach_cb);
8560 #endif
8561
8562         mono_thread_attach (domain);
8563         return domain;
8564 }
8565
8566 MonoJitStats mono_jit_stats = {0};
8567
8568 static void 
8569 print_jit_stats (void)
8570 {
8571         if (mono_jit_stats.enabled) {
8572                 g_print ("Mono Jit statistics\n");
8573                 g_print ("Compiled methods:       %ld\n", mono_jit_stats.methods_compiled);
8574                 g_print ("Methods from AOT:       %ld\n", mono_jit_stats.methods_aot);
8575                 g_print ("Methods cache lookup:   %ld\n", mono_jit_stats.methods_lookups);
8576                 g_print ("Method trampolines:     %ld\n", mono_jit_stats.method_trampolines);
8577                 g_print ("Basic blocks:           %ld\n", mono_jit_stats.basic_blocks);
8578                 g_print ("Max basic blocks:       %ld\n", mono_jit_stats.max_basic_blocks);
8579                 g_print ("Allocated vars:         %ld\n", mono_jit_stats.allocate_var);
8580                 g_print ("Analyze stack repeat:   %ld\n", mono_jit_stats.analyze_stack_repeat);
8581                 g_print ("Compiled CIL code size: %ld\n", mono_jit_stats.cil_code_size);
8582                 g_print ("Native code size:       %ld\n", mono_jit_stats.native_code_size);
8583                 g_print ("Max code size ratio:    %.2f (%s::%s)\n", mono_jit_stats.max_code_size_ratio/100.0,
8584                                 mono_jit_stats.max_ratio_method->klass->name, mono_jit_stats.max_ratio_method->name);
8585                 g_print ("Biggest method:         %ld (%s::%s)\n", mono_jit_stats.biggest_method_size,
8586                                 mono_jit_stats.biggest_method->klass->name, mono_jit_stats.biggest_method->name);
8587                 g_print ("Code reallocs:          %ld\n", mono_jit_stats.code_reallocs);
8588                 g_print ("Allocated code size:    %ld\n", mono_jit_stats.allocated_code_size);
8589                 g_print ("Inlineable methods:     %ld\n", mono_jit_stats.inlineable_methods);
8590                 g_print ("Inlined methods:        %ld\n", mono_jit_stats.inlined_methods);
8591                 
8592                 g_print ("\nCreated object count:   %ld\n", mono_stats.new_object_count);
8593                 g_print ("Initialized classes:    %ld\n", mono_stats.initialized_class_count);
8594                 g_print ("Used classes:           %ld\n", mono_stats.used_class_count);
8595                 g_print ("Static data size:       %ld\n", mono_stats.class_static_data_size);
8596                 g_print ("VTable data size:       %ld\n", mono_stats.class_vtable_size);
8597
8598                 g_print ("\nGeneric instances:      %ld\n", mono_stats.generic_instance_count);
8599                 g_print ("Inflated methods:       %ld\n", mono_stats.inflated_method_count);
8600                 g_print ("Inflated types:         %ld\n", mono_stats.inflated_type_count);
8601                 g_print ("Generics metadata size: %ld\n", mono_stats.generics_metadata_size);
8602         }
8603 }
8604
8605 void
8606 mini_cleanup (MonoDomain *domain)
8607 {
8608         /* 
8609          * mono_runtime_cleanup() and mono_domain_finalize () need to
8610          * be called early since they need the execution engine still
8611          * fully working (mono_domain_finalize may invoke managed finalizers
8612          * and mono_runtime_cleanup will wait for other threads to finish).
8613          */
8614         mono_domain_finalize (domain, 2000);
8615
8616         mono_runtime_cleanup (domain);
8617
8618         mono_profiler_shutdown ();
8619
8620         mono_debug_cleanup ();
8621
8622 #ifdef PLATFORM_WIN32
8623         win32_seh_cleanup();
8624 #endif
8625
8626         mono_domain_free (domain, TRUE);
8627
8628         print_jit_stats ();
8629 }
8630
8631 void
8632 mono_set_defaults (int verbose_level, guint32 opts)
8633 {
8634         mini_verbose = verbose_level;
8635         default_opt = opts;
8636 }
8637
8638 static void
8639 mono_precompile_assembly (MonoAssembly *ass, void *user_data)
8640 {
8641         MonoImage *image = ass->image;
8642         MonoMethod *method;
8643         int i, count = 0;
8644
8645         if (mini_verbose > 0)
8646                 printf ("PRECOMPILE: %s.\n", ass->image->name);
8647
8648         for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8649                 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
8650                 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
8651                         continue;
8652                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
8653                         continue;
8654
8655                 count++;
8656                 if (mini_verbose > 1) {
8657                         char * desc = mono_method_full_name (method, TRUE);
8658                         g_print ("Compiling %d %s\n", count, desc);
8659                         g_free (desc);
8660                 }
8661                 mono_compile_method (method);
8662         }
8663 }
8664
8665 void mono_precompile_assemblies ()
8666 {
8667         mono_assembly_foreach ((GFunc)mono_precompile_assembly, NULL);
8668 }