3d82c2e8828ae1e3b137b11a26272cce513025b5
[mono.git] / mono / mini / mini.c
1 /*
2  * mini.c: The new Mono code generator.
3  *
4  * Authors:
5  *   Paolo Molaro (lupus@ximian.com)
6  *   Dietmar Maurer (dietmar@ximian.com)
7  *
8  * Copyright 2002-2003 Ximian, Inc.
9  * Copyright 2003-2010 Novell, Inc.
10  * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
11  */
12
13 #include <config.h>
14 #ifdef HAVE_ALLOCA_H
15 #include <alloca.h>
16 #endif
17 #ifdef HAVE_UNISTD_H
18 #include <unistd.h>
19 #endif
20 #include <math.h>
21 #ifdef HAVE_SYS_TIME_H
22 #include <sys/time.h>
23 #endif
24
25 #include <mono/utils/memcheck.h>
26
27 #include <mono/metadata/assembly.h>
28 #include <mono/metadata/loader.h>
29 #include <mono/metadata/tabledefs.h>
30 #include <mono/metadata/class.h>
31 #include <mono/metadata/object.h>
32 #include <mono/metadata/tokentype.h>
33 #include <mono/metadata/tabledefs.h>
34 #include <mono/metadata/threads.h>
35 #include <mono/metadata/appdomain.h>
36 #include <mono/metadata/debug-helpers.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/gc-internal.h>
43 #include <mono/metadata/threads-types.h>
44 #include <mono/metadata/verify.h>
45 #include <mono/metadata/verify-internals.h>
46 #include <mono/metadata/mempool-internals.h>
47 #include <mono/metadata/attach.h>
48 #include <mono/metadata/runtime.h>
49 #include <mono/utils/mono-math.h>
50 #include <mono/utils/mono-compiler.h>
51 #include <mono/utils/mono-counters.h>
52 #include <mono/utils/mono-error-internals.h>
53 #include <mono/utils/mono-logger-internal.h>
54 #include <mono/utils/mono-mmap.h>
55 #include <mono/utils/mono-path.h>
56 #include <mono/utils/mono-tls.h>
57 #include <mono/utils/mono-hwcap.h>
58 #include <mono/utils/dtrace.h>
59 #include <mono/utils/mono-threads.h>
60 #include <mono/io-layer/io-layer.h>
61
62 #include "mini.h"
63 #include "seq-points.h"
64 #include "tasklets.h"
65 #include <string.h>
66 #include <ctype.h>
67 #include "trace.h"
68 #include "version.h"
69 #include "ir-emit.h"
70
71 #include "jit-icalls.h"
72
73 #include "mini-gc.h"
74 #include "debugger-agent.h"
75
76 MonoTraceSpec *mono_jit_trace_calls;
77 MonoMethodDesc *mono_inject_async_exc_method;
78 int mono_inject_async_exc_pos;
79 MonoMethodDesc *mono_break_at_bb_method;
80 int mono_break_at_bb_bb_num;
81 gboolean mono_do_x86_stack_align = TRUE;
82 gboolean mono_using_xdebug;
83
84 #define mono_jit_lock() mono_mutex_lock (&jit_mutex)
85 #define mono_jit_unlock() mono_mutex_unlock (&jit_mutex)
86 static mono_mutex_t jit_mutex;
87
88 /* Whenever to check for pending exceptions in managed-to-native wrappers */
89 gboolean check_for_pending_exc = TRUE;
90
91 gpointer
92 mono_realloc_native_code (MonoCompile *cfg)
93 {
94 #if defined(__default_codegen__)
95         return g_realloc (cfg->native_code, cfg->code_size);
96 #elif defined(__native_client_codegen__)
97         guint old_padding;
98         gpointer native_code;
99         guint alignment_check;
100
101         /* Save the old alignment offset so we can re-align after the realloc. */
102         old_padding = (guint)(cfg->native_code - cfg->native_code_alloc);
103         cfg->code_size = NACL_BUNDLE_ALIGN_UP (cfg->code_size);
104
105         cfg->native_code_alloc = g_realloc ( cfg->native_code_alloc,
106                                                                                  cfg->code_size + kNaClAlignment );
107
108         /* Align native_code to next nearest kNaClAlignment byte. */
109         native_code = (guint)cfg->native_code_alloc + kNaClAlignment;
110         native_code = (guint)native_code & ~kNaClAlignmentMask;
111
112         /* Shift the data to be 32-byte aligned again. */
113         memmove (native_code, cfg->native_code_alloc + old_padding, cfg->code_size);
114
115         alignment_check = (guint)native_code & kNaClAlignmentMask;
116         g_assert (alignment_check == 0);
117         return native_code;
118 #else
119         g_assert_not_reached ();
120         return cfg->native_code;
121 #endif
122 }
123
124 #ifdef __native_client_codegen__
125
126 /* Prevent instructions from straddling a 32-byte alignment boundary.   */
127 /* Instructions longer than 32 bytes must be aligned internally.        */
128 /* IN: pcode, instlen                                                   */
129 /* OUT: pcode                                                           */
130 void mono_nacl_align_inst(guint8 **pcode, int instlen) {
131   int space_in_block;
132
133   space_in_block = kNaClAlignment - ((uintptr_t)(*pcode) & kNaClAlignmentMask);
134
135   if (G_UNLIKELY (instlen >= kNaClAlignment)) {
136     g_assert_not_reached();
137   } else if (instlen > space_in_block) {
138     *pcode = mono_arch_nacl_pad(*pcode, space_in_block);
139   }
140 }
141
142 /* Move emitted call sequence to the end of a kNaClAlignment-byte block.  */
143 /* IN: start    pointer to start of call sequence                         */
144 /* IN: pcode    pointer to end of call sequence (current "IP")            */
145 /* OUT: start   pointer to the start of the call sequence after padding   */
146 /* OUT: pcode   pointer to the end of the call sequence after padding     */
147 void mono_nacl_align_call(guint8 **start, guint8 **pcode) {
148   const size_t MAX_NACL_CALL_LENGTH = kNaClAlignment;
149   guint8 copy_of_call[MAX_NACL_CALL_LENGTH];
150   guint8 *temp;
151
152   const size_t length = (size_t)((*pcode)-(*start));
153   g_assert(length < MAX_NACL_CALL_LENGTH);
154
155   memcpy(copy_of_call, *start, length);
156   temp = mono_nacl_pad_call(*start, (guint8)length);
157   memcpy(temp, copy_of_call, length);
158   (*start) = temp;
159   (*pcode) = temp + length;
160 }
161
162 /* mono_nacl_pad_call(): Insert padding for Native Client call instructions */
163 /*    code     pointer to buffer for emitting code                          */
164 /*    ilength  length of call instruction                                   */
165 guint8 *mono_nacl_pad_call(guint8 *code, guint8 ilength) {
166   int freeSpaceInBlock = kNaClAlignment - ((uintptr_t)code & kNaClAlignmentMask);
167   int padding = freeSpaceInBlock - ilength;
168
169   if (padding < 0) {
170     /* There isn't enough space in this block for the instruction. */
171     /* Fill this block and start a new one.                        */
172     code = mono_arch_nacl_pad(code, freeSpaceInBlock);
173     freeSpaceInBlock = kNaClAlignment;
174     padding = freeSpaceInBlock - ilength;
175   }
176   g_assert(ilength > 0);
177   g_assert(padding >= 0);
178   g_assert(padding < kNaClAlignment);
179   if (0 == padding) return code;
180   return mono_arch_nacl_pad(code, padding);
181 }
182
183 guint8 *mono_nacl_align(guint8 *code) {
184   int padding = kNaClAlignment - ((uintptr_t)code & kNaClAlignmentMask);
185   if (padding != kNaClAlignment) code = mono_arch_nacl_pad(code, padding);
186   return code;
187 }
188
189 void mono_nacl_fix_patches(const guint8 *code, MonoJumpInfo *ji)
190 {
191 #ifndef USE_JUMP_TABLES
192   MonoJumpInfo *patch_info;
193   for (patch_info = ji; patch_info; patch_info = patch_info->next) {
194     unsigned char *ip = patch_info->ip.i + code;
195     ip = mono_arch_nacl_skip_nops(ip);
196     patch_info->ip.i = ip - code;
197   }
198 #endif
199 }
200 #endif  /* __native_client_codegen__ */
201
202 typedef struct {
203         MonoExceptionClause *clause;
204         MonoBasicBlock *basic_block;
205         int start_offset;
206 } TryBlockHole;
207
208 /**
209  * mono_emit_unwind_op:
210  *
211  *   Add an unwind op with the given parameters for the list of unwind ops stored in
212  * cfg->unwind_ops.
213  */
214 void
215 mono_emit_unwind_op (MonoCompile *cfg, int when, int tag, int reg, int val)
216 {
217         MonoUnwindOp *op = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoUnwindOp));
218
219         op->op = tag;
220         op->reg = reg;
221         op->val = val;
222         op->when = when;
223         
224         cfg->unwind_ops = g_slist_append_mempool (cfg->mempool, cfg->unwind_ops, op);
225         if (cfg->verbose_level > 1) {
226                 switch (tag) {
227                 case DW_CFA_def_cfa:
228                         printf ("CFA: [%x] def_cfa: %s+0x%x\n", when, mono_arch_regname (reg), val);
229                         break;
230                 case DW_CFA_def_cfa_register:
231                         printf ("CFA: [%x] def_cfa_reg: %s\n", when, mono_arch_regname (reg));
232                         break;
233                 case DW_CFA_def_cfa_offset:
234                         printf ("CFA: [%x] def_cfa_offset: 0x%x\n", when, val);
235                         break;
236                 case DW_CFA_offset:
237                         printf ("CFA: [%x] offset: %s at cfa-0x%x\n", when, mono_arch_regname (reg), -val);
238                         break;
239                 }
240         }
241 }
242
243 #define MONO_INIT_VARINFO(vi,id) do { \
244         (vi)->range.first_use.pos.bid = 0xffff; \
245         (vi)->reg = -1; \
246         (vi)->idx = (id); \
247 } while (0)
248
249 /**
250  * mono_unlink_bblock:
251  *
252  *   Unlink two basic blocks.
253  */
254 void
255 mono_unlink_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
256 {
257         int i, pos;
258         gboolean found;
259
260         found = FALSE;
261         for (i = 0; i < from->out_count; ++i) {
262                 if (to == from->out_bb [i]) {
263                         found = TRUE;
264                         break;
265                 }
266         }
267         if (found) {
268                 pos = 0;
269                 for (i = 0; i < from->out_count; ++i) {
270                         if (from->out_bb [i] != to)
271                                 from->out_bb [pos ++] = from->out_bb [i];
272                 }
273                 g_assert (pos == from->out_count - 1);
274                 from->out_count--;
275         }
276
277         found = FALSE;
278         for (i = 0; i < to->in_count; ++i) {
279                 if (from == to->in_bb [i]) {
280                         found = TRUE;
281                         break;
282                 }
283         }
284         if (found) {
285                 pos = 0;
286                 for (i = 0; i < to->in_count; ++i) {
287                         if (to->in_bb [i] != from)
288                                 to->in_bb [pos ++] = to->in_bb [i];
289                 }
290                 g_assert (pos == to->in_count - 1);
291                 to->in_count--;
292         }
293 }
294
295 /*
296  * mono_bblocks_linked:
297  *
298  *   Return whenever BB1 and BB2 are linked in the CFG.
299  */
300 gboolean
301 mono_bblocks_linked (MonoBasicBlock *bb1, MonoBasicBlock *bb2)
302 {
303         int i;
304
305         for (i = 0; i < bb1->out_count; ++i) {
306                 if (bb1->out_bb [i] == bb2)
307                         return TRUE;
308         }
309
310         return FALSE;
311 }
312
313 static int
314 mono_find_block_region_notry (MonoCompile *cfg, int offset)
315 {
316         MonoMethodHeader *header = cfg->header;
317         MonoExceptionClause *clause;
318         int i;
319
320         for (i = 0; i < header->num_clauses; ++i) {
321                 clause = &header->clauses [i];
322                 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->data.filter_offset) &&
323                     (offset < (clause->handler_offset)))
324                         return ((i + 1) << 8) | MONO_REGION_FILTER | clause->flags;
325                            
326                 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
327                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
328                                 return ((i + 1) << 8) | MONO_REGION_FINALLY | clause->flags;
329                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
330                                 return ((i + 1) << 8) | MONO_REGION_FAULT | clause->flags;
331                         else
332                                 return ((i + 1) << 8) | MONO_REGION_CATCH | clause->flags;
333                 }
334         }
335
336         return -1;
337 }
338
339 /*
340  * mono_get_block_region_notry:
341  *
342  *   Return the region corresponding to REGION, ignoring try clauses nested inside
343  * finally clauses.
344  */
345 int
346 mono_get_block_region_notry (MonoCompile *cfg, int region)
347 {
348         if ((region & (0xf << 4)) == MONO_REGION_TRY) {
349                 MonoMethodHeader *header = cfg->header;
350                 
351                 /*
352                  * This can happen if a try clause is nested inside a finally clause.
353                  */
354                 int clause_index = (region >> 8) - 1;
355                 g_assert (clause_index >= 0 && clause_index < header->num_clauses);
356                 
357                 region = mono_find_block_region_notry (cfg, header->clauses [clause_index].try_offset);
358         }
359
360         return region;
361 }
362
363 MonoInst *
364 mono_find_spvar_for_region (MonoCompile *cfg, int region)
365 {
366         region = mono_get_block_region_notry (cfg, region);
367
368         return g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
369 }
370
371 static void
372 df_visit (MonoBasicBlock *start, int *dfn, MonoBasicBlock **array)
373 {
374         int i;
375
376         array [*dfn] = start;
377         /* g_print ("visit %d at %p (BB%ld)\n", *dfn, start->cil_code, start->block_num); */
378         for (i = 0; i < start->out_count; ++i) {
379                 if (start->out_bb [i]->dfn)
380                         continue;
381                 (*dfn)++;
382                 start->out_bb [i]->dfn = *dfn;
383                 start->out_bb [i]->df_parent = start;
384                 array [*dfn] = start->out_bb [i];
385                 df_visit (start->out_bb [i], dfn, array);
386         }
387 }
388
389 guint32
390 mono_reverse_branch_op (guint32 opcode)
391 {
392         static const int reverse_map [] = {
393                 CEE_BNE_UN, CEE_BLT, CEE_BLE, CEE_BGT, CEE_BGE,
394                 CEE_BEQ, CEE_BLT_UN, CEE_BLE_UN, CEE_BGT_UN, CEE_BGE_UN
395         };
396         static const int reverse_fmap [] = {
397                 OP_FBNE_UN, OP_FBLT, OP_FBLE, OP_FBGT, OP_FBGE,
398                 OP_FBEQ, OP_FBLT_UN, OP_FBLE_UN, OP_FBGT_UN, OP_FBGE_UN
399         };
400         static const int reverse_lmap [] = {
401                 OP_LBNE_UN, OP_LBLT, OP_LBLE, OP_LBGT, OP_LBGE,
402                 OP_LBEQ, OP_LBLT_UN, OP_LBLE_UN, OP_LBGT_UN, OP_LBGE_UN
403         };
404         static const int reverse_imap [] = {
405                 OP_IBNE_UN, OP_IBLT, OP_IBLE, OP_IBGT, OP_IBGE,
406                 OP_IBEQ, OP_IBLT_UN, OP_IBLE_UN, OP_IBGT_UN, OP_IBGE_UN
407         };
408                                 
409         if (opcode >= CEE_BEQ && opcode <= CEE_BLT_UN) {
410                 opcode = reverse_map [opcode - CEE_BEQ];
411         } else if (opcode >= OP_FBEQ && opcode <= OP_FBLT_UN) {
412                 opcode = reverse_fmap [opcode - OP_FBEQ];
413         } else if (opcode >= OP_LBEQ && opcode <= OP_LBLT_UN) {
414                 opcode = reverse_lmap [opcode - OP_LBEQ];
415         } else if (opcode >= OP_IBEQ && opcode <= OP_IBLT_UN) {
416                 opcode = reverse_imap [opcode - OP_IBEQ];
417         } else
418                 g_assert_not_reached ();
419
420         return opcode;
421 }
422
423 guint
424 mono_type_to_store_membase (MonoCompile *cfg, MonoType *type)
425 {
426         type = mini_get_underlying_type (cfg, type);
427
428 handle_enum:
429         switch (type->type) {
430         case MONO_TYPE_I1:
431         case MONO_TYPE_U1:
432                 return OP_STOREI1_MEMBASE_REG;
433         case MONO_TYPE_I2:
434         case MONO_TYPE_U2:
435                 return OP_STOREI2_MEMBASE_REG;
436         case MONO_TYPE_I4:
437         case MONO_TYPE_U4:
438                 return OP_STOREI4_MEMBASE_REG;
439         case MONO_TYPE_I:
440         case MONO_TYPE_U:
441         case MONO_TYPE_PTR:
442         case MONO_TYPE_FNPTR:
443                 return OP_STORE_MEMBASE_REG;
444         case MONO_TYPE_CLASS:
445         case MONO_TYPE_STRING:
446         case MONO_TYPE_OBJECT:
447         case MONO_TYPE_SZARRAY:
448         case MONO_TYPE_ARRAY:    
449                 return OP_STORE_MEMBASE_REG;
450         case MONO_TYPE_I8:
451         case MONO_TYPE_U8:
452                 return OP_STOREI8_MEMBASE_REG;
453         case MONO_TYPE_R4:
454                 return OP_STORER4_MEMBASE_REG;
455         case MONO_TYPE_R8:
456                 return OP_STORER8_MEMBASE_REG;
457         case MONO_TYPE_VALUETYPE:
458                 if (type->data.klass->enumtype) {
459                         type = mono_class_enum_basetype (type->data.klass);
460                         goto handle_enum;
461                 }
462                 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
463                         return OP_STOREX_MEMBASE;
464                 return OP_STOREV_MEMBASE;
465         case MONO_TYPE_TYPEDBYREF:
466                 return OP_STOREV_MEMBASE;
467         case MONO_TYPE_GENERICINST:
468                 type = &type->data.generic_class->container_class->byval_arg;
469                 goto handle_enum;
470         case MONO_TYPE_VAR:
471         case MONO_TYPE_MVAR:
472                 g_assert (mini_type_var_is_vt (cfg, type));
473                 return OP_STOREV_MEMBASE;
474         default:
475                 g_error ("unknown type 0x%02x in type_to_store_membase", type->type);
476         }
477         return -1;
478 }
479
480 guint
481 mono_type_to_load_membase (MonoCompile *cfg, MonoType *type)
482 {
483         type = mini_get_underlying_type (cfg, type);
484
485         switch (type->type) {
486         case MONO_TYPE_I1:
487                 return OP_LOADI1_MEMBASE;
488         case MONO_TYPE_U1:
489                 return OP_LOADU1_MEMBASE;
490         case MONO_TYPE_I2:
491                 return OP_LOADI2_MEMBASE;
492         case MONO_TYPE_U2:
493                 return OP_LOADU2_MEMBASE;
494         case MONO_TYPE_I4:
495                 return OP_LOADI4_MEMBASE;
496         case MONO_TYPE_U4:
497                 return OP_LOADU4_MEMBASE;
498         case MONO_TYPE_I:
499         case MONO_TYPE_U:
500         case MONO_TYPE_PTR:
501         case MONO_TYPE_FNPTR:
502                 return OP_LOAD_MEMBASE;
503         case MONO_TYPE_CLASS:
504         case MONO_TYPE_STRING:
505         case MONO_TYPE_OBJECT:
506         case MONO_TYPE_SZARRAY:
507         case MONO_TYPE_ARRAY:    
508                 return OP_LOAD_MEMBASE;
509         case MONO_TYPE_I8:
510         case MONO_TYPE_U8:
511                 return OP_LOADI8_MEMBASE;
512         case MONO_TYPE_R4:
513                 return OP_LOADR4_MEMBASE;
514         case MONO_TYPE_R8:
515                 return OP_LOADR8_MEMBASE;
516         case MONO_TYPE_VALUETYPE:
517                 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
518                         return OP_LOADX_MEMBASE;
519         case MONO_TYPE_TYPEDBYREF:
520                 return OP_LOADV_MEMBASE;
521         case MONO_TYPE_GENERICINST:
522                 if (mono_type_generic_inst_is_valuetype (type))
523                         return OP_LOADV_MEMBASE;
524                 else
525                         return OP_LOAD_MEMBASE;
526                 break;
527         case MONO_TYPE_VAR:
528         case MONO_TYPE_MVAR:
529                 g_assert (cfg->generic_sharing_context);
530                 g_assert (mini_type_var_is_vt (cfg, type));
531                 return OP_LOADV_MEMBASE;
532         default:
533                 g_error ("unknown type 0x%02x in type_to_load_membase", type->type);
534         }
535         return -1;
536 }
537
538 static guint
539 mini_type_to_ldind (MonoCompile* cfg, MonoType *type)
540 {
541         type = mini_get_underlying_type (cfg, type);
542         if (cfg->generic_sharing_context && !type->byref && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)) {
543                 g_assert (mini_type_var_is_vt (cfg, type));
544                 return CEE_LDOBJ;
545         }
546         return mono_type_to_ldind (type);
547 }
548
549 #ifndef DISABLE_JIT
550
551 guint
552 mini_type_to_stind (MonoCompile* cfg, MonoType *type)
553 {
554         type = mini_get_underlying_type (cfg, type);
555         if (cfg->generic_sharing_context && !type->byref && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)) {
556                 g_assert (mini_type_var_is_vt (cfg, type));
557                 return CEE_STOBJ;
558         }
559         return mono_type_to_stind (type);
560 }
561
562 int
563 mono_op_imm_to_op (int opcode)
564 {
565         switch (opcode) {
566         case OP_ADD_IMM:
567 #if SIZEOF_REGISTER == 4
568                 return OP_IADD;
569 #else
570                 return OP_LADD;
571 #endif
572         case OP_IADD_IMM:
573                 return OP_IADD;
574         case OP_LADD_IMM:
575                 return OP_LADD;
576         case OP_ISUB_IMM:
577                 return OP_ISUB;
578         case OP_LSUB_IMM:
579                 return OP_LSUB;
580         case OP_IMUL_IMM:
581                 return OP_IMUL;
582         case OP_AND_IMM:
583 #if SIZEOF_REGISTER == 4
584                 return OP_IAND;
585 #else
586                 return OP_LAND;
587 #endif
588         case OP_OR_IMM:
589 #if SIZEOF_REGISTER == 4
590                 return OP_IOR;
591 #else
592                 return OP_LOR;
593 #endif
594         case OP_XOR_IMM:
595 #if SIZEOF_REGISTER == 4
596                 return OP_IXOR;
597 #else
598                 return OP_LXOR;
599 #endif
600         case OP_IAND_IMM:
601                 return OP_IAND;
602         case OP_LAND_IMM:
603                 return OP_LAND;
604         case OP_IOR_IMM:
605                 return OP_IOR;
606         case OP_LOR_IMM:
607                 return OP_LOR;
608         case OP_IXOR_IMM:
609                 return OP_IXOR;
610         case OP_LXOR_IMM:
611                 return OP_LXOR;
612         case OP_ISHL_IMM:
613                 return OP_ISHL;
614         case OP_LSHL_IMM:
615                 return OP_LSHL;
616         case OP_ISHR_IMM:
617                 return OP_ISHR;
618         case OP_LSHR_IMM:
619                 return OP_LSHR;
620         case OP_ISHR_UN_IMM:
621                 return OP_ISHR_UN;
622         case OP_LSHR_UN_IMM:
623                 return OP_LSHR_UN;
624         case OP_IDIV_IMM:
625                 return OP_IDIV;
626         case OP_IDIV_UN_IMM:
627                 return OP_IDIV_UN;
628         case OP_IREM_UN_IMM:
629                 return OP_IREM_UN;
630         case OP_IREM_IMM:
631                 return OP_IREM;
632         case OP_LREM_IMM:
633                 return OP_LREM;
634         case OP_DIV_IMM:
635 #if SIZEOF_REGISTER == 4
636                 return OP_IDIV;
637 #else
638                 return OP_LDIV;
639 #endif
640         case OP_REM_IMM:
641 #if SIZEOF_REGISTER == 4
642                 return OP_IREM;
643 #else
644                 return OP_LREM;
645 #endif
646         case OP_ADDCC_IMM:
647                 return OP_ADDCC;
648         case OP_ADC_IMM:
649                 return OP_ADC;
650         case OP_SUBCC_IMM:
651                 return OP_SUBCC;
652         case OP_SBB_IMM:
653                 return OP_SBB;
654         case OP_IADC_IMM:
655                 return OP_IADC;
656         case OP_ISBB_IMM:
657                 return OP_ISBB;
658         case OP_COMPARE_IMM:
659                 return OP_COMPARE;
660         case OP_ICOMPARE_IMM:
661                 return OP_ICOMPARE;
662         case OP_LOCALLOC_IMM:
663                 return OP_LOCALLOC;
664         default:
665                 printf ("%s\n", mono_inst_name (opcode));
666                 g_assert_not_reached ();
667                 return -1;
668         }
669 }
670
671 /*
672  * mono_decompose_op_imm:
673  *
674  *   Replace the OP_.._IMM INS with its non IMM variant.
675  */
676 void
677 mono_decompose_op_imm (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins)
678 {
679         MonoInst *temp;
680
681         MONO_INST_NEW (cfg, temp, OP_ICONST);
682         temp->inst_c0 = ins->inst_imm;
683         temp->dreg = mono_alloc_ireg (cfg);
684         mono_bblock_insert_before_ins (bb, ins, temp);
685         ins->opcode = mono_op_imm_to_op (ins->opcode);
686         if (ins->opcode == OP_LOCALLOC)
687                 ins->sreg1 = temp->dreg;
688         else
689                 ins->sreg2 = temp->dreg;
690
691         bb->max_vreg = MAX (bb->max_vreg, cfg->next_vreg);
692 }
693
694 #endif
695
696 static void
697 set_vreg_to_inst (MonoCompile *cfg, int vreg, MonoInst *inst)
698 {
699         if (vreg >= cfg->vreg_to_inst_len) {
700                 MonoInst **tmp = cfg->vreg_to_inst;
701                 int size = cfg->vreg_to_inst_len;
702
703                 while (vreg >= cfg->vreg_to_inst_len)
704                         cfg->vreg_to_inst_len = cfg->vreg_to_inst_len ? cfg->vreg_to_inst_len * 2 : 32;
705                 cfg->vreg_to_inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * cfg->vreg_to_inst_len);
706                 if (size)
707                         memcpy (cfg->vreg_to_inst, tmp, size * sizeof (MonoInst*));
708         }
709         cfg->vreg_to_inst [vreg] = inst;
710 }
711
712 #define mono_type_is_long(type) (!(type)->byref && ((mono_type_get_underlying_type (type)->type == MONO_TYPE_I8) || (mono_type_get_underlying_type (type)->type == MONO_TYPE_U8)))
713 #define mono_type_is_float(type) (!(type)->byref && (((type)->type == MONO_TYPE_R8) || ((type)->type == MONO_TYPE_R4)))
714
715 #ifdef DISABLE_JIT
716
717 MonoInst*
718 mono_compile_create_var (MonoCompile *cfg, MonoType *type, int opcode)
719 {
720         return NULL;
721 }
722
723 #else
724
725 MonoInst*
726 mono_compile_create_var_for_vreg (MonoCompile *cfg, MonoType *type, int opcode, int vreg)
727 {
728         MonoInst *inst;
729         int num = cfg->num_varinfo;
730         gboolean regpair;
731
732         type = mini_get_underlying_type (cfg, type);
733
734         if ((num + 1) >= cfg->varinfo_count) {
735                 int orig_count = cfg->varinfo_count;
736                 cfg->varinfo_count = cfg->varinfo_count ? (cfg->varinfo_count * 2) : 32;
737                 cfg->varinfo = (MonoInst **)g_realloc (cfg->varinfo, sizeof (MonoInst*) * cfg->varinfo_count);
738                 cfg->vars = (MonoMethodVar *)g_realloc (cfg->vars, sizeof (MonoMethodVar) * cfg->varinfo_count);
739                 memset (&cfg->vars [orig_count], 0, (cfg->varinfo_count - orig_count) * sizeof (MonoMethodVar));
740         }
741
742         cfg->stat_allocate_var++;
743
744         MONO_INST_NEW (cfg, inst, opcode);
745         inst->inst_c0 = num;
746         inst->inst_vtype = type;
747         inst->klass = mono_class_from_mono_type (type);
748         type_to_eval_stack_type (cfg, type, inst);
749         /* if set to 1 the variable is native */
750         inst->backend.is_pinvoke = 0;
751         inst->dreg = vreg;
752
753         if (inst->klass->exception_type)
754                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD);
755
756         if (cfg->compute_gc_maps) {
757                 if (type->byref) {
758                         mono_mark_vreg_as_mp (cfg, vreg);
759                 } else {
760                         if ((MONO_TYPE_ISSTRUCT (type) && inst->klass->has_references) || mini_type_is_reference (cfg, type)) {
761                                 inst->flags |= MONO_INST_GC_TRACK;
762                                 mono_mark_vreg_as_ref (cfg, vreg);
763                         }
764                 }
765         }
766         
767         cfg->varinfo [num] = inst;
768
769         MONO_INIT_VARINFO (&cfg->vars [num], num);
770         MONO_VARINFO (cfg, num)->vreg = vreg;
771
772         if (vreg != -1)
773                 set_vreg_to_inst (cfg, vreg, inst);
774
775 #if SIZEOF_REGISTER == 4
776         if (mono_arch_is_soft_float ()) {
777                 regpair = mono_type_is_long (type) || mono_type_is_float (type);
778         } else {
779                 regpair = mono_type_is_long (type);
780         }
781 #else
782         regpair = FALSE;
783 #endif
784
785         if (regpair) {
786                 MonoInst *tree;
787
788                 /* 
789                  * These two cannot be allocated using create_var_for_vreg since that would
790                  * put it into the cfg->varinfo array, confusing many parts of the JIT.
791                  */
792
793                 /* 
794                  * Set flags to VOLATILE so SSA skips it.
795                  */
796
797                 if (cfg->verbose_level >= 4) {
798                         printf ("  Create LVAR R%d (R%d, R%d)\n", inst->dreg, inst->dreg + 1, inst->dreg + 2);
799                 }
800
801                 if (mono_arch_is_soft_float () && cfg->opt & MONO_OPT_SSA) {
802                         if (mono_type_is_float (type))
803                                 inst->flags = MONO_INST_VOLATILE;
804                 }
805
806                 /* Allocate a dummy MonoInst for the first vreg */
807                 MONO_INST_NEW (cfg, tree, OP_LOCAL);
808                 tree->dreg = inst->dreg + 1;
809                 if (cfg->opt & MONO_OPT_SSA)
810                         tree->flags = MONO_INST_VOLATILE;
811                 tree->inst_c0 = num;
812                 tree->type = STACK_I4;
813                 tree->inst_vtype = &mono_defaults.int32_class->byval_arg;
814                 tree->klass = mono_class_from_mono_type (tree->inst_vtype);
815
816                 set_vreg_to_inst (cfg, inst->dreg + 1, tree);
817
818                 /* Allocate a dummy MonoInst for the second vreg */
819                 MONO_INST_NEW (cfg, tree, OP_LOCAL);
820                 tree->dreg = inst->dreg + 2;
821                 if (cfg->opt & MONO_OPT_SSA)
822                         tree->flags = MONO_INST_VOLATILE;
823                 tree->inst_c0 = num;
824                 tree->type = STACK_I4;
825                 tree->inst_vtype = &mono_defaults.int32_class->byval_arg;
826                 tree->klass = mono_class_from_mono_type (tree->inst_vtype);
827
828                 set_vreg_to_inst (cfg, inst->dreg + 2, tree);
829         }
830
831         cfg->num_varinfo++;
832         if (cfg->verbose_level > 2)
833                 g_print ("created temp %d (R%d) of type %s\n", num, vreg, mono_type_get_name (type));
834         return inst;
835 }
836
837 MonoInst*
838 mono_compile_create_var (MonoCompile *cfg, MonoType *type, int opcode)
839 {
840         int dreg;
841         type = mini_get_underlying_type (cfg, type);
842
843         if (mono_type_is_long (type))
844                 dreg = mono_alloc_dreg (cfg, STACK_I8);
845         else if (mono_arch_is_soft_float () && mono_type_is_float (type))
846                 dreg = mono_alloc_dreg (cfg, STACK_R8);
847         else
848                 /* All the others are unified */
849                 dreg = mono_alloc_preg (cfg);
850
851         return mono_compile_create_var_for_vreg (cfg, type, opcode, dreg);
852 }
853
854 /*
855  * Transform a MonoInst into a load from the variable of index var_index.
856  */
857 void
858 mono_compile_make_var_load (MonoCompile *cfg, MonoInst *dest, gssize var_index)
859 {
860         memset (dest, 0, sizeof (MonoInst));
861         dest->inst_i0 = cfg->varinfo [var_index];
862         dest->opcode = mini_type_to_ldind (cfg, dest->inst_i0->inst_vtype);
863         type_to_eval_stack_type (cfg, dest->inst_i0->inst_vtype, dest);
864         dest->klass = dest->inst_i0->klass;
865 }
866
867 MonoInst*
868 mini_get_int_to_float_spill_area (MonoCompile *cfg)
869 {
870 #ifdef TARGET_X86
871         if (!cfg->iconv_raw_var) {
872                 cfg->iconv_raw_var = mono_compile_create_var (cfg, &mono_defaults.int32_class->byval_arg, OP_LOCAL);
873                 cfg->iconv_raw_var->flags |= MONO_INST_VOLATILE; /*FIXME, use the don't regalloc flag*/
874         }
875         return cfg->iconv_raw_var;
876 #else
877         return NULL;
878 #endif
879 }
880
881 #endif
882
883 void
884 mono_mark_vreg_as_ref (MonoCompile *cfg, int vreg)
885 {
886         if (vreg >= cfg->vreg_is_ref_len) {
887                 gboolean *tmp = cfg->vreg_is_ref;
888                 int size = cfg->vreg_is_ref_len;
889
890                 while (vreg >= cfg->vreg_is_ref_len)
891                         cfg->vreg_is_ref_len = cfg->vreg_is_ref_len ? cfg->vreg_is_ref_len * 2 : 32;
892                 cfg->vreg_is_ref = mono_mempool_alloc0 (cfg->mempool, sizeof (gboolean) * cfg->vreg_is_ref_len);
893                 if (size)
894                         memcpy (cfg->vreg_is_ref, tmp, size * sizeof (gboolean));
895         }
896         cfg->vreg_is_ref [vreg] = TRUE;
897 }       
898
899 void
900 mono_mark_vreg_as_mp (MonoCompile *cfg, int vreg)
901 {
902         if (vreg >= cfg->vreg_is_mp_len) {
903                 gboolean *tmp = cfg->vreg_is_mp;
904                 int size = cfg->vreg_is_mp_len;
905
906                 while (vreg >= cfg->vreg_is_mp_len)
907                         cfg->vreg_is_mp_len = cfg->vreg_is_mp_len ? cfg->vreg_is_mp_len * 2 : 32;
908                 cfg->vreg_is_mp = mono_mempool_alloc0 (cfg->mempool, sizeof (gboolean) * cfg->vreg_is_mp_len);
909                 if (size)
910                         memcpy (cfg->vreg_is_mp, tmp, size * sizeof (gboolean));
911         }
912         cfg->vreg_is_mp [vreg] = TRUE;
913 }       
914
915 static MonoType*
916 type_from_stack_type (MonoInst *ins) {
917         switch (ins->type) {
918         case STACK_I4: return &mono_defaults.int32_class->byval_arg;
919         case STACK_I8: return &mono_defaults.int64_class->byval_arg;
920         case STACK_PTR: return &mono_defaults.int_class->byval_arg;
921         case STACK_R8: return &mono_defaults.double_class->byval_arg;
922         case STACK_MP:
923                 /* 
924                  * this if used to be commented without any specific reason, but
925                  * it breaks #80235 when commented
926                  */
927                 if (ins->klass)
928                         return &ins->klass->this_arg;
929                 else
930                         return &mono_defaults.object_class->this_arg;
931         case STACK_OBJ:
932                 /* ins->klass may not be set for ldnull.
933                  * Also, if we have a boxed valuetype, we want an object lass,
934                  * not the valuetype class
935                  */
936                 if (ins->klass && !ins->klass->valuetype)
937                         return &ins->klass->byval_arg;
938                 return &mono_defaults.object_class->byval_arg;
939         case STACK_VTYPE: return &ins->klass->byval_arg;
940         default:
941                 g_error ("stack type %d to montype not handled\n", ins->type);
942         }
943         return NULL;
944 }
945
946 MonoType*
947 mono_type_from_stack_type (MonoInst *ins) {
948         return type_from_stack_type (ins);
949 }
950
951 /*
952  * mono_add_ins_to_end:
953  *
954  *   Same as MONO_ADD_INS, but add INST before any branches at the end of BB.
955  */
956 void
957 mono_add_ins_to_end (MonoBasicBlock *bb, MonoInst *inst)
958 {
959         int opcode;
960
961         if (!bb->code) {
962                 MONO_ADD_INS (bb, inst);
963                 return;
964         }
965
966         switch (bb->last_ins->opcode) {
967         case OP_BR:
968         case OP_BR_REG:
969         case CEE_BEQ:
970         case CEE_BGE:
971         case CEE_BGT:
972         case CEE_BLE:
973         case CEE_BLT:
974         case CEE_BNE_UN:
975         case CEE_BGE_UN:
976         case CEE_BGT_UN:
977         case CEE_BLE_UN:
978         case CEE_BLT_UN:
979         case OP_SWITCH:
980                 mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
981                 break;
982         default:
983                 if (MONO_IS_COND_BRANCH_OP (bb->last_ins)) {
984                         /* Need to insert the ins before the compare */
985                         if (bb->code == bb->last_ins) {
986                                 mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
987                                 return;
988                         }
989
990                         if (bb->code->next == bb->last_ins) {
991                                 /* Only two instructions */
992                                 opcode = bb->code->opcode;
993
994                                 if ((opcode == OP_COMPARE) || (opcode == OP_COMPARE_IMM) || (opcode == OP_ICOMPARE) || (opcode == OP_ICOMPARE_IMM) || (opcode == OP_FCOMPARE) || (opcode == OP_LCOMPARE) || (opcode == OP_LCOMPARE_IMM) || (opcode == OP_RCOMPARE)) {
995                                         /* NEW IR */
996                                         mono_bblock_insert_before_ins (bb, bb->code, inst);
997                                 } else {
998                                         mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
999                                 }
1000                         } else {
1001                                 opcode = bb->last_ins->prev->opcode;
1002
1003                                 if ((opcode == OP_COMPARE) || (opcode == OP_COMPARE_IMM) || (opcode == OP_ICOMPARE) || (opcode == OP_ICOMPARE_IMM) || (opcode == OP_FCOMPARE) || (opcode == OP_LCOMPARE) || (opcode == OP_LCOMPARE_IMM) || (opcode == OP_RCOMPARE)) {
1004                                         /* NEW IR */
1005                                         mono_bblock_insert_before_ins (bb, bb->last_ins->prev, inst);
1006                                 } else {
1007                                         mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
1008                                 }                                       
1009                         }
1010                 }
1011                 else
1012                         MONO_ADD_INS (bb, inst);
1013                 break;
1014         }
1015 }
1016
1017 void
1018 mono_create_jump_table (MonoCompile *cfg, MonoInst *label, MonoBasicBlock **bbs, int num_blocks)
1019 {
1020         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
1021         MonoJumpInfoBBTable *table;
1022
1023         table = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfoBBTable));
1024         table->table = bbs;
1025         table->table_size = num_blocks;
1026         
1027         ji->ip.label = label;
1028         ji->type = MONO_PATCH_INFO_SWITCH;
1029         ji->data.table = table;
1030         ji->next = cfg->patch_info;
1031         cfg->patch_info = ji;
1032 }
1033
1034 static MonoMethodSignature *
1035 mono_get_array_new_va_signature (int arity)
1036 {
1037         static GHashTable *sighash;
1038         MonoMethodSignature *res;
1039         int i;
1040
1041         mono_jit_lock ();
1042         if (!sighash) {
1043                 sighash = g_hash_table_new (NULL, NULL);
1044         }
1045         else if ((res = g_hash_table_lookup (sighash, GINT_TO_POINTER (arity)))) {
1046                 mono_jit_unlock ();
1047                 return res;
1048         }
1049
1050         res = mono_metadata_signature_alloc (mono_defaults.corlib, arity + 1);
1051
1052         res->pinvoke = 1;
1053         if (ARCH_VARARG_ICALLS)
1054                 /* Only set this only some archs since not all backends can handle varargs+pinvoke */
1055                 res->call_convention = MONO_CALL_VARARG;
1056
1057 #ifdef TARGET_WIN32
1058         res->call_convention = MONO_CALL_C;
1059 #endif
1060
1061         res->params [0] = &mono_defaults.int_class->byval_arg;  
1062         for (i = 0; i < arity; i++)
1063                 res->params [i + 1] = &mono_defaults.int_class->byval_arg;
1064
1065         res->ret = &mono_defaults.object_class->byval_arg;
1066
1067         g_hash_table_insert (sighash, GINT_TO_POINTER (arity), res);
1068         mono_jit_unlock ();
1069
1070         return res;
1071 }
1072
1073 MonoJitICallInfo *
1074 mono_get_array_new_va_icall (int rank)
1075 {
1076         MonoMethodSignature *esig;
1077         char icall_name [256];
1078         char *name;
1079         MonoJitICallInfo *info;
1080
1081         /* Need to register the icall so it gets an icall wrapper */
1082         sprintf (icall_name, "ves_array_new_va_%d", rank);
1083
1084         mono_jit_lock ();
1085         info = mono_find_jit_icall_by_name (icall_name);
1086         if (info == NULL) {
1087                 esig = mono_get_array_new_va_signature (rank);
1088                 name = g_strdup (icall_name);
1089                 info = mono_register_jit_icall (mono_array_new_va, name, esig, FALSE);
1090         }
1091         mono_jit_unlock ();
1092
1093         return info;
1094 }
1095
1096 gboolean
1097 mini_class_is_system_array (MonoClass *klass)
1098 {
1099         if (klass->parent == mono_defaults.array_class)
1100                 return TRUE;
1101         else
1102                 return FALSE;
1103 }
1104
1105 gboolean
1106 mini_assembly_can_skip_verification (MonoDomain *domain, MonoMethod *method)
1107 {
1108         MonoAssembly *assembly = method->klass->image->assembly;
1109         if (method->wrapper_type != MONO_WRAPPER_NONE && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
1110                 return FALSE;
1111         if (assembly->in_gac || assembly->image == mono_defaults.corlib)
1112                 return FALSE;
1113         if (mono_security_enabled ())
1114                 return FALSE;
1115         return mono_assembly_has_skip_verification (assembly);
1116 }
1117
1118 /*
1119  * mini_method_verify:
1120  * 
1121  * Verify the method using the new verfier.
1122  * 
1123  * Returns true if the method is invalid. 
1124  */
1125 static gboolean
1126 mini_method_verify (MonoCompile *cfg, MonoMethod *method, gboolean fail_compile)
1127 {
1128         GSList *tmp, *res;
1129         gboolean is_fulltrust;
1130         MonoLoaderError *error;
1131
1132         if (method->verification_success)
1133                 return FALSE;
1134
1135         if (!mono_verifier_is_enabled_for_method (method))
1136                 return FALSE;
1137
1138         /*skip verification implies the assembly must be */
1139         is_fulltrust = mono_verifier_is_method_full_trust (method) ||  mini_assembly_can_skip_verification (cfg->domain, method);
1140
1141         res = mono_method_verify_with_current_settings (method, cfg->skip_visibility, is_fulltrust);
1142
1143         if ((error = mono_loader_get_last_error ())) {
1144                 if (fail_compile)
1145                         cfg->exception_type = error->exception_type;
1146                 else
1147                         mono_loader_clear_error ();
1148                 if (res)
1149                         mono_free_verify_list (res);
1150                 return TRUE;
1151         }
1152
1153         if (res) { 
1154                 for (tmp = res; tmp; tmp = tmp->next) {
1155                         MonoVerifyInfoExtended *info = (MonoVerifyInfoExtended *)tmp->data;
1156                         if (info->info.status == MONO_VERIFY_ERROR) {
1157                                 if (fail_compile) {
1158                                 char *method_name = mono_method_full_name (method, TRUE);
1159                                         cfg->exception_type = info->exception_type;
1160                                         cfg->exception_message = g_strdup_printf ("Error verifying %s: %s", method_name, info->info.message);
1161                                         g_free (method_name);
1162                                 }
1163                                 mono_free_verify_list (res);
1164                                 return TRUE;
1165                         }
1166                         if (info->info.status == MONO_VERIFY_NOT_VERIFIABLE && (!is_fulltrust || info->exception_type == MONO_EXCEPTION_METHOD_ACCESS || info->exception_type == MONO_EXCEPTION_FIELD_ACCESS)) {
1167                                 if (fail_compile) {
1168                                         char *method_name = mono_method_full_name (method, TRUE);
1169                                         cfg->exception_type = info->exception_type;
1170                                         cfg->exception_message = g_strdup_printf ("Error verifying %s: %s", method_name, info->info.message);
1171                                         g_free (method_name);
1172                                 }
1173                                 mono_free_verify_list (res);
1174                                 return TRUE;
1175                         }
1176                 }
1177                 mono_free_verify_list (res);
1178         }
1179         method->verification_success = 1;
1180         return FALSE;
1181 }
1182
1183 /*Returns true if something went wrong*/
1184 gboolean
1185 mono_compile_is_broken (MonoCompile *cfg, MonoMethod *method, gboolean fail_compile)
1186 {
1187         MonoMethod *method_definition = method;
1188         gboolean dont_verify = method->klass->image->assembly->corlib_internal;
1189
1190         while (method_definition->is_inflated) {
1191                 MonoMethodInflated *imethod = (MonoMethodInflated *) method_definition;
1192                 method_definition = imethod->declaring;
1193         }
1194
1195         return !dont_verify && mini_method_verify (cfg, method_definition, fail_compile);
1196 }
1197
1198 static void
1199 mono_dynamic_code_hash_insert (MonoDomain *domain, MonoMethod *method, MonoJitDynamicMethodInfo *ji)
1200 {
1201         if (!domain_jit_info (domain)->dynamic_code_hash)
1202                 domain_jit_info (domain)->dynamic_code_hash = g_hash_table_new (NULL, NULL);
1203         g_hash_table_insert (domain_jit_info (domain)->dynamic_code_hash, method, ji);
1204 }
1205
1206 static MonoJitDynamicMethodInfo*
1207 mono_dynamic_code_hash_lookup (MonoDomain *domain, MonoMethod *method)
1208 {
1209         MonoJitDynamicMethodInfo *res;
1210
1211         if (domain_jit_info (domain)->dynamic_code_hash)
1212                 res = g_hash_table_lookup (domain_jit_info (domain)->dynamic_code_hash, method);
1213         else
1214                 res = NULL;
1215         return res;
1216 }
1217
1218 typedef struct {
1219         MonoClass *vtype;
1220         GList *active, *inactive;
1221         GSList *slots;
1222 } StackSlotInfo;
1223
1224 static gint 
1225 compare_by_interval_start_pos_func (gconstpointer a, gconstpointer b)
1226 {
1227         MonoMethodVar *v1 = (MonoMethodVar*)a;
1228         MonoMethodVar *v2 = (MonoMethodVar*)b;
1229
1230         if (v1 == v2)
1231                 return 0;
1232         else if (v1->interval->range && v2->interval->range)
1233                 return v1->interval->range->from - v2->interval->range->from;
1234         else if (v1->interval->range)
1235                 return -1;
1236         else
1237                 return 1;
1238 }
1239
1240 #ifndef DISABLE_JIT
1241
1242 #if 0
1243 #define LSCAN_DEBUG(a) do { a; } while (0)
1244 #else
1245 #define LSCAN_DEBUG(a)
1246 #endif
1247
1248 static gint32*
1249 mono_allocate_stack_slots2 (MonoCompile *cfg, gboolean backward, guint32 *stack_size, guint32 *stack_align)
1250 {
1251         int i, slot, offset, size;
1252         guint32 align;
1253         MonoMethodVar *vmv;
1254         MonoInst *inst;
1255         gint32 *offsets;
1256         GList *vars = NULL, *l, *unhandled;
1257         StackSlotInfo *scalar_stack_slots, *vtype_stack_slots, *slot_info;
1258         MonoType *t;
1259         int nvtypes;
1260         gboolean reuse_slot;
1261
1262         LSCAN_DEBUG (printf ("Allocate Stack Slots 2 for %s:\n", mono_method_full_name (cfg->method, TRUE)));
1263
1264         scalar_stack_slots = mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * MONO_TYPE_PINNED);
1265         vtype_stack_slots = NULL;
1266         nvtypes = 0;
1267
1268         offsets = mono_mempool_alloc (cfg->mempool, sizeof (gint32) * cfg->num_varinfo);
1269         for (i = 0; i < cfg->num_varinfo; ++i)
1270                 offsets [i] = -1;
1271
1272         for (i = cfg->locals_start; i < cfg->num_varinfo; i++) {
1273                 inst = cfg->varinfo [i];
1274                 vmv = MONO_VARINFO (cfg, i);
1275
1276                 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR || inst->opcode == OP_REGOFFSET)
1277                         continue;
1278
1279                 vars = g_list_prepend (vars, vmv);
1280         }
1281
1282         vars = g_list_sort (g_list_copy (vars), compare_by_interval_start_pos_func);
1283
1284         /* Sanity check */
1285         /*
1286         i = 0;
1287         for (unhandled = vars; unhandled; unhandled = unhandled->next) {
1288                 MonoMethodVar *current = unhandled->data;
1289
1290                 if (current->interval->range) {
1291                         g_assert (current->interval->range->from >= i);
1292                         i = current->interval->range->from;
1293                 }
1294         }
1295         */
1296
1297         offset = 0;
1298         *stack_align = 0;
1299         for (unhandled = vars; unhandled; unhandled = unhandled->next) {
1300                 MonoMethodVar *current = unhandled->data;
1301
1302                 vmv = current;
1303                 inst = cfg->varinfo [vmv->idx];
1304
1305                 t = mono_type_get_underlying_type (inst->inst_vtype);
1306                 if (cfg->gsharedvt && mini_is_gsharedvt_variable_type (cfg, t))
1307                         continue;
1308
1309                 /* inst->backend.is_pinvoke indicates native sized value types, this is used by the
1310                 * pinvoke wrappers when they call functions returning structures */
1311                 if (inst->backend.is_pinvoke && MONO_TYPE_ISSTRUCT (t) && t->type != MONO_TYPE_TYPEDBYREF) {
1312                         size = mono_class_native_size (mono_class_from_mono_type (t), &align);
1313                 }
1314                 else {
1315                         int ialign;
1316
1317                         size = mini_type_stack_size (NULL, t, &ialign);
1318                         align = ialign;
1319
1320                         if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (t)))
1321                                 align = 16;
1322                 }
1323
1324                 reuse_slot = TRUE;
1325                 if (cfg->disable_reuse_stack_slots)
1326                         reuse_slot = FALSE;
1327
1328                 t = mini_get_underlying_type (cfg, t);
1329                 switch (t->type) {
1330                 case MONO_TYPE_GENERICINST:
1331                         if (!mono_type_generic_inst_is_valuetype (t)) {
1332                                 slot_info = &scalar_stack_slots [t->type];
1333                                 break;
1334                         }
1335                         /* Fall through */
1336                 case MONO_TYPE_VALUETYPE:
1337                         if (!vtype_stack_slots)
1338                                 vtype_stack_slots = mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * 256);
1339                         for (i = 0; i < nvtypes; ++i)
1340                                 if (t->data.klass == vtype_stack_slots [i].vtype)
1341                                         break;
1342                         if (i < nvtypes)
1343                                 slot_info = &vtype_stack_slots [i];
1344                         else {
1345                                 g_assert (nvtypes < 256);
1346                                 vtype_stack_slots [nvtypes].vtype = t->data.klass;
1347                                 slot_info = &vtype_stack_slots [nvtypes];
1348                                 nvtypes ++;
1349                         }
1350                         if (cfg->disable_reuse_ref_stack_slots)
1351                                 reuse_slot = FALSE;
1352                         break;
1353
1354                 case MONO_TYPE_PTR:
1355                 case MONO_TYPE_I:
1356                 case MONO_TYPE_U:
1357 #if SIZEOF_VOID_P == 4
1358                 case MONO_TYPE_I4:
1359 #else
1360                 case MONO_TYPE_I8:
1361 #endif
1362                         if (cfg->disable_ref_noref_stack_slot_share) {
1363                                 slot_info = &scalar_stack_slots [MONO_TYPE_I];
1364                                 break;
1365                         }
1366                         /* Fall through */
1367
1368                 case MONO_TYPE_CLASS:
1369                 case MONO_TYPE_OBJECT:
1370                 case MONO_TYPE_ARRAY:
1371                 case MONO_TYPE_SZARRAY:
1372                 case MONO_TYPE_STRING:
1373                         /* Share non-float stack slots of the same size */
1374                         slot_info = &scalar_stack_slots [MONO_TYPE_CLASS];
1375                         if (cfg->disable_reuse_ref_stack_slots)
1376                                 reuse_slot = FALSE;
1377                         break;
1378
1379                 default:
1380                         slot_info = &scalar_stack_slots [t->type];
1381                 }
1382
1383                 slot = 0xffffff;
1384                 if (cfg->comp_done & MONO_COMP_LIVENESS) {
1385                         int pos;
1386                         gboolean changed;
1387
1388                         //printf ("START  %2d %08x %08x\n",  vmv->idx, vmv->range.first_use.abs_pos, vmv->range.last_use.abs_pos);
1389
1390                         if (!current->interval->range) {
1391                                 if (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))
1392                                         pos = ~0;
1393                                 else {
1394                                         /* Dead */
1395                                         inst->flags |= MONO_INST_IS_DEAD;
1396                                         continue;
1397                                 }
1398                         }
1399                         else
1400                                 pos = current->interval->range->from;
1401
1402                         LSCAN_DEBUG (printf ("process R%d ", inst->dreg));
1403                         if (current->interval->range)
1404                                 LSCAN_DEBUG (mono_linterval_print (current->interval));
1405                         LSCAN_DEBUG (printf ("\n"));
1406
1407                         /* Check for intervals in active which expired or inactive */
1408                         changed = TRUE;
1409                         /* FIXME: Optimize this */
1410                         while (changed) {
1411                                 changed = FALSE;
1412                                 for (l = slot_info->active; l != NULL; l = l->next) {
1413                                         MonoMethodVar *v = (MonoMethodVar*)l->data;
1414
1415                                         if (v->interval->last_range->to < pos) {
1416                                                 slot_info->active = g_list_delete_link (slot_info->active, l);
1417                                                 slot_info->slots = g_slist_prepend_mempool (cfg->mempool, slot_info->slots, GINT_TO_POINTER (offsets [v->idx]));
1418                                                 LSCAN_DEBUG (printf ("Interval R%d has expired, adding 0x%x to slots\n", cfg->varinfo [v->idx]->dreg, offsets [v->idx]));
1419                                                 changed = TRUE;
1420                                                 break;
1421                                         }
1422                                         else if (!mono_linterval_covers (v->interval, pos)) {
1423                                                 slot_info->inactive = g_list_append (slot_info->inactive, v);
1424                                                 slot_info->active = g_list_delete_link (slot_info->active, l);
1425                                                 LSCAN_DEBUG (printf ("Interval R%d became inactive\n", cfg->varinfo [v->idx]->dreg));
1426                                                 changed = TRUE;
1427                                                 break;
1428                                         }
1429                                 }
1430                         }
1431
1432                         /* Check for intervals in inactive which expired or active */
1433                         changed = TRUE;
1434                         /* FIXME: Optimize this */
1435                         while (changed) {
1436                                 changed = FALSE;
1437                                 for (l = slot_info->inactive; l != NULL; l = l->next) {
1438                                         MonoMethodVar *v = (MonoMethodVar*)l->data;
1439
1440                                         if (v->interval->last_range->to < pos) {
1441                                                 slot_info->inactive = g_list_delete_link (slot_info->inactive, l);
1442                                                 // FIXME: Enabling this seems to cause impossible to debug crashes
1443                                                 //slot_info->slots = g_slist_prepend_mempool (cfg->mempool, slot_info->slots, GINT_TO_POINTER (offsets [v->idx]));
1444                                                 LSCAN_DEBUG (printf ("Interval R%d has expired, adding 0x%x to slots\n", cfg->varinfo [v->idx]->dreg, offsets [v->idx]));
1445                                                 changed = TRUE;
1446                                                 break;
1447                                         }
1448                                         else if (mono_linterval_covers (v->interval, pos)) {
1449                                                 slot_info->active = g_list_append (slot_info->active, v);
1450                                                 slot_info->inactive = g_list_delete_link (slot_info->inactive, l);
1451                                                 LSCAN_DEBUG (printf ("\tInterval R%d became active\n", cfg->varinfo [v->idx]->dreg));
1452                                                 changed = TRUE;
1453                                                 break;
1454                                         }
1455                                 }
1456                         }
1457
1458                         /* 
1459                          * This also handles the case when the variable is used in an
1460                          * exception region, as liveness info is not computed there.
1461                          */
1462                         /* 
1463                          * FIXME: All valuetypes are marked as INDIRECT because of LDADDR
1464                          * opcodes.
1465                          */
1466                         if (! (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
1467                                 if (slot_info->slots) {
1468                                         slot = GPOINTER_TO_INT (slot_info->slots->data);
1469
1470                                         slot_info->slots = slot_info->slots->next;
1471                                 }
1472
1473                                 /* FIXME: We might want to consider the inactive intervals as well if slot_info->slots is empty */
1474
1475                                 slot_info->active = mono_varlist_insert_sorted (cfg, slot_info->active, vmv, TRUE);
1476                         }
1477                 }
1478
1479 #if 0
1480                 {
1481                         static int count = 0;
1482                         count ++;
1483
1484                         if (count == atoi (g_getenv ("COUNT3")))
1485                                 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
1486                         if (count > atoi (g_getenv ("COUNT3")))
1487                                 slot = 0xffffff;
1488                         else {
1489                                 mono_print_ins (inst);
1490                                 }
1491                 }
1492 #endif
1493
1494                 LSCAN_DEBUG (printf ("R%d %s -> 0x%x\n", inst->dreg, mono_type_full_name (t), slot));
1495
1496                 if (inst->flags & MONO_INST_LMF) {
1497                         size = sizeof (MonoLMF);
1498                         align = sizeof (mgreg_t);
1499                         reuse_slot = FALSE;
1500                 }
1501
1502                 if (!reuse_slot)
1503                         slot = 0xffffff;
1504
1505                 if (slot == 0xffffff) {
1506                         /*
1507                          * Allways allocate valuetypes to sizeof (gpointer) to allow more
1508                          * efficient copying (and to work around the fact that OP_MEMCPY
1509                          * and OP_MEMSET ignores alignment).
1510                          */
1511                         if (MONO_TYPE_ISSTRUCT (t)) {
1512                                 align = MAX (align, sizeof (gpointer));
1513                                 align = MAX (align, mono_class_min_align (mono_class_from_mono_type (t)));
1514                         }
1515
1516                         if (backward) {
1517                                 offset += size;
1518                                 offset += align - 1;
1519                                 offset &= ~(align - 1);
1520                                 slot = offset;
1521                         }
1522                         else {
1523                                 offset += align - 1;
1524                                 offset &= ~(align - 1);
1525                                 slot = offset;
1526                                 offset += size;
1527                         }
1528
1529                         if (*stack_align == 0)
1530                                 *stack_align = align;
1531                 }
1532
1533                 offsets [vmv->idx] = slot;
1534         }
1535         g_list_free (vars);
1536         for (i = 0; i < MONO_TYPE_PINNED; ++i) {
1537                 if (scalar_stack_slots [i].active)
1538                         g_list_free (scalar_stack_slots [i].active);
1539         }
1540         for (i = 0; i < nvtypes; ++i) {
1541                 if (vtype_stack_slots [i].active)
1542                         g_list_free (vtype_stack_slots [i].active);
1543         }
1544
1545         cfg->stat_locals_stack_size += offset;
1546
1547         *stack_size = offset;
1548         return offsets;
1549 }
1550
1551 /*
1552  *  mono_allocate_stack_slots:
1553  *
1554  *  Allocate stack slots for all non register allocated variables using a
1555  * linear scan algorithm.
1556  * Returns: an array of stack offsets.
1557  * STACK_SIZE is set to the amount of stack space needed.
1558  * STACK_ALIGN is set to the alignment needed by the locals area.
1559  */
1560 gint32*
1561 mono_allocate_stack_slots (MonoCompile *cfg, gboolean backward, guint32 *stack_size, guint32 *stack_align)
1562 {
1563         int i, slot, offset, size;
1564         guint32 align;
1565         MonoMethodVar *vmv;
1566         MonoInst *inst;
1567         gint32 *offsets;
1568         GList *vars = NULL, *l;
1569         StackSlotInfo *scalar_stack_slots, *vtype_stack_slots, *slot_info;
1570         MonoType *t;
1571         int nvtypes;
1572         gboolean reuse_slot;
1573
1574         if ((cfg->num_varinfo > 0) && MONO_VARINFO (cfg, 0)->interval)
1575                 return mono_allocate_stack_slots2 (cfg, backward, stack_size, stack_align);
1576
1577         scalar_stack_slots = mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * MONO_TYPE_PINNED);
1578         vtype_stack_slots = NULL;
1579         nvtypes = 0;
1580
1581         offsets = mono_mempool_alloc (cfg->mempool, sizeof (gint32) * cfg->num_varinfo);
1582         for (i = 0; i < cfg->num_varinfo; ++i)
1583                 offsets [i] = -1;
1584
1585         for (i = cfg->locals_start; i < cfg->num_varinfo; i++) {
1586                 inst = cfg->varinfo [i];
1587                 vmv = MONO_VARINFO (cfg, i);
1588
1589                 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR || inst->opcode == OP_REGOFFSET)
1590                         continue;
1591
1592                 vars = g_list_prepend (vars, vmv);
1593         }
1594
1595         vars = mono_varlist_sort (cfg, vars, 0);
1596         offset = 0;
1597         *stack_align = sizeof(mgreg_t);
1598         for (l = vars; l; l = l->next) {
1599                 vmv = l->data;
1600                 inst = cfg->varinfo [vmv->idx];
1601
1602                 t = mono_type_get_underlying_type (inst->inst_vtype);
1603                 if (cfg->gsharedvt && mini_is_gsharedvt_variable_type (cfg, t))
1604                         continue;
1605
1606                 /* inst->backend.is_pinvoke indicates native sized value types, this is used by the
1607                 * pinvoke wrappers when they call functions returning structures */
1608                 if (inst->backend.is_pinvoke && MONO_TYPE_ISSTRUCT (t) && t->type != MONO_TYPE_TYPEDBYREF) {
1609                         size = mono_class_native_size (mono_class_from_mono_type (t), &align);
1610                 } else {
1611                         int ialign;
1612
1613                         size = mini_type_stack_size (NULL, t, &ialign);
1614                         align = ialign;
1615
1616                         if (mono_class_from_mono_type (t)->exception_type)
1617                                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD);
1618
1619                         if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (t)))
1620                                 align = 16;
1621                 }
1622
1623                 reuse_slot = TRUE;
1624                 if (cfg->disable_reuse_stack_slots)
1625                         reuse_slot = FALSE;
1626
1627                 t = mini_get_underlying_type (cfg, t);
1628                 switch (t->type) {
1629                 case MONO_TYPE_GENERICINST:
1630                         if (!mono_type_generic_inst_is_valuetype (t)) {
1631                                 slot_info = &scalar_stack_slots [t->type];
1632                                 break;
1633                         }
1634                         /* Fall through */
1635                 case MONO_TYPE_VALUETYPE:
1636                         if (!vtype_stack_slots)
1637                                 vtype_stack_slots = mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * 256);
1638                         for (i = 0; i < nvtypes; ++i)
1639                                 if (t->data.klass == vtype_stack_slots [i].vtype)
1640                                         break;
1641                         if (i < nvtypes)
1642                                 slot_info = &vtype_stack_slots [i];
1643                         else {
1644                                 g_assert (nvtypes < 256);
1645                                 vtype_stack_slots [nvtypes].vtype = t->data.klass;
1646                                 slot_info = &vtype_stack_slots [nvtypes];
1647                                 nvtypes ++;
1648                         }
1649                         if (cfg->disable_reuse_ref_stack_slots)
1650                                 reuse_slot = FALSE;
1651                         break;
1652
1653                 case MONO_TYPE_PTR:
1654                 case MONO_TYPE_I:
1655                 case MONO_TYPE_U:
1656 #if SIZEOF_VOID_P == 4
1657                 case MONO_TYPE_I4:
1658 #else
1659                 case MONO_TYPE_I8:
1660 #endif
1661                         if (cfg->disable_ref_noref_stack_slot_share) {
1662                                 slot_info = &scalar_stack_slots [MONO_TYPE_I];
1663                                 break;
1664                         }
1665                         /* Fall through */
1666
1667                 case MONO_TYPE_CLASS:
1668                 case MONO_TYPE_OBJECT:
1669                 case MONO_TYPE_ARRAY:
1670                 case MONO_TYPE_SZARRAY:
1671                 case MONO_TYPE_STRING:
1672                         /* Share non-float stack slots of the same size */
1673                         slot_info = &scalar_stack_slots [MONO_TYPE_CLASS];
1674                         if (cfg->disable_reuse_ref_stack_slots)
1675                                 reuse_slot = FALSE;
1676                         break;
1677                 case MONO_TYPE_VAR:
1678                 case MONO_TYPE_MVAR:
1679                         slot_info = &scalar_stack_slots [t->type];
1680                         break;
1681                 default:
1682                         slot_info = &scalar_stack_slots [t->type];
1683                         break;
1684                 }
1685
1686                 slot = 0xffffff;
1687                 if (cfg->comp_done & MONO_COMP_LIVENESS) {
1688                         //printf ("START  %2d %08x %08x\n",  vmv->idx, vmv->range.first_use.abs_pos, vmv->range.last_use.abs_pos);
1689                         
1690                         /* expire old intervals in active */
1691                         while (slot_info->active) {
1692                                 MonoMethodVar *amv = (MonoMethodVar *)slot_info->active->data;
1693
1694                                 if (amv->range.last_use.abs_pos > vmv->range.first_use.abs_pos)
1695                                         break;
1696
1697                                 //printf ("EXPIR  %2d %08x %08x C%d R%d\n", amv->idx, amv->range.first_use.abs_pos, amv->range.last_use.abs_pos, amv->spill_costs, amv->reg);
1698
1699                                 slot_info->active = g_list_delete_link (slot_info->active, slot_info->active);
1700                                 slot_info->slots = g_slist_prepend_mempool (cfg->mempool, slot_info->slots, GINT_TO_POINTER (offsets [amv->idx]));
1701                         }
1702
1703                         /* 
1704                          * This also handles the case when the variable is used in an
1705                          * exception region, as liveness info is not computed there.
1706                          */
1707                         /* 
1708                          * FIXME: All valuetypes are marked as INDIRECT because of LDADDR
1709                          * opcodes.
1710                          */
1711                         if (! (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
1712                                 if (slot_info->slots) {
1713                                         slot = GPOINTER_TO_INT (slot_info->slots->data);
1714
1715                                         slot_info->slots = slot_info->slots->next;
1716                                 }
1717
1718                                 slot_info->active = mono_varlist_insert_sorted (cfg, slot_info->active, vmv, TRUE);
1719                         }
1720                 }
1721
1722                 {
1723                         static int count = 0;
1724                         count ++;
1725
1726                         /*
1727                         if (count == atoi (g_getenv ("COUNT")))
1728                                 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
1729                         if (count > atoi (g_getenv ("COUNT")))
1730                                 slot = 0xffffff;
1731                         else {
1732                                 mono_print_ins (inst);
1733                                 }
1734                         */
1735                 }
1736
1737                 if (inst->flags & MONO_INST_LMF) {
1738                         /*
1739                          * This variable represents a MonoLMF structure, which has no corresponding
1740                          * CLR type, so hard-code its size/alignment.
1741                          */
1742                         size = sizeof (MonoLMF);
1743                         align = sizeof (mgreg_t);
1744                         reuse_slot = FALSE;
1745                 }
1746
1747                 if (!reuse_slot)
1748                         slot = 0xffffff;
1749
1750                 if (slot == 0xffffff) {
1751                         /*
1752                          * Allways allocate valuetypes to sizeof (gpointer) to allow more
1753                          * efficient copying (and to work around the fact that OP_MEMCPY
1754                          * and OP_MEMSET ignores alignment).
1755                          */
1756                         if (MONO_TYPE_ISSTRUCT (t)) {
1757                                 align = MAX (align, sizeof (gpointer));
1758                                 align = MAX (align, mono_class_min_align (mono_class_from_mono_type (t)));
1759                                 /* 
1760                                  * Align the size too so the code generated for passing vtypes in
1761                                  * registers doesn't overwrite random locals.
1762                                  */
1763                                 size = (size + (align - 1)) & ~(align -1);
1764                         }
1765
1766                         if (backward) {
1767                                 offset += size;
1768                                 offset += align - 1;
1769                                 offset &= ~(align - 1);
1770                                 slot = offset;
1771                         }
1772                         else {
1773                                 offset += align - 1;
1774                                 offset &= ~(align - 1);
1775                                 slot = offset;
1776                                 offset += size;
1777                         }
1778
1779                         *stack_align = MAX (*stack_align, align);
1780                 }
1781
1782                 offsets [vmv->idx] = slot;
1783         }
1784         g_list_free (vars);
1785         for (i = 0; i < MONO_TYPE_PINNED; ++i) {
1786                 if (scalar_stack_slots [i].active)
1787                         g_list_free (scalar_stack_slots [i].active);
1788         }
1789         for (i = 0; i < nvtypes; ++i) {
1790                 if (vtype_stack_slots [i].active)
1791                         g_list_free (vtype_stack_slots [i].active);
1792         }
1793
1794         cfg->stat_locals_stack_size += offset;
1795
1796         *stack_size = offset;
1797         return offsets;
1798 }
1799
1800 #else
1801
1802 gint32*
1803 mono_allocate_stack_slots (MonoCompile *cfg, gboolean backward, guint32 *stack_size, guint32 *stack_align)
1804 {
1805         g_assert_not_reached ();
1806         return NULL;
1807 }
1808
1809 #endif /* DISABLE_JIT */
1810
1811 #define EMUL_HIT_SHIFT 3
1812 #define EMUL_HIT_MASK ((1 << EMUL_HIT_SHIFT) - 1)
1813 /* small hit bitmap cache */
1814 static mono_byte emul_opcode_hit_cache [(OP_LAST>>EMUL_HIT_SHIFT) + 1] = {0};
1815 static short emul_opcode_num = 0;
1816 static short emul_opcode_alloced = 0;
1817 static short *emul_opcode_opcodes;
1818 static MonoJitICallInfo **emul_opcode_map;
1819
1820 MonoJitICallInfo *
1821 mono_find_jit_opcode_emulation (int opcode)
1822 {
1823         g_assert (opcode >= 0 && opcode <= OP_LAST);
1824         if (emul_opcode_hit_cache [opcode >> (EMUL_HIT_SHIFT + 3)] & (1 << (opcode & EMUL_HIT_MASK))) {
1825                 int i;
1826                 for (i = 0; i < emul_opcode_num; ++i) {
1827                         if (emul_opcode_opcodes [i] == opcode)
1828                                 return emul_opcode_map [i];
1829                 }
1830         }
1831         return NULL;
1832 }
1833
1834 void
1835 mini_register_opcode_emulation (int opcode, const char *name, const char *sigstr, gpointer func, const char *symbol, gboolean no_throw)
1836 {
1837         MonoJitICallInfo *info;
1838         MonoMethodSignature *sig = mono_create_icall_signature (sigstr);
1839
1840         g_assert (!sig->hasthis);
1841         g_assert (sig->param_count < 3);
1842
1843         /* Opcode emulation functions are assumed to don't call mono_raise_exception () */
1844         info = mono_register_jit_icall_full (func, name, sig, no_throw, TRUE, symbol);
1845
1846         if (emul_opcode_num >= emul_opcode_alloced) {
1847                 int incr = emul_opcode_alloced? emul_opcode_alloced/2: 16;
1848                 emul_opcode_alloced += incr;
1849                 emul_opcode_map = g_realloc (emul_opcode_map, sizeof (emul_opcode_map [0]) * emul_opcode_alloced);
1850                 emul_opcode_opcodes = g_realloc (emul_opcode_opcodes, sizeof (emul_opcode_opcodes [0]) * emul_opcode_alloced);
1851         }
1852         emul_opcode_map [emul_opcode_num] = info;
1853         emul_opcode_opcodes [emul_opcode_num] = opcode;
1854         emul_opcode_num++;
1855         emul_opcode_hit_cache [opcode >> (EMUL_HIT_SHIFT + 3)] |= (1 << (opcode & EMUL_HIT_MASK));
1856 }
1857
1858 static void
1859 print_dfn (MonoCompile *cfg) {
1860         int i, j;
1861         char *code;
1862         MonoBasicBlock *bb;
1863         MonoInst *c;
1864
1865         {
1866                 char *method_name = mono_method_full_name (cfg->method, TRUE);
1867                 g_print ("IR code for method %s\n", method_name);
1868                 g_free (method_name);
1869         }
1870
1871         for (i = 0; i < cfg->num_bblocks; ++i) {
1872                 bb = cfg->bblocks [i];
1873                 /*if (bb->cil_code) {
1874                         char* code1, *code2;
1875                         code1 = mono_disasm_code_one (NULL, cfg->method, bb->cil_code, NULL);
1876                         if (bb->last_ins->cil_code)
1877                                 code2 = mono_disasm_code_one (NULL, cfg->method, bb->last_ins->cil_code, NULL);
1878                         else
1879                                 code2 = g_strdup ("");
1880
1881                         code1 [strlen (code1) - 1] = 0;
1882                         code = g_strdup_printf ("%s -> %s", code1, code2);
1883                         g_free (code1);
1884                         g_free (code2);
1885                 } else*/
1886                         code = g_strdup ("\n");
1887                 g_print ("\nBB%d (%d) (len: %d): %s", bb->block_num, i, bb->cil_length, code);
1888                 MONO_BB_FOR_EACH_INS (bb, c) {
1889                         mono_print_ins_index (-1, c);
1890                 }
1891
1892                 g_print ("\tprev:");
1893                 for (j = 0; j < bb->in_count; ++j) {
1894                         g_print (" BB%d", bb->in_bb [j]->block_num);
1895                 }
1896                 g_print ("\t\tsucc:");
1897                 for (j = 0; j < bb->out_count; ++j) {
1898                         g_print (" BB%d", bb->out_bb [j]->block_num);
1899                 }
1900                 g_print ("\n\tidom: BB%d\n", bb->idom? bb->idom->block_num: -1);
1901
1902                 if (bb->idom)
1903                         g_assert (mono_bitset_test_fast (bb->dominators, bb->idom->dfn));
1904
1905                 if (bb->dominators)
1906                         mono_blockset_print (cfg, bb->dominators, "\tdominators", bb->idom? bb->idom->dfn: -1);
1907                 if (bb->dfrontier)
1908                         mono_blockset_print (cfg, bb->dfrontier, "\tdfrontier", -1);
1909                 g_free (code);
1910         }
1911
1912         g_print ("\n");
1913 }
1914
1915 void
1916 mono_bblock_add_inst (MonoBasicBlock *bb, MonoInst *inst)
1917 {
1918         MONO_ADD_INS (bb, inst);
1919 }
1920
1921 void
1922 mono_bblock_insert_after_ins (MonoBasicBlock *bb, MonoInst *ins, MonoInst *ins_to_insert)
1923 {
1924         if (ins == NULL) {
1925                 ins = bb->code;
1926                 bb->code = ins_to_insert;
1927
1928                 /* Link with next */
1929                 ins_to_insert->next = ins;
1930                 if (ins)
1931                         ins->prev = ins_to_insert;
1932
1933                 if (bb->last_ins == NULL)
1934                         bb->last_ins = ins_to_insert;
1935         } else {
1936                 /* Link with next */
1937                 ins_to_insert->next = ins->next;
1938                 if (ins->next)
1939                         ins->next->prev = ins_to_insert;
1940
1941                 /* Link with previous */
1942                 ins->next = ins_to_insert;
1943                 ins_to_insert->prev = ins;
1944
1945                 if (bb->last_ins == ins)
1946                         bb->last_ins = ins_to_insert;
1947         }
1948 }
1949
1950 void
1951 mono_bblock_insert_before_ins (MonoBasicBlock *bb, MonoInst *ins, MonoInst *ins_to_insert)
1952 {
1953         if (ins == NULL) {
1954                 ins = bb->code;
1955                 if (ins)
1956                         ins->prev = ins_to_insert;
1957                 bb->code = ins_to_insert;
1958                 ins_to_insert->next = ins;
1959                 if (bb->last_ins == NULL)
1960                         bb->last_ins = ins_to_insert;
1961         } else {
1962                 /* Link with previous */
1963                 if (ins->prev)
1964                         ins->prev->next = ins_to_insert;
1965                 ins_to_insert->prev = ins->prev;
1966
1967                 /* Link with next */
1968                 ins->prev = ins_to_insert;
1969                 ins_to_insert->next = ins;
1970
1971                 if (bb->code == ins)
1972                         bb->code = ins_to_insert;
1973         }
1974 }
1975
1976 /*
1977  * mono_verify_bblock:
1978  *
1979  *   Verify that the next and prev pointers are consistent inside the instructions in BB.
1980  */
1981 void
1982 mono_verify_bblock (MonoBasicBlock *bb)
1983 {
1984         MonoInst *ins, *prev;
1985
1986         prev = NULL;
1987         for (ins = bb->code; ins; ins = ins->next) {
1988                 g_assert (ins->prev == prev);
1989                 prev = ins;
1990         }
1991         if (bb->last_ins)
1992                 g_assert (!bb->last_ins->next);
1993 }
1994
1995 /*
1996  * mono_verify_cfg:
1997  *
1998  *   Perform consistency checks on the JIT data structures and the IR
1999  */
2000 void
2001 mono_verify_cfg (MonoCompile *cfg)
2002 {
2003         MonoBasicBlock *bb;
2004
2005         for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
2006                 mono_verify_bblock (bb);
2007 }
2008
2009 void
2010 mono_destroy_compile (MonoCompile *cfg)
2011 {
2012 #ifndef DISABLE_JIT
2013         GSList *l;
2014
2015         if (cfg->header)
2016                 mono_metadata_free_mh (cfg->header);
2017         //mono_mempool_stats (cfg->mempool);
2018         mono_free_loop_info (cfg);
2019         if (cfg->rs)
2020                 mono_regstate_free (cfg->rs);
2021         if (cfg->spvars)
2022                 g_hash_table_destroy (cfg->spvars);
2023         if (cfg->exvars)
2024                 g_hash_table_destroy (cfg->exvars);
2025         for (l = cfg->headers_to_free; l; l = l->next)
2026                 mono_metadata_free_mh (l->data);
2027         g_list_free (cfg->ldstr_list);
2028         g_hash_table_destroy (cfg->token_info_hash);
2029         if (cfg->abs_patches)
2030                 g_hash_table_destroy (cfg->abs_patches);
2031         mono_mempool_destroy (cfg->mempool);
2032
2033         mono_debug_free_method (cfg);
2034
2035         g_free (cfg->varinfo);
2036         g_free (cfg->vars);
2037         g_free (cfg->exception_message);
2038         g_free (cfg);
2039 #endif
2040 }
2041
2042 #ifndef DISABLE_JIT
2043
2044 static MonoInst*
2045 mono_create_tls_get_offset (MonoCompile *cfg, int offset)
2046 {
2047         MonoInst* ins;
2048
2049         if (!MONO_ARCH_HAVE_TLS_GET)
2050                 return NULL;
2051
2052         if (offset == -1)
2053                 return NULL;
2054
2055         MONO_INST_NEW (cfg, ins, OP_TLS_GET);
2056         ins->dreg = mono_alloc_preg (cfg);
2057         ins->inst_offset = offset;
2058         return ins;
2059 }
2060
2061 gboolean
2062 mini_tls_get_supported (MonoCompile *cfg, MonoTlsKey key)
2063 {
2064         if (!MONO_ARCH_HAVE_TLS_GET)
2065                 return FALSE;
2066
2067         if (cfg->compile_aot)
2068                 return ARCH_HAVE_TLS_GET_REG;
2069         else
2070                 return mini_get_tls_offset (key) != -1;
2071 }
2072
2073 MonoInst*
2074 mono_create_tls_get (MonoCompile *cfg, MonoTlsKey key)
2075 {
2076         /*
2077          * TLS offsets might be different at AOT time, so load them from a GOT slot and
2078          * use a different opcode.
2079          */
2080         if (cfg->compile_aot) {
2081                 if (MONO_ARCH_HAVE_TLS_GET && ARCH_HAVE_TLS_GET_REG) {
2082                         MonoInst *ins, *c;
2083
2084                         EMIT_NEW_TLS_OFFSETCONST (cfg, c, key);
2085                         MONO_INST_NEW (cfg, ins, OP_TLS_GET_REG);
2086                         ins->dreg = mono_alloc_preg (cfg);
2087                         ins->sreg1 = c->dreg;
2088                         return ins;
2089                 } else {
2090                         return NULL;
2091                 }
2092         }
2093
2094         return mono_create_tls_get_offset (cfg, mini_get_tls_offset (key));
2095 }
2096
2097 MonoInst*
2098 mono_get_jit_tls_intrinsic (MonoCompile *cfg)
2099 {
2100         return mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
2101 }
2102
2103 MonoInst*
2104 mono_get_domain_intrinsic (MonoCompile* cfg)
2105 {
2106         return mono_create_tls_get (cfg, TLS_KEY_DOMAIN);
2107 }
2108
2109 MonoInst*
2110 mono_get_thread_intrinsic (MonoCompile* cfg)
2111 {
2112         return mono_create_tls_get (cfg, TLS_KEY_THREAD);
2113 }
2114
2115 MonoInst*
2116 mono_get_lmf_intrinsic (MonoCompile* cfg)
2117 {
2118         return mono_create_tls_get (cfg, TLS_KEY_LMF);
2119 }
2120
2121 MonoInst*
2122 mono_get_lmf_addr_intrinsic (MonoCompile* cfg)
2123 {
2124         return mono_create_tls_get (cfg, TLS_KEY_LMF_ADDR);
2125 }
2126
2127 #endif /* !DISABLE_JIT */
2128
2129
2130 void
2131 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
2132 {
2133         MonoJumpInfo *ji = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfo));
2134
2135         ji->ip.i = ip;
2136         ji->type = type;
2137         ji->data.target = target;
2138         ji->next = cfg->patch_info;
2139
2140         cfg->patch_info = ji;
2141 }
2142
2143 void
2144 mono_add_patch_info_rel (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target, int relocation)
2145 {
2146         MonoJumpInfo *ji = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfo));
2147
2148         ji->ip.i = ip;
2149         ji->type = type;
2150         ji->relocation = relocation;
2151         ji->data.target = target;
2152         ji->next = cfg->patch_info;
2153
2154         cfg->patch_info = ji;
2155 }
2156
2157 void
2158 mono_remove_patch_info (MonoCompile *cfg, int ip)
2159 {
2160         MonoJumpInfo **ji = &cfg->patch_info;
2161
2162         while (*ji) {
2163                 if ((*ji)->ip.i == ip)
2164                         *ji = (*ji)->next;
2165                 else
2166                         ji = &((*ji)->next);
2167         }
2168 }
2169
2170 void
2171 mono_add_seq_point (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins, int native_offset)
2172 {
2173         ins->inst_offset = native_offset;
2174         g_ptr_array_add (cfg->seq_points, ins);
2175         if (bb) {
2176                 bb->seq_points = g_slist_prepend_mempool (cfg->mempool, bb->seq_points, ins);
2177                 bb->last_seq_point = ins;
2178         }
2179 }
2180
2181 void
2182 mono_add_var_location (MonoCompile *cfg, MonoInst *var, gboolean is_reg, int reg, int offset, int from, int to)
2183 {
2184         MonoDwarfLocListEntry *entry = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoDwarfLocListEntry));
2185
2186         if (is_reg)
2187                 g_assert (offset == 0);
2188
2189         entry->is_reg = is_reg;
2190         entry->reg = reg;
2191         entry->offset = offset;
2192         entry->from = from;
2193         entry->to = to;
2194
2195         if (var == cfg->args [0])
2196                 cfg->this_loclist = g_slist_append_mempool (cfg->mempool, cfg->this_loclist, entry);
2197         else if (var == cfg->rgctx_var)
2198                 cfg->rgctx_loclist = g_slist_append_mempool (cfg->mempool, cfg->rgctx_loclist, entry);
2199 }
2200
2201 #ifndef DISABLE_JIT
2202
2203 static void
2204 mono_compile_create_vars (MonoCompile *cfg)
2205 {
2206         MonoMethodSignature *sig;
2207         MonoMethodHeader *header;
2208         int i;
2209
2210         header = cfg->header;
2211
2212         sig = mono_method_signature (cfg->method);
2213         
2214         if (!MONO_TYPE_IS_VOID (sig->ret)) {
2215                 cfg->ret = mono_compile_create_var (cfg, sig->ret, OP_ARG);
2216                 /* Inhibit optimizations */
2217                 cfg->ret->flags |= MONO_INST_VOLATILE;
2218         }
2219         if (cfg->verbose_level > 2)
2220                 g_print ("creating vars\n");
2221
2222         cfg->args = mono_mempool_alloc0 (cfg->mempool, (sig->param_count + sig->hasthis) * sizeof (MonoInst*));
2223
2224         if (sig->hasthis)
2225                 cfg->args [0] = mono_compile_create_var (cfg, &cfg->method->klass->this_arg, OP_ARG);
2226
2227         for (i = 0; i < sig->param_count; ++i) {
2228                 cfg->args [i + sig->hasthis] = mono_compile_create_var (cfg, sig->params [i], OP_ARG);
2229         }
2230
2231         if (cfg->verbose_level > 2) {
2232                 if (cfg->ret) {
2233                         printf ("\treturn : ");
2234                         mono_print_ins (cfg->ret);
2235                 }
2236
2237                 if (sig->hasthis) {
2238                         printf ("\tthis: ");
2239                         mono_print_ins (cfg->args [0]);
2240                 }
2241
2242                 for (i = 0; i < sig->param_count; ++i) {
2243                         printf ("\targ [%d]: ", i);
2244                         mono_print_ins (cfg->args [i + sig->hasthis]);
2245                 }
2246         }
2247
2248         cfg->locals_start = cfg->num_varinfo;
2249         cfg->locals = mono_mempool_alloc0 (cfg->mempool, header->num_locals * sizeof (MonoInst*));
2250
2251         if (cfg->verbose_level > 2)
2252                 g_print ("creating locals\n");
2253
2254         for (i = 0; i < header->num_locals; ++i)
2255                 cfg->locals [i] = mono_compile_create_var (cfg, header->locals [i], OP_LOCAL);
2256
2257         if (cfg->verbose_level > 2)
2258                 g_print ("locals done\n");
2259
2260         mono_arch_create_vars (cfg);
2261
2262         if (cfg->method->save_lmf && cfg->create_lmf_var) {
2263                 MonoInst *lmf_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
2264                 lmf_var->flags |= MONO_INST_VOLATILE;
2265                 lmf_var->flags |= MONO_INST_LMF;
2266                 cfg->lmf_var = lmf_var;
2267         }
2268 }
2269
2270 void
2271 mono_print_code (MonoCompile *cfg, const char* msg)
2272 {
2273         MonoBasicBlock *bb;
2274         
2275         for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
2276                 mono_print_bb (bb, msg);
2277 }
2278
2279 static void
2280 mono_postprocess_patches (MonoCompile *cfg)
2281 {
2282         MonoJumpInfo *patch_info;
2283         int i;
2284
2285         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2286                 switch (patch_info->type) {
2287                 case MONO_PATCH_INFO_ABS: {
2288                         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (patch_info->data.target);
2289
2290                         /*
2291                          * Change patches of type MONO_PATCH_INFO_ABS into patches describing the 
2292                          * absolute address.
2293                          */
2294                         if (info) {
2295                                 //printf ("TEST %s %p\n", info->name, patch_info->data.target);
2296                                 /* for these array methods we currently register the same function pointer
2297                                  * since it's a vararg function. But this means that mono_find_jit_icall_by_addr ()
2298                                  * will return the incorrect one depending on the order they are registered.
2299                                  * See tests/test-arr.cs
2300                                  */
2301                                 if (strstr (info->name, "ves_array_new_va_") == NULL && strstr (info->name, "ves_array_element_address_") == NULL) {
2302                                         patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
2303                                         patch_info->data.name = info->name;
2304                                 }
2305                         }
2306
2307                         if (patch_info->type == MONO_PATCH_INFO_ABS) {
2308                                 if (cfg->abs_patches) {
2309                                         MonoJumpInfo *abs_ji = g_hash_table_lookup (cfg->abs_patches, patch_info->data.target);
2310                                         if (abs_ji) {
2311                                                 patch_info->type = abs_ji->type;
2312                                                 patch_info->data.target = abs_ji->data.target;
2313                                         }
2314                                 }
2315                         }
2316
2317                         break;
2318                 }
2319                 case MONO_PATCH_INFO_SWITCH: {
2320                         gpointer *table;
2321 #if defined(__native_client__) && defined(__native_client_codegen__)
2322                         /* This memory will leak.  */
2323                         /* TODO: can we free this when  */
2324                         /* making the final jump table? */
2325                         table = g_malloc0 (sizeof(gpointer) * patch_info->data.table->table_size);
2326 #else
2327                         if (cfg->method->dynamic) {
2328                                 table = mono_code_manager_reserve (cfg->dynamic_info->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
2329                         } else {
2330                                 table = mono_domain_code_reserve (cfg->domain, sizeof (gpointer) * patch_info->data.table->table_size);
2331                         }
2332 #endif
2333
2334                         for (i = 0; i < patch_info->data.table->table_size; i++) {
2335                                 /* Might be NULL if the switch is eliminated */
2336                                 if (patch_info->data.table->table [i]) {
2337                                         g_assert (patch_info->data.table->table [i]->native_offset);
2338                                         table [i] = GINT_TO_POINTER (patch_info->data.table->table [i]->native_offset);
2339                                 } else {
2340                                         table [i] = NULL;
2341                                 }
2342                         }
2343                         patch_info->data.table->table = (MonoBasicBlock**)table;
2344                         break;
2345                 }
2346                 case MONO_PATCH_INFO_METHOD_JUMP: {
2347                         MonoJumpList *jlist;
2348                         MonoDomain *domain = cfg->domain;
2349                         unsigned char *ip = cfg->native_code + patch_info->ip.i;
2350 #if defined(__native_client__) && defined(__native_client_codegen__)
2351                         /* When this jump target gets evaluated, the method */
2352                         /* will be installed in the dynamic code section,   */
2353                         /* not at the location of cfg->native_code.         */
2354                         ip = nacl_inverse_modify_patch_target (cfg->native_code) + patch_info->ip.i;
2355 #endif
2356
2357                         mono_domain_lock (domain);
2358                         jlist = g_hash_table_lookup (domain_jit_info (domain)->jump_target_hash, patch_info->data.method);
2359                         if (!jlist) {
2360                                 jlist = mono_domain_alloc0 (domain, sizeof (MonoJumpList));
2361                                 g_hash_table_insert (domain_jit_info (domain)->jump_target_hash, patch_info->data.method, jlist);
2362                         }
2363                         jlist->list = g_slist_prepend (jlist->list, ip);
2364                         mono_domain_unlock (domain);
2365                         break;
2366                 }
2367                 default:
2368                         /* do nothing */
2369                         break;
2370                 }
2371         }
2372 }
2373
2374 void
2375 mono_codegen (MonoCompile *cfg)
2376 {
2377         MonoBasicBlock *bb;
2378         int max_epilog_size;
2379         guint8 *code;
2380         MonoDomain *code_domain;
2381         guint unwindlen = 0;
2382
2383         if (mono_using_xdebug)
2384                 /*
2385                  * Recent gdb versions have trouble processing symbol files containing
2386                  * overlapping address ranges, so allocate all code from the code manager
2387                  * of the root domain. (#666152).
2388                  */
2389                 code_domain = mono_get_root_domain ();
2390         else
2391                 code_domain = cfg->domain;
2392
2393 #if defined(__native_client_codegen__) && defined(__native_client__)
2394         void *code_dest;
2395
2396         /* This keeps patch targets from being transformed during
2397          * ordinary method compilation, for local branches and jumps.
2398          */
2399         nacl_allow_target_modification (FALSE);
2400 #endif
2401
2402         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2403                 cfg->spill_count = 0;
2404                 /* we reuse dfn here */
2405                 /* bb->dfn = bb_count++; */
2406
2407                 mono_arch_lowering_pass (cfg, bb);
2408
2409                 if (cfg->opt & MONO_OPT_PEEPHOLE)
2410                         mono_arch_peephole_pass_1 (cfg, bb);
2411
2412                 if (!cfg->globalra)
2413                         mono_local_regalloc (cfg, bb);
2414
2415                 if (cfg->opt & MONO_OPT_PEEPHOLE)
2416                         mono_arch_peephole_pass_2 (cfg, bb);
2417
2418                 if (cfg->gen_seq_points && !cfg->gen_sdb_seq_points)
2419                         bb_deduplicate_op_il_seq_points (cfg, bb);
2420         }
2421
2422         if (cfg->prof_options & MONO_PROFILE_COVERAGE)
2423                 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, cfg->num_bblocks);
2424
2425         code = mono_arch_emit_prolog (cfg);
2426
2427         cfg->code_len = code - cfg->native_code;
2428         cfg->prolog_end = cfg->code_len;
2429         cfg->cfa_reg = cfg->cur_cfa_reg;
2430         cfg->cfa_offset = cfg->cur_cfa_offset;
2431
2432         mono_debug_open_method (cfg);
2433
2434         /* emit code all basic blocks */
2435         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2436                 bb->native_offset = cfg->code_len;
2437                 bb->real_native_offset = cfg->code_len;
2438                 //if ((bb == cfg->bb_entry) || !(bb->region == -1 && !bb->dfn))
2439                         mono_arch_output_basic_block (cfg, bb);
2440                 bb->native_length = cfg->code_len - bb->native_offset;
2441
2442                 if (bb == cfg->bb_exit) {
2443                         cfg->epilog_begin = cfg->code_len;
2444                         mono_arch_emit_epilog (cfg);
2445                         cfg->epilog_end = cfg->code_len;
2446                 }
2447         }
2448
2449 #ifdef __native_client_codegen__
2450         mono_nacl_fix_patches (cfg->native_code, cfg->patch_info);
2451 #endif
2452         mono_arch_emit_exceptions (cfg);
2453
2454         max_epilog_size = 0;
2455
2456         /* we always allocate code in cfg->domain->code_mp to increase locality */
2457         cfg->code_size = cfg->code_len + max_epilog_size;
2458 #ifdef __native_client_codegen__
2459         cfg->code_size = NACL_BUNDLE_ALIGN_UP (cfg->code_size);
2460 #endif
2461         /* fixme: align to MONO_ARCH_CODE_ALIGNMENT */
2462
2463 #ifdef MONO_ARCH_HAVE_UNWIND_TABLE
2464         unwindlen = mono_arch_unwindinfo_get_size (cfg->arch.unwindinfo);
2465 #endif
2466
2467         if (cfg->method->dynamic) {
2468                 /* Allocate the code into a separate memory pool so it can be freed */
2469                 cfg->dynamic_info = g_new0 (MonoJitDynamicMethodInfo, 1);
2470                 cfg->dynamic_info->code_mp = mono_code_manager_new_dynamic ();
2471                 mono_domain_lock (cfg->domain);
2472                 mono_dynamic_code_hash_insert (cfg->domain, cfg->method, cfg->dynamic_info);
2473                 mono_domain_unlock (cfg->domain);
2474
2475                 if (mono_using_xdebug)
2476                         /* See the comment for cfg->code_domain */
2477                         code = mono_domain_code_reserve (code_domain, cfg->code_size + cfg->thunk_area + unwindlen);
2478                 else
2479                         code = mono_code_manager_reserve (cfg->dynamic_info->code_mp, cfg->code_size + cfg->thunk_area + unwindlen);
2480         } else {
2481                 code = mono_domain_code_reserve (code_domain, cfg->code_size + cfg->thunk_area + unwindlen);
2482         }
2483 #if defined(__native_client_codegen__) && defined(__native_client__)
2484         nacl_allow_target_modification (TRUE);
2485 #endif
2486         if (cfg->thunk_area) {
2487                 cfg->thunks_offset = cfg->code_size + unwindlen;
2488                 cfg->thunks = code + cfg->thunks_offset;
2489                 memset (cfg->thunks, 0, cfg->thunk_area);
2490         }
2491
2492         g_assert (code);
2493         memcpy (code, cfg->native_code, cfg->code_len);
2494 #if defined(__default_codegen__)
2495         g_free (cfg->native_code);
2496 #elif defined(__native_client_codegen__)
2497         if (cfg->native_code_alloc) {
2498                 g_free (cfg->native_code_alloc);
2499                 cfg->native_code_alloc = 0;
2500         }
2501         else if (cfg->native_code) {
2502                 g_free (cfg->native_code);
2503         }
2504 #endif /* __native_client_codegen__ */
2505         cfg->native_code = code;
2506         code = cfg->native_code + cfg->code_len;
2507   
2508         /* g_assert (((int)cfg->native_code & (MONO_ARCH_CODE_ALIGNMENT - 1)) == 0); */
2509         mono_postprocess_patches (cfg);
2510
2511 #ifdef VALGRIND_JIT_REGISTER_MAP
2512         if (valgrind_register){
2513                 char* nm = mono_method_full_name (cfg->method, TRUE);
2514                 VALGRIND_JIT_REGISTER_MAP (nm, cfg->native_code, cfg->native_code + cfg->code_len);
2515                 g_free (nm);
2516         }
2517 #endif
2518  
2519         if (cfg->verbose_level > 0) {
2520                 char* nm = mono_method_full_name (cfg->method, TRUE);
2521                 g_print ("Method %s emitted at %p to %p (code length %d) [%s]\n", 
2522                                  nm, 
2523                                  cfg->native_code, cfg->native_code + cfg->code_len, cfg->code_len, cfg->domain->friendly_name);
2524                 g_free (nm);
2525         }
2526
2527         {
2528                 gboolean is_generic = FALSE;
2529
2530                 if (cfg->method->is_inflated || mono_method_get_generic_container (cfg->method) ||
2531                                 cfg->method->klass->generic_container || cfg->method->klass->generic_class) {
2532                         is_generic = TRUE;
2533                 }
2534
2535                 if (cfg->generic_sharing_context)
2536                         g_assert (is_generic);
2537         }
2538
2539 #ifdef MONO_ARCH_HAVE_SAVE_UNWIND_INFO
2540         mono_arch_save_unwind_info (cfg);
2541 #endif
2542
2543 #if defined(__native_client_codegen__) && defined(__native_client__)
2544         if (!cfg->compile_aot) {
2545                 if (cfg->method->dynamic) {
2546                         code_dest = nacl_code_manager_get_code_dest(cfg->dynamic_info->code_mp, cfg->native_code);
2547                 } else {
2548                         code_dest = nacl_domain_get_code_dest(cfg->domain, cfg->native_code);
2549                 }
2550         }
2551 #endif
2552
2553 #if defined(__native_client_codegen__)
2554         mono_nacl_fix_patches (cfg->native_code, cfg->patch_info);
2555 #endif
2556
2557 #ifdef MONO_ARCH_HAVE_PATCH_CODE_NEW
2558         {
2559                 MonoJumpInfo *ji;
2560                 gpointer target;
2561
2562                 for (ji = cfg->patch_info; ji; ji = ji->next) {
2563                         if (cfg->compile_aot) {
2564                                 switch (ji->type) {
2565                                 case MONO_PATCH_INFO_BB:
2566                                 case MONO_PATCH_INFO_LABEL:
2567                                         break;
2568                                 default:
2569                                         /* No need to patch these */
2570                                         continue;
2571                                 }
2572                         }
2573
2574                         if (ji->type == MONO_PATCH_INFO_NONE)
2575                                 continue;
2576
2577                         target = mono_resolve_patch_target (cfg->method, cfg->domain, cfg->native_code, ji, cfg->run_cctors);
2578                         mono_arch_patch_code_new (cfg, cfg->domain, cfg->native_code, ji, target);
2579                 }
2580         }
2581 #else
2582         mono_arch_patch_code (cfg, cfg->method, cfg->domain, cfg->native_code, cfg->patch_info, cfg->run_cctors);
2583 #endif
2584
2585         if (cfg->method->dynamic) {
2586                 if (mono_using_xdebug)
2587                         mono_domain_code_commit (code_domain, cfg->native_code, cfg->code_size, cfg->code_len);
2588                 else
2589                         mono_code_manager_commit (cfg->dynamic_info->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
2590         } else {
2591                 mono_domain_code_commit (code_domain, cfg->native_code, cfg->code_size, cfg->code_len);
2592         }
2593 #if defined(__native_client_codegen__) && defined(__native_client__)
2594         cfg->native_code = code_dest;
2595 #endif
2596         mono_profiler_code_buffer_new (cfg->native_code, cfg->code_len, MONO_PROFILER_CODE_BUFFER_METHOD, cfg->method);
2597         
2598         mono_arch_flush_icache (cfg->native_code, cfg->code_len);
2599
2600         mono_debug_close_method (cfg);
2601
2602 #ifdef MONO_ARCH_HAVE_UNWIND_TABLE
2603         mono_arch_unwindinfo_install_unwind_info (&cfg->arch.unwindinfo, cfg->native_code, cfg->code_len);
2604 #endif
2605 }
2606
2607 static void
2608 compute_reachable (MonoBasicBlock *bb)
2609 {
2610         int i;
2611
2612         if (!(bb->flags & BB_VISITED)) {
2613                 bb->flags |= BB_VISITED;
2614                 for (i = 0; i < bb->out_count; ++i)
2615                         compute_reachable (bb->out_bb [i]);
2616         }
2617 }
2618
2619 static void
2620 mono_handle_out_of_line_bblock (MonoCompile *cfg)
2621 {
2622         MonoBasicBlock *bb;
2623         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2624                 if (bb->next_bb && bb->next_bb->out_of_line && bb->last_ins && !MONO_IS_BRANCH_OP (bb->last_ins)) {
2625                         MonoInst *ins;
2626                         MONO_INST_NEW (cfg, ins, OP_BR);
2627                         MONO_ADD_INS (bb, ins);
2628                         ins->inst_target_bb = bb->next_bb;
2629                 }
2630         }
2631 }
2632
2633 #endif /* #ifndef DISABLE_JIT */
2634
2635 static MonoJitInfo*
2636 create_jit_info_for_trampoline (MonoMethod *wrapper, MonoTrampInfo *info)
2637 {
2638         MonoDomain *domain = mono_get_root_domain ();
2639         MonoJitInfo *jinfo;
2640         guint8 *uw_info;
2641         guint32 info_len;
2642
2643         if (info->uw_info) {
2644                 uw_info = info->uw_info;
2645                 info_len = info->uw_info_len;
2646         } else {
2647                 uw_info = mono_unwind_ops_encode (info->unwind_ops, &info_len);
2648         }
2649
2650         jinfo = mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO);
2651         jinfo->d.method = wrapper;
2652         jinfo->code_start = info->code;
2653         jinfo->code_size = info->code_size;
2654         jinfo->unwind_info = mono_cache_unwind_info (uw_info, info_len);
2655
2656         if (!info->uw_info)
2657                 g_free (uw_info);
2658
2659         return jinfo;
2660 }
2661
2662 #ifndef DISABLE_JIT
2663
2664 static MonoJitInfo*
2665 create_jit_info (MonoCompile *cfg, MonoMethod *method_to_compile)
2666 {
2667         GSList *tmp;
2668         MonoMethodHeader *header;
2669         MonoJitInfo *jinfo;
2670         MonoJitInfoFlags flags = JIT_INFO_NONE;
2671         int num_clauses, num_holes = 0;
2672         guint32 stack_size = 0;
2673
2674         g_assert (method_to_compile == cfg->method);
2675         header = cfg->header;
2676
2677         if (cfg->generic_sharing_context)
2678                 flags |= JIT_INFO_HAS_GENERIC_JIT_INFO;
2679
2680         if (cfg->arch_eh_jit_info) {
2681                 MonoJitArgumentInfo *arg_info;
2682                 MonoMethodSignature *sig = mono_method_signature (cfg->method_to_register);
2683
2684                 /*
2685                  * This cannot be computed during stack walking, as
2686                  * mono_arch_get_argument_info () is not signal safe.
2687                  */
2688                 arg_info = g_newa (MonoJitArgumentInfo, sig->param_count + 1);
2689                 stack_size = mono_arch_get_argument_info (cfg->generic_sharing_context, sig, sig->param_count, arg_info);
2690
2691                 if (stack_size)
2692                         flags |= JIT_INFO_HAS_ARCH_EH_INFO;
2693         }
2694
2695         if (cfg->has_unwind_info_for_epilog && !(flags & JIT_INFO_HAS_ARCH_EH_INFO))
2696                 flags |= JIT_INFO_HAS_ARCH_EH_INFO;
2697
2698         if (cfg->thunk_area)
2699                 flags |= JIT_INFO_HAS_THUNK_INFO;
2700
2701         if (cfg->try_block_holes) {
2702                 for (tmp = cfg->try_block_holes; tmp; tmp = tmp->next) {
2703                         TryBlockHole *hole = tmp->data;
2704                         MonoExceptionClause *ec = hole->clause;
2705                         int hole_end = hole->basic_block->native_offset + hole->basic_block->native_length;
2706                         MonoBasicBlock *clause_last_bb = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
2707                         g_assert (clause_last_bb);
2708
2709                         /* Holes at the end of a try region can be represented by simply reducing the size of the block itself.*/
2710                         if (clause_last_bb->native_offset != hole_end)
2711                                 ++num_holes;
2712                 }
2713                 if (num_holes)
2714                         flags |= JIT_INFO_HAS_TRY_BLOCK_HOLES;
2715                 if (G_UNLIKELY (cfg->verbose_level >= 4))
2716                         printf ("Number of try block holes %d\n", num_holes);
2717         }
2718
2719         if (mono_security_method_has_declsec (cfg->method_to_register))
2720                 flags |= JIT_INFO_HAS_ARCH_EH_INFO;
2721
2722         if (COMPILE_LLVM (cfg))
2723                 num_clauses = cfg->llvm_ex_info_len;
2724         else
2725                 num_clauses = header->num_clauses;
2726
2727         if (cfg->method->dynamic)
2728                 jinfo = g_malloc0 (mono_jit_info_size (flags, num_clauses, num_holes));
2729         else
2730                 jinfo = mono_domain_alloc0 (cfg->domain, mono_jit_info_size (flags, num_clauses, num_holes));
2731         mono_jit_info_init (jinfo, cfg->method_to_register, cfg->native_code, cfg->code_len, flags, num_clauses, num_holes);
2732         jinfo->domain_neutral = (cfg->opt & MONO_OPT_SHARED) != 0;
2733
2734         if (COMPILE_LLVM (cfg))
2735                 jinfo->from_llvm = TRUE;
2736
2737         if (cfg->generic_sharing_context) {
2738                 MonoInst *inst;
2739                 MonoGenericJitInfo *gi;
2740                 GSList *loclist = NULL;
2741
2742                 gi = mono_jit_info_get_generic_jit_info (jinfo);
2743                 g_assert (gi);
2744
2745                 if (cfg->method->dynamic)
2746                         gi->generic_sharing_context = g_new0 (MonoGenericSharingContext, 1);
2747                 else
2748                         gi->generic_sharing_context = mono_domain_alloc0 (cfg->domain, sizeof (MonoGenericSharingContext));
2749                 mini_init_gsctx (cfg->method->dynamic ? NULL : cfg->domain, NULL, cfg->gsctx_context, gi->generic_sharing_context);
2750
2751                 if ((method_to_compile->flags & METHOD_ATTRIBUTE_STATIC) ||
2752                                 mini_method_get_context (method_to_compile)->method_inst ||
2753                                 method_to_compile->klass->valuetype) {
2754                         g_assert (cfg->rgctx_var);
2755                 }
2756
2757                 gi->has_this = 1;
2758
2759                 if ((method_to_compile->flags & METHOD_ATTRIBUTE_STATIC) ||
2760                                 mini_method_get_context (method_to_compile)->method_inst ||
2761                                 method_to_compile->klass->valuetype) {
2762                         inst = cfg->rgctx_var;
2763                         if (!COMPILE_LLVM (cfg))
2764                                 g_assert (inst->opcode == OP_REGOFFSET);
2765                         loclist = cfg->rgctx_loclist;
2766                 } else {
2767                         inst = cfg->args [0];
2768                         loclist = cfg->this_loclist;
2769                 }
2770
2771                 if (loclist) {
2772                         /* Needed to handle async exceptions */
2773                         GSList *l;
2774                         int i;
2775
2776                         gi->nlocs = g_slist_length (loclist);
2777                         if (cfg->method->dynamic)
2778                                 gi->locations = g_malloc0 (gi->nlocs * sizeof (MonoDwarfLocListEntry));
2779                         else
2780                                 gi->locations = mono_domain_alloc0 (cfg->domain, gi->nlocs * sizeof (MonoDwarfLocListEntry));
2781                         i = 0;
2782                         for (l = loclist; l; l = l->next) {
2783                                 memcpy (&(gi->locations [i]), l->data, sizeof (MonoDwarfLocListEntry));
2784                                 i ++;
2785                         }
2786                 }
2787
2788                 if (COMPILE_LLVM (cfg)) {
2789                         g_assert (cfg->llvm_this_reg != -1);
2790                         gi->this_in_reg = 0;
2791                         gi->this_reg = cfg->llvm_this_reg;
2792                         gi->this_offset = cfg->llvm_this_offset;
2793                 } else if (inst->opcode == OP_REGVAR) {
2794                         gi->this_in_reg = 1;
2795                         gi->this_reg = inst->dreg;
2796                 } else {
2797                         g_assert (inst->opcode == OP_REGOFFSET);
2798 #ifdef TARGET_X86
2799                         g_assert (inst->inst_basereg == X86_EBP);
2800 #elif defined(TARGET_AMD64)
2801                         g_assert (inst->inst_basereg == X86_EBP || inst->inst_basereg == X86_ESP);
2802 #endif
2803                         g_assert (inst->inst_offset >= G_MININT32 && inst->inst_offset <= G_MAXINT32);
2804
2805                         gi->this_in_reg = 0;
2806                         gi->this_reg = inst->inst_basereg;
2807                         gi->this_offset = inst->inst_offset;
2808                 }
2809         }
2810
2811         if (num_holes) {
2812                 MonoTryBlockHoleTableJitInfo *table;
2813                 int i;
2814
2815                 table = mono_jit_info_get_try_block_hole_table_info (jinfo);
2816                 table->num_holes = (guint16)num_holes;
2817                 i = 0;
2818                 for (tmp = cfg->try_block_holes; tmp; tmp = tmp->next) {
2819                         guint32 start_bb_offset;
2820                         MonoTryBlockHoleJitInfo *hole;
2821                         TryBlockHole *hole_data = tmp->data;
2822                         MonoExceptionClause *ec = hole_data->clause;
2823                         int hole_end = hole_data->basic_block->native_offset + hole_data->basic_block->native_length;
2824                         MonoBasicBlock *clause_last_bb = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
2825                         g_assert (clause_last_bb);
2826
2827                         /* Holes at the end of a try region can be represented by simply reducing the size of the block itself.*/
2828                         if (clause_last_bb->native_offset == hole_end)
2829                                 continue;
2830
2831                         start_bb_offset = hole_data->start_offset - hole_data->basic_block->native_offset;
2832                         hole = &table->holes [i++];
2833                         hole->clause = hole_data->clause - &header->clauses [0];
2834                         hole->offset = (guint32)hole_data->start_offset;
2835                         hole->length = (guint16)(hole_data->basic_block->native_length - start_bb_offset);
2836
2837                         if (G_UNLIKELY (cfg->verbose_level >= 4))
2838                                 printf ("\tTry block hole at eh clause %d offset %x length %x\n", hole->clause, hole->offset, hole->length);
2839                 }
2840                 g_assert (i == num_holes);
2841         }
2842
2843         if (jinfo->has_arch_eh_info) {
2844                 MonoArchEHJitInfo *info;
2845
2846                 info = mono_jit_info_get_arch_eh_info (jinfo);
2847
2848                 info->stack_size = stack_size;
2849         }
2850
2851         if (cfg->thunk_area) {
2852                 MonoThunkJitInfo *info;
2853
2854                 info = mono_jit_info_get_thunk_info (jinfo);
2855                 info->thunks_offset = cfg->thunks_offset;
2856                 info->thunks_size = cfg->thunk_area;
2857         }
2858
2859         if (COMPILE_LLVM (cfg)) {
2860                 if (num_clauses)
2861                         memcpy (&jinfo->clauses [0], &cfg->llvm_ex_info [0], num_clauses * sizeof (MonoJitExceptionInfo));
2862         } else if (header->num_clauses) {
2863                 int i;
2864
2865                 for (i = 0; i < header->num_clauses; i++) {
2866                         MonoExceptionClause *ec = &header->clauses [i];
2867                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
2868                         MonoBasicBlock *tblock;
2869                         MonoInst *exvar, *spvar;
2870
2871                         ei->flags = ec->flags;
2872
2873                         if (G_UNLIKELY (cfg->verbose_level >= 4))
2874                                 printf ("IL clause: try 0x%x-0x%x handler 0x%x-0x%x filter 0x%x\n", ec->try_offset, ec->try_offset + ec->try_len, ec->handler_offset, ec->handler_offset + ec->handler_len, ec->flags == MONO_EXCEPTION_CLAUSE_FILTER ? ec->data.filter_offset : 0);
2875
2876                         /*
2877                          * The spvars are needed by mono_arch_install_handler_block_guard ().
2878                          */
2879                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY) {
2880                                 int region;
2881
2882                                 region = ((i + 1) << 8) | MONO_REGION_FINALLY | ec->flags;
2883                                 spvar = mono_find_spvar_for_region (cfg, region);
2884                                 g_assert (spvar);
2885                                 ei->exvar_offset = spvar->inst_offset;
2886                         } else {
2887                                 exvar = mono_find_exvar_for_offset (cfg, ec->handler_offset);
2888                                 ei->exvar_offset = exvar ? exvar->inst_offset : 0;
2889                         }
2890
2891                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
2892                                 tblock = cfg->cil_offset_to_bb [ec->data.filter_offset];
2893                                 g_assert (tblock);
2894                                 ei->data.filter = cfg->native_code + tblock->native_offset;
2895                         } else {
2896                                 ei->data.catch_class = ec->data.catch_class;
2897                         }
2898
2899                         tblock = cfg->cil_offset_to_bb [ec->try_offset];
2900                         g_assert (tblock);
2901                         g_assert (tblock->native_offset);
2902                         ei->try_start = cfg->native_code + tblock->native_offset;
2903                         if (tblock->extend_try_block) {
2904                                 /*
2905                                  * Extend the try block backwards to include parts of the previous call
2906                                  * instruction.
2907                                  */
2908                                 ei->try_start = (guint8*)ei->try_start - MONO_ARCH_MONITOR_ENTER_ADJUSTMENT;
2909                         }
2910                         tblock = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
2911                         g_assert (tblock);
2912                         if (!tblock->native_offset) {
2913                                 int j, end;
2914                                 for (j = ec->try_offset + ec->try_len, end = ec->try_offset; j >= end; --j) {
2915                                         MonoBasicBlock *bb = cfg->cil_offset_to_bb [j];
2916                                         if (bb && bb->native_offset) {
2917                                                 tblock = bb;
2918                                                 break;
2919                                         }
2920                                 }
2921                         }
2922                         ei->try_end = cfg->native_code + tblock->native_offset;
2923                         g_assert (tblock->native_offset);
2924                         tblock = cfg->cil_offset_to_bb [ec->handler_offset];
2925                         g_assert (tblock);
2926                         ei->handler_start = cfg->native_code + tblock->native_offset;
2927
2928                         for (tmp = cfg->try_block_holes; tmp; tmp = tmp->next) {
2929                                 TryBlockHole *hole = tmp->data;
2930                                 gpointer hole_end = cfg->native_code + (hole->basic_block->native_offset + hole->basic_block->native_length);
2931                                 if (hole->clause == ec && hole_end == ei->try_end) {
2932                                         if (G_UNLIKELY (cfg->verbose_level >= 4))
2933                                                 printf ("\tShortening try block %d from %x to %x\n", i, (int)((guint8*)ei->try_end - cfg->native_code), hole->start_offset);
2934
2935                                         ei->try_end = cfg->native_code + hole->start_offset;
2936                                         break;
2937                                 }
2938                         }
2939
2940                         if (ec->flags == MONO_EXCEPTION_CLAUSE_FINALLY) {
2941                                 int end_offset;
2942                                 if (ec->handler_offset + ec->handler_len < header->code_size) {
2943                                         tblock = cfg->cil_offset_to_bb [ec->handler_offset + ec->handler_len];
2944                                         if (tblock->native_offset) {
2945                                                 end_offset = tblock->native_offset;
2946                                         } else {
2947                                                 int j, end;
2948
2949                                                 for (j = ec->handler_offset + ec->handler_len, end = ec->handler_offset; j >= end; --j) {
2950                                                         MonoBasicBlock *bb = cfg->cil_offset_to_bb [j];
2951                                                         if (bb && bb->native_offset) {
2952                                                                 tblock = bb;
2953                                                                 break;
2954                                                         }
2955                                                 }
2956                                                 end_offset = tblock->native_offset +  tblock->native_length;
2957                                         }
2958                                 } else {
2959                                         end_offset = cfg->epilog_begin;
2960                                 }
2961                                 ei->data.handler_end = cfg->native_code + end_offset;
2962                         }
2963                 }
2964         }
2965
2966         if (G_UNLIKELY (cfg->verbose_level >= 4)) {
2967                 int i;
2968                 for (i = 0; i < jinfo->num_clauses; i++) {
2969                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
2970                         int start = (guint8*)ei->try_start - cfg->native_code;
2971                         int end = (guint8*)ei->try_end - cfg->native_code;
2972                         int handler = (guint8*)ei->handler_start - cfg->native_code;
2973                         int handler_end = (guint8*)ei->data.handler_end - cfg->native_code;
2974
2975                         printf ("JitInfo EH clause %d flags %x try %x-%x handler %x-%x\n", i, ei->flags, start, end, handler, handler_end);
2976                 }
2977         }
2978
2979         if (cfg->encoded_unwind_ops) {
2980                 /* Generated by LLVM */
2981                 jinfo->unwind_info = mono_cache_unwind_info (cfg->encoded_unwind_ops, cfg->encoded_unwind_ops_len);
2982                 g_free (cfg->encoded_unwind_ops);
2983         } else if (cfg->unwind_ops) {
2984                 guint32 info_len;
2985                 guint8 *unwind_info = mono_unwind_ops_encode (cfg->unwind_ops, &info_len);
2986                 guint32 unwind_desc;
2987
2988                 unwind_desc = mono_cache_unwind_info (unwind_info, info_len);
2989
2990                 if (cfg->has_unwind_info_for_epilog) {
2991                         MonoArchEHJitInfo *info;
2992
2993                         info = mono_jit_info_get_arch_eh_info (jinfo);
2994                         g_assert (info);
2995                         info->epilog_size = cfg->code_len - cfg->epilog_begin;
2996                 }
2997                 jinfo->unwind_info = unwind_desc;
2998                 g_free (unwind_info);
2999         } else {
3000                 jinfo->unwind_info = cfg->used_int_regs;
3001         }
3002
3003         return jinfo;
3004 }
3005 #endif
3006
3007 /* Return whenever METHOD is a gsharedvt method */
3008 static gboolean
3009 is_gsharedvt_method (MonoMethod *method)
3010 {
3011         MonoGenericContext *context;
3012         MonoGenericInst *inst;
3013         int i;
3014
3015         if (!method->is_inflated)
3016                 return FALSE;
3017         context = mono_method_get_context (method);
3018         inst = context->class_inst;
3019         if (inst) {
3020                 for (i = 0; i < inst->type_argc; ++i)
3021                         if (mini_is_gsharedvt_gparam (inst->type_argv [i]))
3022                                 return TRUE;
3023         }
3024         inst = context->method_inst;
3025         if (inst) {
3026                 for (i = 0; i < inst->type_argc; ++i)
3027                         if (mini_is_gsharedvt_gparam (inst->type_argv [i]))
3028                                 return TRUE;
3029         }
3030         return FALSE;
3031 }
3032
3033 static gboolean
3034 is_open_method (MonoMethod *method)
3035 {
3036         MonoGenericContext *context;
3037
3038         if (!method->is_inflated)
3039                 return FALSE;
3040         context = mono_method_get_context (method);
3041         if (context->class_inst && context->class_inst->is_open)
3042                 return TRUE;
3043         if (context->method_inst && context->method_inst->is_open)
3044                 return TRUE;
3045         return FALSE;
3046 }
3047
3048 #ifndef DISABLE_JIT
3049
3050 #if defined(__native_client_codegen__) || USE_COOP_GC
3051
3052 static void
3053 mono_create_gc_safepoint (MonoCompile *cfg, MonoBasicBlock *bblock)
3054 {
3055         MonoInst *poll_addr, *ins;
3056         if (cfg->verbose_level)
3057                 printf ("ADDING SAFE POINT TO BB %d\n", bblock->block_num);
3058
3059 #if defined(__native_client_codegen__)
3060         NEW_AOTCONST (cfg, poll_addr, MONO_PATCH_INFO_GC_SAFE_POINT_FLAG, (gpointer)&__nacl_thread_suspension_needed);
3061 #else
3062         NEW_AOTCONST (cfg, poll_addr, MONO_PATCH_INFO_GC_SAFE_POINT_FLAG, (gpointer)&mono_polling_required);
3063 #endif
3064
3065         MONO_INST_NEW (cfg, ins, OP_GC_SAFE_POINT);
3066         ins->sreg1 = poll_addr->dreg;
3067
3068          if (bblock->flags & BB_EXCEPTION_HANDLER) {
3069                 MonoInst *eh_op = bblock->code;
3070
3071                 // we only skip the ops that start EH blocks.
3072                 if (eh_op && eh_op->opcode != OP_START_HANDLER && eh_op->opcode != OP_GET_EX_OBJ)
3073                         eh_op = NULL;
3074
3075                 mono_bblock_insert_after_ins (bblock, eh_op, poll_addr);
3076                 mono_bblock_insert_after_ins (bblock, poll_addr, ins);
3077         } else if (bblock == cfg->bb_entry) {
3078                 mono_bblock_insert_after_ins (bblock, bblock->last_ins, poll_addr);
3079                 mono_bblock_insert_after_ins (bblock, poll_addr, ins);
3080
3081         } else {
3082                 mono_bblock_insert_before_ins (bblock, NULL, poll_addr);
3083                 mono_bblock_insert_after_ins (bblock, poll_addr, ins);
3084         }
3085 }
3086
3087 /*
3088 This code inserts safepoints into managed code at important code paths.
3089 Those are:
3090
3091 -the first basic block
3092 -landing BB for exception handlers
3093 -loop body starts.
3094
3095 */
3096 static void
3097 mono_insert_safepoints (MonoCompile *cfg)
3098 {
3099         MonoBasicBlock *bb;
3100
3101         if (cfg->verbose_level)
3102                 printf ("INSERTING SAFEPOINTS\n");
3103
3104         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3105                 if (bb->loop_body_start || bb == cfg->bb_entry || bb->flags & BB_EXCEPTION_HANDLER)
3106                         mono_create_gc_safepoint (cfg, bb);
3107         }
3108 }
3109
3110 #else
3111
3112 static void
3113 mono_insert_safepoints (MonoCompile *cfg)
3114 {
3115 }
3116
3117 #endif
3118
3119 /*
3120  * mini_method_compile:
3121  * @method: the method to compile
3122  * @opts: the optimization flags to use
3123  * @domain: the domain where the method will be compiled in
3124  * @flags: compilation flags
3125  * @parts: debug flag
3126  *
3127  * Returns: a MonoCompile* pointer. Caller must check the exception_type
3128  * field in the returned struct to see if compilation succeded.
3129  */
3130 MonoCompile*
3131 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFlags flags, int parts)
3132 {
3133         MonoMethodHeader *header;
3134         MonoMethodSignature *sig;
3135         MonoError err;
3136         MonoCompile *cfg;
3137         int dfn, i, code_size_ratio;
3138         gboolean try_generic_shared, try_llvm = FALSE;
3139         MonoMethod *method_to_compile, *method_to_register;
3140         gboolean method_is_gshared = FALSE;
3141         gboolean run_cctors = (flags & JIT_FLAG_RUN_CCTORS) ? 1 : 0;
3142         gboolean compile_aot = (flags & JIT_FLAG_AOT) ? 1 : 0;
3143         gboolean full_aot = (flags & JIT_FLAG_FULL_AOT) ? 1 : 0;
3144         gboolean disable_direct_icalls = (flags & JIT_FLAG_NO_DIRECT_ICALLS) ? 1 : 0;
3145         gboolean gsharedvt_method = FALSE;
3146 #ifdef ENABLE_LLVM
3147         gboolean llvm = (flags & JIT_FLAG_LLVM) ? 1 : 0;
3148 #endif
3149         static gboolean verbose_method_inited;
3150         static const char *verbose_method_name;
3151
3152         InterlockedIncrement (&mono_jit_stats.methods_compiled);
3153         if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)
3154                 mono_profiler_method_jit (method);
3155         if (MONO_METHOD_COMPILE_BEGIN_ENABLED ())
3156                 MONO_PROBE_METHOD_COMPILE_BEGIN (method);
3157
3158         /*
3159          * In AOT mode, method can be the following:
3160          * - the generic method definition. In this case, we are compiling the fully shared
3161          *   version of the method, i.e. the version where all the type parameters are
3162          *   reference types.
3163          * - a gsharedvt method.
3164          * - a method inflated with type parameters. This is for partial sharing.
3165          * - a method inflated with concrete types.
3166          */
3167         if (compile_aot)
3168                 try_generic_shared = mono_class_generic_sharing_enabled (method->klass) &&
3169                         (opts & MONO_OPT_GSHARED) && ((method->is_generic || method->klass->generic_container) || (!method->klass->generic_class && mono_method_is_generic_sharable_full (method, TRUE, FALSE, FALSE)));
3170         else
3171                 try_generic_shared = mono_class_generic_sharing_enabled (method->klass) &&
3172                         (opts & MONO_OPT_GSHARED) && mono_method_is_generic_sharable (method, FALSE);
3173
3174         /*
3175         if (try_generic_shared && !mono_debug_count ())
3176                 try_generic_shared = FALSE;
3177         */
3178
3179         if (opts & MONO_OPT_GSHARED) {
3180                 if (try_generic_shared)
3181                         mono_stats.generics_sharable_methods++;
3182                 else if (mono_method_is_generic_impl (method))
3183                         mono_stats.generics_unsharable_methods++;
3184         }
3185
3186         if (mini_is_gsharedvt_sharable_method (method)) {
3187                 if (!mono_debug_count ())
3188                         try_generic_shared = FALSE;
3189                 if (compile_aot)
3190                         try_generic_shared = FALSE;
3191         }
3192
3193         gsharedvt_method = is_gsharedvt_method (method);
3194         if (gsharedvt_method || (compile_aot && is_open_method (method))) {
3195                 /* We are AOTing a gshared method directly */
3196                 method_is_gshared = TRUE;
3197                 g_assert (compile_aot);
3198                 try_generic_shared = TRUE;
3199         }
3200
3201 #ifdef ENABLE_LLVM
3202         try_llvm = mono_use_llvm || llvm;
3203 #endif
3204
3205  restart_compile:
3206         if (method_is_gshared) {
3207                 method_to_compile = method;
3208         } else {
3209                 if (try_generic_shared) {
3210                         method_to_compile = mini_get_shared_method (method);
3211                         g_assert (method_to_compile);
3212                 } else {
3213                         method_to_compile = method;
3214                 }
3215         }
3216
3217         cfg = g_new0 (MonoCompile, 1);
3218         cfg->method = method_to_compile;
3219         cfg->header = mono_method_get_header (cfg->method);
3220         cfg->mempool = mono_mempool_new ();
3221         cfg->opt = opts;
3222         cfg->prof_options = mono_profiler_get_events ();
3223         cfg->run_cctors = run_cctors;
3224         cfg->domain = domain;
3225         cfg->verbose_level = mini_verbose;
3226         cfg->compile_aot = compile_aot;
3227         cfg->full_aot = full_aot;
3228         cfg->skip_visibility = method->skip_visibility;
3229         cfg->orig_method = method;
3230         cfg->gen_seq_points = debug_options.gen_seq_points_compact_data || debug_options.gen_sdb_seq_points;
3231         cfg->gen_sdb_seq_points = debug_options.gen_sdb_seq_points;
3232
3233 #ifdef PLATFORM_ANDROID
3234         if (cfg->method->wrapper_type != MONO_WRAPPER_NONE) {
3235                 /* FIXME: Why is this needed */
3236                 cfg->gen_seq_points = FALSE;
3237                 cfg->gen_sdb_seq_points = FALSE;
3238         }
3239 #endif
3240         /* coop / nacl requires loop detection to happen */
3241 #if defined(__native_client_codegen__) || defined(USE_COOP_GC)
3242         cfg->opt |= MONO_OPT_LOOP;
3243 #endif
3244
3245         cfg->explicit_null_checks = debug_options.explicit_null_checks;
3246         cfg->soft_breakpoints = debug_options.soft_breakpoints;
3247         cfg->check_pinvoke_callconv = debug_options.check_pinvoke_callconv;
3248         cfg->disable_direct_icalls = disable_direct_icalls;
3249         if (try_generic_shared)
3250                 cfg->generic_sharing_context = (MonoGenericSharingContext*)&cfg->gsctx;
3251         cfg->compile_llvm = try_llvm;
3252         cfg->token_info_hash = g_hash_table_new (NULL, NULL);
3253
3254         if (!mono_debug_count ())
3255                 cfg->opt &= ~MONO_OPT_FLOAT32;
3256         cfg->r4fp = (cfg->opt & MONO_OPT_FLOAT32) ? 1 : 0;
3257         cfg->r4_stack_type = cfg->r4fp ? STACK_R4 : STACK_R8;
3258
3259         if (cfg->gen_seq_points)
3260                 cfg->seq_points = g_ptr_array_new ();
3261         mono_error_init (&cfg->error);
3262
3263         if (cfg->compile_aot && !try_generic_shared && (method->is_generic || method->klass->generic_container || method_is_gshared)) {
3264                 cfg->exception_type = MONO_EXCEPTION_GENERIC_SHARING_FAILED;
3265                 return cfg;
3266         }
3267
3268         if (cfg->generic_sharing_context && (gsharedvt_method || mini_is_gsharedvt_sharable_method (method))) {
3269                 MonoMethodInflated *inflated;
3270                 MonoGenericContext *context;
3271
3272                 if (gsharedvt_method) {
3273                         g_assert (method->is_inflated);
3274                         inflated = (MonoMethodInflated*)method;
3275                         context = &inflated->context;
3276
3277                         /* We are compiling a gsharedvt method directly */
3278                         g_assert (compile_aot);
3279                 } else {
3280                         g_assert (method_to_compile->is_inflated);
3281                         inflated = (MonoMethodInflated*)method_to_compile;
3282                         context = &inflated->context;
3283                 }
3284
3285                 mini_init_gsctx (NULL, cfg->mempool, context, &cfg->gsctx);
3286                 cfg->gsctx_context = context;
3287
3288                 cfg->gsharedvt = TRUE;
3289                 // FIXME:
3290                 cfg->disable_llvm = TRUE;
3291         }
3292
3293         if (cfg->generic_sharing_context) {
3294                 method_to_register = method_to_compile;
3295                 cfg->gshared = TRUE;
3296         } else {
3297                 g_assert (method == method_to_compile);
3298                 method_to_register = method;
3299         }
3300         cfg->method_to_register = method_to_register;
3301
3302         mono_error_init (&err);
3303         sig = mono_method_signature_checked (cfg->method, &err);        
3304         if (!sig) {
3305                 cfg->exception_type = MONO_EXCEPTION_TYPE_LOAD;
3306                 cfg->exception_message = g_strdup (mono_error_get_message (&err));
3307                 mono_error_cleanup (&err);
3308                 if (MONO_METHOD_COMPILE_END_ENABLED ())
3309                         MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
3310                 return cfg;
3311         }
3312
3313         header = cfg->header;
3314         if (!header) {
3315                 MonoLoaderError *error;
3316
3317                 if ((error = mono_loader_get_last_error ())) {
3318                         cfg->exception_type = error->exception_type;
3319                 } else {
3320                         cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
3321                         cfg->exception_message = g_strdup_printf ("Missing or incorrect header for method %s", cfg->method->name);
3322                 }
3323                 if (MONO_METHOD_COMPILE_END_ENABLED ())
3324                         MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
3325                 return cfg;
3326         }
3327
3328 #ifdef ENABLE_LLVM
3329         {
3330                 static gboolean inited;
3331
3332                 if (!inited)
3333                         inited = TRUE;
3334
3335                 /* 
3336                  * Check for methods which cannot be compiled by LLVM early, to avoid
3337                  * the extra compilation pass.
3338                  */
3339                 if (COMPILE_LLVM (cfg)) {
3340                         mono_llvm_check_method_supported (cfg);
3341                         if (cfg->disable_llvm) {
3342                                 if (cfg->verbose_level >= 1) {
3343                                         //nm = mono_method_full_name (cfg->method, TRUE);
3344                                         printf ("LLVM failed for '%s': %s\n", method->name, cfg->exception_message);
3345                                         //g_free (nm);
3346                                 }
3347                                 mono_destroy_compile (cfg);
3348                                 try_llvm = FALSE;
3349                                 goto restart_compile;
3350                         }
3351                 }
3352         }
3353 #endif
3354
3355         /* The debugger has no liveness information, so avoid sharing registers/stack slots */
3356         if (debug_options.mdb_optimizations) {
3357                 cfg->disable_reuse_registers = TRUE;
3358                 cfg->disable_reuse_stack_slots = TRUE;
3359                 /* 
3360                  * This decreases the change the debugger will read registers/stack slots which are
3361                  * not yet initialized.
3362                  */
3363                 cfg->disable_initlocals_opt = TRUE;
3364
3365                 cfg->extend_live_ranges = TRUE;
3366
3367                 /* Temporarily disable this when running in the debugger until we have support
3368                  * for this in the debugger. */
3369                 /* This is no longer needed with sdb */
3370                 //cfg->disable_omit_fp = TRUE;
3371
3372                 /* The debugger needs all locals to be on the stack or in a global register */
3373                 cfg->disable_vreg_to_lvreg = TRUE;
3374
3375                 /* Don't remove unused variables when running inside the debugger since the user
3376                  * may still want to view them. */
3377                 cfg->disable_deadce_vars = TRUE;
3378
3379                 // cfg->opt |= MONO_OPT_SHARED;
3380                 cfg->opt &= ~MONO_OPT_DEADCE;
3381                 cfg->opt &= ~MONO_OPT_INLINE;
3382                 cfg->opt &= ~MONO_OPT_COPYPROP;
3383                 cfg->opt &= ~MONO_OPT_CONSPROP;
3384                 /* This is no longer needed with sdb */
3385                 //cfg->opt &= ~MONO_OPT_GSHARED;
3386
3387                 /* This is needed for the soft debugger, which doesn't like code after the epilog */
3388                 cfg->disable_out_of_line_bblocks = TRUE;
3389         }
3390
3391         if (mono_using_xdebug) {
3392                 /* 
3393                  * Make each variable use its own register/stack slot and extend 
3394                  * their liveness to cover the whole method, making them displayable
3395                  * in gdb even after they are dead.
3396                  */
3397                 cfg->disable_reuse_registers = TRUE;
3398                 cfg->disable_reuse_stack_slots = TRUE;
3399                 cfg->extend_live_ranges = TRUE;
3400                 cfg->compute_precise_live_ranges = TRUE;
3401         }
3402
3403         mini_gc_init_cfg (cfg);
3404
3405         if (COMPILE_LLVM (cfg)) {
3406                 cfg->opt |= MONO_OPT_ABCREM;
3407         }
3408
3409         if (!verbose_method_inited) {
3410                 verbose_method_name = g_getenv ("MONO_VERBOSE_METHOD");
3411                 verbose_method_inited = TRUE;
3412         }
3413         if (verbose_method_name) {
3414                 const char *name = verbose_method_name;
3415
3416                 if ((strchr (name, '.') > name) || strchr (name, ':')) {
3417                         MonoMethodDesc *desc;
3418                         
3419                         desc = mono_method_desc_new (name, TRUE);
3420                         if (mono_method_desc_full_match (desc, cfg->method)) {
3421                                 cfg->verbose_level = 4;
3422                         }
3423                         mono_method_desc_free (desc);
3424                 } else {
3425                         if (strcmp (cfg->method->name, name) == 0)
3426                                 cfg->verbose_level = 4;
3427                 }
3428         }
3429
3430         cfg->intvars = mono_mempool_alloc0 (cfg->mempool, sizeof (guint16) * STACK_MAX * header->max_stack);
3431
3432         if (cfg->verbose_level > 0) {
3433                 char *method_name;
3434
3435                 method_name = mono_method_full_name (method, TRUE);
3436                 g_print ("converting %s%s%smethod %s\n", COMPILE_LLVM (cfg) ? "llvm " : "", cfg->gsharedvt ? "gsharedvt " : "", (cfg->generic_sharing_context && !cfg->gsharedvt) ? "gshared " : "", method_name);
3437                 /*
3438                 if (COMPILE_LLVM (cfg))
3439                         g_print ("converting llvm method %s\n", method_name = mono_method_full_name (method, TRUE));
3440                 else if (cfg->gsharedvt)
3441                         g_print ("converting gsharedvt method %s\n", method_name = mono_method_full_name (method_to_compile, TRUE));
3442                 else if (cfg->generic_sharing_context)
3443                         g_print ("converting shared method %s\n", method_name = mono_method_full_name (method_to_compile, TRUE));
3444                 else
3445                         g_print ("converting method %s\n", method_name = mono_method_full_name (method, TRUE));
3446                 */
3447                 g_free (method_name);
3448         }
3449
3450         if (cfg->opt & MONO_OPT_ABCREM)
3451                 cfg->opt |= MONO_OPT_SSA;
3452
3453         /* 
3454         if ((cfg->method->klass->image != mono_defaults.corlib) || (strstr (cfg->method->klass->name, "StackOverflowException") && strstr (cfg->method->name, ".ctor")) || (strstr (cfg->method->klass->name, "OutOfMemoryException") && strstr (cfg->method->name, ".ctor")))
3455                 cfg->globalra = TRUE;
3456         */
3457
3458         //cfg->globalra = TRUE;
3459
3460         //if (!strcmp (cfg->method->klass->name, "Tests") && !cfg->method->wrapper_type)
3461         //      cfg->globalra = TRUE;
3462
3463         {
3464                 static int count = 0;
3465                 count ++;
3466
3467                 /*
3468                 if (g_getenv ("COUNT2")) {
3469                         cfg->globalra = TRUE;
3470                         if (count == atoi (g_getenv ("COUNT2")))
3471                                 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
3472                         if (count > atoi (g_getenv ("COUNT2")))
3473                                 cfg->globalra = FALSE;
3474                 }
3475                 */
3476         }
3477
3478         if (header->clauses)
3479                 cfg->globalra = FALSE;
3480
3481         if (cfg->method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED)
3482                 /* The code in the prolog clobbers caller saved registers */
3483                 cfg->globalra = FALSE;
3484
3485         // FIXME: Disable globalra in case of tracing/profiling
3486
3487         if (cfg->method->save_lmf)
3488                 /* The LMF saving code might clobber caller saved registers */
3489                 cfg->globalra = FALSE;
3490
3491         if (header->code_size > 5000)
3492                 // FIXME:
3493                 /* Too large bblocks could overflow the ins positions */
3494                 cfg->globalra = FALSE;
3495
3496         cfg->rs = mono_regstate_new ();
3497         if (cfg->globalra)
3498                 cfg->rs->next_vreg = MONO_MAX_IREGS + MONO_MAX_FREGS;
3499         cfg->next_vreg = cfg->rs->next_vreg;
3500
3501         /* FIXME: Fix SSA to handle branches inside bblocks */
3502         if (cfg->opt & MONO_OPT_SSA)
3503                 cfg->enable_extended_bblocks = FALSE;
3504
3505         /*
3506          * FIXME: This confuses liveness analysis because variables which are assigned after
3507          * a branch inside a bblock become part of the kill set, even though the assignment
3508          * might not get executed. This causes the optimize_initlocals pass to delete some
3509          * assignments which are needed.
3510          * Also, the mono_if_conversion pass needs to be modified to recognize the code
3511          * created by this.
3512          */
3513         //cfg->enable_extended_bblocks = TRUE;
3514
3515         /*We must verify the method before doing any IR generation as mono_compile_create_vars can assert.*/
3516         if (mono_compile_is_broken (cfg, cfg->method, TRUE)) {
3517                 if (mini_get_debug_options ()->break_on_unverified)
3518                         G_BREAKPOINT ();
3519                 return cfg;
3520         }
3521
3522         /*
3523          * create MonoInst* which represents arguments and local variables
3524          */
3525         mono_compile_create_vars (cfg);
3526
3527         i = mono_method_to_ir (cfg, method_to_compile, NULL, NULL, NULL, NULL, 0, FALSE);
3528
3529         if (i < 0) {
3530                 if (try_generic_shared && cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
3531                         if (compile_aot) {
3532                                 if (MONO_METHOD_COMPILE_END_ENABLED ())
3533                                         MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
3534                                 return cfg;
3535                         }
3536                         mono_destroy_compile (cfg);
3537                         try_generic_shared = FALSE;
3538                         goto restart_compile;
3539                 }
3540                 g_assert (cfg->exception_type != MONO_EXCEPTION_GENERIC_SHARING_FAILED);
3541
3542                 if (MONO_METHOD_COMPILE_END_ENABLED ())
3543                         MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
3544                 /* cfg contains the details of the failure, so let the caller cleanup */
3545                 return cfg;
3546         }
3547
3548         cfg->stat_basic_blocks += cfg->num_bblocks;
3549
3550         if (COMPILE_LLVM (cfg)) {
3551                 MonoInst *ins;
3552
3553                 /* The IR has to be in SSA form for LLVM */
3554                 cfg->opt |= MONO_OPT_SSA;
3555
3556                 // FIXME:
3557                 if (cfg->ret) {
3558                         // Allow SSA on the result value
3559                         cfg->ret->flags &= ~MONO_INST_VOLATILE;
3560
3561                         // Add an explicit return instruction referencing the return value
3562                         MONO_INST_NEW (cfg, ins, OP_SETRET);
3563                         ins->sreg1 = cfg->ret->dreg;
3564
3565                         MONO_ADD_INS (cfg->bb_exit, ins);
3566                 }
3567
3568                 cfg->opt &= ~MONO_OPT_LINEARS;
3569
3570                 /* FIXME: */
3571                 cfg->opt &= ~MONO_OPT_BRANCH;
3572         }
3573
3574         /* todo: remove code when we have verified that the liveness for try/catch blocks
3575          * works perfectly 
3576          */
3577         /* 
3578          * Currently, this can't be commented out since exception blocks are not
3579          * processed during liveness analysis.
3580          * It is also needed, because otherwise the local optimization passes would
3581          * delete assignments in cases like this:
3582          * r1 <- 1
3583          * <something which throws>
3584          * r1 <- 2
3585          * This also allows SSA to be run on methods containing exception clauses, since
3586          * SSA will ignore variables marked VOLATILE.
3587          */
3588         mono_liveness_handle_exception_clauses (cfg);
3589
3590         mono_handle_out_of_line_bblock (cfg);
3591
3592         /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/
3593
3594         if (!COMPILE_LLVM (cfg))
3595                 mono_decompose_long_opts (cfg);
3596
3597         /* Should be done before branch opts */
3598         if (cfg->opt & (MONO_OPT_CONSPROP | MONO_OPT_COPYPROP))
3599                 mono_local_cprop (cfg);
3600
3601         if (cfg->opt & MONO_OPT_BRANCH)
3602                 mono_optimize_branches (cfg);
3603
3604         /* This must be done _before_ global reg alloc and _after_ decompose */
3605         mono_handle_global_vregs (cfg);
3606         if (cfg->opt & MONO_OPT_DEADCE)
3607                 mono_local_deadce (cfg);
3608         if (cfg->opt & MONO_OPT_ALIAS_ANALYSIS)
3609                 mono_local_alias_analysis (cfg);
3610         /* Disable this for LLVM to make the IR easier to handle */
3611         if (!COMPILE_LLVM (cfg))
3612                 mono_if_conversion (cfg);
3613
3614         if (cfg->globalra)
3615                 mono_remove_critical_edges (cfg);
3616
3617         /* Depth-first ordering on basic blocks */
3618         cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
3619
3620         cfg->max_block_num = cfg->num_bblocks;
3621
3622         dfn = 0;
3623         df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
3624         if (cfg->num_bblocks != dfn + 1) {
3625                 MonoBasicBlock *bb;
3626
3627                 cfg->num_bblocks = dfn + 1;
3628
3629                 /* remove unreachable code, because the code in them may be 
3630                  * inconsistent  (access to dead variables for example) */
3631                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
3632                         bb->flags &= ~BB_VISITED;
3633                 compute_reachable (cfg->bb_entry);
3634                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
3635                         if (bb->flags & BB_EXCEPTION_HANDLER)
3636                                 compute_reachable (bb);
3637                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3638                         if (!(bb->flags & BB_VISITED)) {
3639                                 if (cfg->verbose_level > 1)
3640                                         g_print ("found unreachable code in BB%d\n", bb->block_num);
3641                                 bb->code = bb->last_ins = NULL;
3642                                 while (bb->out_count)
3643                                         mono_unlink_bblock (cfg, bb, bb->out_bb [0]);
3644                         }
3645                 }
3646                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
3647                         bb->flags &= ~BB_VISITED;
3648         }
3649
3650         if (((cfg->num_varinfo > 2000) || (cfg->num_bblocks > 1000)) && !cfg->compile_aot) {
3651                 /* 
3652                  * we disable some optimizations if there are too many variables
3653                  * because JIT time may become too expensive. The actual number needs 
3654                  * to be tweaked and eventually the non-linear algorithms should be fixed.
3655                  */
3656                 cfg->opt &= ~ (MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP);
3657                 cfg->disable_ssa = TRUE;
3658         }
3659
3660         if (cfg->opt & MONO_OPT_LOOP) {
3661                 mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM);
3662                 mono_compute_natural_loops (cfg);
3663         }
3664
3665         mono_insert_safepoints (cfg);
3666
3667         /* after method_to_ir */
3668         if (parts == 1) {
3669                 if (MONO_METHOD_COMPILE_END_ENABLED ())
3670                         MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
3671                 return cfg;
3672         }
3673
3674         /*
3675           if (header->num_clauses)
3676           cfg->disable_ssa = TRUE;
3677         */
3678
3679 //#define DEBUGSSA "logic_run"
3680 //#define DEBUGSSA_CLASS "Tests"
3681 #ifdef DEBUGSSA
3682
3683         if (!cfg->disable_ssa) {
3684                 mono_local_cprop (cfg);
3685
3686 #ifndef DISABLE_SSA
3687                 mono_ssa_compute (cfg);
3688 #endif
3689         }
3690 #else 
3691         if (cfg->opt & MONO_OPT_SSA) {
3692                 if (!(cfg->comp_done & MONO_COMP_SSA) && !cfg->disable_ssa) {
3693 #ifndef DISABLE_SSA
3694                         mono_ssa_compute (cfg);
3695 #endif
3696
3697                         if (cfg->verbose_level >= 2) {
3698                                 print_dfn (cfg);
3699                         }
3700                 }
3701         }
3702 #endif
3703
3704         /* after SSA translation */
3705         if (parts == 2) {
3706                 if (MONO_METHOD_COMPILE_END_ENABLED ())
3707                         MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
3708                 return cfg;
3709         }
3710
3711         if ((cfg->opt & MONO_OPT_CONSPROP) || (cfg->opt & MONO_OPT_COPYPROP)) {
3712                 if (cfg->comp_done & MONO_COMP_SSA && !COMPILE_LLVM (cfg)) {
3713 #ifndef DISABLE_SSA
3714                         mono_ssa_cprop (cfg);
3715 #endif
3716                 }
3717         }
3718
3719 #ifndef DISABLE_SSA
3720         if (cfg->comp_done & MONO_COMP_SSA && !COMPILE_LLVM (cfg)) {
3721                 //mono_ssa_strength_reduction (cfg);
3722
3723                 if (cfg->opt & MONO_OPT_DEADCE)
3724                         mono_ssa_deadce (cfg);
3725
3726                 if ((cfg->flags & (MONO_CFG_HAS_LDELEMA|MONO_CFG_HAS_CHECK_THIS)) && (cfg->opt & MONO_OPT_ABCREM))
3727                         mono_perform_abc_removal (cfg);
3728
3729                 mono_ssa_remove (cfg);
3730                 mono_local_cprop (cfg);
3731                 mono_handle_global_vregs (cfg);
3732                 if (cfg->opt & MONO_OPT_DEADCE)
3733                         mono_local_deadce (cfg);
3734
3735                 if (cfg->opt & MONO_OPT_BRANCH) {
3736                         MonoBasicBlock *bb;
3737
3738                         mono_optimize_branches (cfg);
3739
3740                         /* Have to recompute cfg->bblocks and bb->dfn */
3741                         if (cfg->globalra) {
3742                                 mono_remove_critical_edges (cfg);
3743
3744                                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
3745                                         bb->dfn = 0;
3746
3747                                 /* Depth-first ordering on basic blocks */
3748                                 cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
3749
3750                                 dfn = 0;
3751                                 df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
3752                                 cfg->num_bblocks = dfn + 1;
3753                         }
3754                 }
3755         }
3756 #endif
3757
3758         if (cfg->comp_done & MONO_COMP_SSA && COMPILE_LLVM (cfg)) {
3759                 mono_ssa_loop_invariant_code_motion (cfg);
3760                 /* This removes MONO_INST_FAULT flags too so perform it unconditionally */
3761                 if (cfg->opt & MONO_OPT_ABCREM)
3762                         mono_perform_abc_removal (cfg);
3763         }
3764
3765         /* after SSA removal */
3766         if (parts == 3) {
3767                 if (MONO_METHOD_COMPILE_END_ENABLED ())
3768                         MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
3769                 return cfg;
3770         }
3771
3772 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
3773         if (COMPILE_SOFT_FLOAT (cfg))
3774                 mono_decompose_soft_float (cfg);
3775 #endif
3776         if (COMPILE_LLVM (cfg))
3777                 mono_decompose_vtype_opts_llvm (cfg);
3778         else
3779                 mono_decompose_vtype_opts (cfg);
3780         if (cfg->flags & MONO_CFG_HAS_ARRAY_ACCESS)
3781                 mono_decompose_array_access_opts (cfg);
3782
3783         if (cfg->got_var) {
3784 #ifndef MONO_ARCH_GOT_REG
3785                 GList *regs;
3786 #endif
3787                 int got_reg;
3788
3789                 g_assert (cfg->got_var_allocated);
3790
3791                 /* 
3792                  * Allways allocate the GOT var to a register, because keeping it
3793                  * in memory will increase the number of live temporaries in some
3794                  * code created by inssel.brg, leading to the well known spills+
3795                  * branches problem. Testcase: mcs crash in 
3796                  * System.MonoCustomAttrs:GetCustomAttributes.
3797                  */
3798 #ifdef MONO_ARCH_GOT_REG
3799                 got_reg = MONO_ARCH_GOT_REG;
3800 #else
3801                 regs = mono_arch_get_global_int_regs (cfg);
3802                 g_assert (regs);
3803                 got_reg = GPOINTER_TO_INT (regs->data);
3804                 g_list_free (regs);
3805 #endif
3806                 cfg->got_var->opcode = OP_REGVAR;
3807                 cfg->got_var->dreg = got_reg;
3808                 cfg->used_int_regs |= 1LL << cfg->got_var->dreg;
3809         }
3810
3811         /*
3812          * Have to call this again to process variables added since the first call.
3813          */
3814         mono_liveness_handle_exception_clauses (cfg);
3815
3816         if (cfg->globalra) {
3817                 MonoBasicBlock *bb;
3818
3819                 /* Have to do this before regalloc since it can create vregs */
3820                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
3821                         mono_arch_lowering_pass (cfg, bb);
3822
3823                 mono_global_regalloc (cfg);
3824         }
3825
3826         if ((cfg->opt & MONO_OPT_LINEARS) && !cfg->globalra) {
3827                 GList *vars, *regs, *l;
3828                 
3829                 /* fixme: maybe we can avoid to compute livenesss here if already computed ? */
3830                 cfg->comp_done &= ~MONO_COMP_LIVENESS;
3831                 if (!(cfg->comp_done & MONO_COMP_LIVENESS))
3832                         mono_analyze_liveness (cfg);
3833
3834                 if ((vars = mono_arch_get_allocatable_int_vars (cfg))) {
3835                         regs = mono_arch_get_global_int_regs (cfg);
3836                         /* Remove the reg reserved for holding the GOT address */
3837                         if (cfg->got_var) {
3838                                 for (l = regs; l; l = l->next) {
3839                                         if (GPOINTER_TO_UINT (l->data) == cfg->got_var->dreg) {
3840                                                 regs = g_list_delete_link (regs, l);
3841                                                 break;
3842                                         }
3843                                 }
3844                         }
3845                         mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs);
3846                 }
3847         }
3848
3849         //mono_print_code (cfg, "");
3850
3851     //print_dfn (cfg);
3852         
3853         /* variables are allocated after decompose, since decompose could create temps */
3854         if (!cfg->globalra && !COMPILE_LLVM (cfg)) {
3855                 mono_arch_allocate_vars (cfg);
3856                 if (cfg->exception_type)
3857                         return cfg;
3858         }
3859
3860         {
3861                 MonoBasicBlock *bb;
3862                 gboolean need_local_opts;
3863
3864                 if (!cfg->globalra && !COMPILE_LLVM (cfg)) {
3865                         mono_spill_global_vars (cfg, &need_local_opts);
3866
3867                         if (need_local_opts || cfg->compile_aot) {
3868                                 /* To optimize code created by spill_global_vars */
3869                                 mono_local_cprop (cfg);
3870                                 if (cfg->opt & MONO_OPT_DEADCE)
3871                                         mono_local_deadce (cfg);
3872                         }
3873                 }
3874
3875                 /* Add branches between non-consecutive bblocks */
3876                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3877                         if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins) &&
3878                                 bb->last_ins->inst_false_bb && bb->next_bb != bb->last_ins->inst_false_bb) {
3879                                 /* we are careful when inverting, since bugs like #59580
3880                                  * could show up when dealing with NaNs.
3881                                  */
3882                                 if (MONO_IS_COND_BRANCH_NOFP(bb->last_ins) && bb->next_bb == bb->last_ins->inst_true_bb) {
3883                                         MonoBasicBlock *tmp =  bb->last_ins->inst_true_bb;
3884                                         bb->last_ins->inst_true_bb = bb->last_ins->inst_false_bb;
3885                                         bb->last_ins->inst_false_bb = tmp;
3886
3887                                         bb->last_ins->opcode = mono_reverse_branch_op (bb->last_ins->opcode);
3888                                 } else {                        
3889                                         MonoInst *inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
3890                                         inst->opcode = OP_BR;
3891                                         inst->inst_target_bb = bb->last_ins->inst_false_bb;
3892                                         mono_bblock_add_inst (bb, inst);
3893                                 }
3894                         }
3895                 }
3896
3897                 if (cfg->verbose_level >= 4 && !cfg->globalra) {
3898                         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3899                                 MonoInst *tree = bb->code;      
3900                                 g_print ("DUMP BLOCK %d:\n", bb->block_num);
3901                                 if (!tree)
3902                                         continue;
3903                                 for (; tree; tree = tree->next) {
3904                                         mono_print_ins_index (-1, tree);
3905                                 }
3906                         }
3907                 }
3908
3909                 /* FIXME: */
3910                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3911                         bb->max_vreg = cfg->next_vreg;
3912                 }
3913         }
3914
3915         if (COMPILE_LLVM (cfg)) {
3916 #ifdef ENABLE_LLVM
3917                 char *nm;
3918
3919                 /* The IR has to be in SSA form for LLVM */
3920                 if (!(cfg->comp_done & MONO_COMP_SSA)) {
3921                         cfg->exception_message = g_strdup ("SSA disabled.");
3922                         cfg->disable_llvm = TRUE;
3923                 }
3924
3925                 if (cfg->flags & MONO_CFG_HAS_ARRAY_ACCESS)
3926                         mono_decompose_array_access_opts (cfg);
3927
3928                 if (!cfg->disable_llvm)
3929                         mono_llvm_emit_method (cfg);
3930                 if (cfg->disable_llvm) {
3931                         if (cfg->verbose_level >= 1) {
3932                                 //nm = mono_method_full_name (cfg->method, TRUE);
3933                                 printf ("LLVM failed for '%s': %s\n", method->name, cfg->exception_message);
3934                                 //g_free (nm);
3935                         }
3936                         mono_destroy_compile (cfg);
3937                         try_llvm = FALSE;
3938                         goto restart_compile;
3939                 }
3940
3941                 if (cfg->verbose_level > 0 && !cfg->compile_aot) {
3942                         nm = mono_method_full_name (cfg->method, TRUE);
3943                         g_print ("LLVM Method %s emitted at %p to %p (code length %d) [%s]\n", 
3944                                          nm, 
3945                                          cfg->native_code, cfg->native_code + cfg->code_len, cfg->code_len, cfg->domain->friendly_name);
3946                         g_free (nm);
3947                 }
3948 #endif
3949         } else {
3950                 mono_codegen (cfg);
3951         }
3952
3953         if (COMPILE_LLVM (cfg))
3954                 InterlockedIncrement (&mono_jit_stats.methods_with_llvm);
3955         else
3956                 InterlockedIncrement (&mono_jit_stats.methods_without_llvm);
3957
3958         cfg->jit_info = create_jit_info (cfg, method_to_compile);
3959
3960 #ifdef MONO_ARCH_HAVE_LIVERANGE_OPS
3961         if (cfg->extend_live_ranges) {
3962                 /* Extend live ranges to cover the whole method */
3963                 for (i = 0; i < cfg->num_varinfo; ++i)
3964                         MONO_VARINFO (cfg, i)->live_range_end = cfg->code_len;
3965         }
3966 #endif
3967
3968         if (!cfg->compile_aot)
3969                 mono_save_xdebug_info (cfg);
3970
3971         mini_gc_create_gc_map (cfg);
3972  
3973         mono_save_seq_point_info (cfg);
3974
3975         if (cfg->verbose_level >= 2) {
3976                 char *id =  mono_method_full_name (cfg->method, FALSE);
3977                 mono_disassemble_code (cfg, cfg->native_code, cfg->code_len, id + 3);
3978                 g_free (id);
3979         }
3980
3981         if (!cfg->compile_aot) {
3982                 mono_domain_lock (cfg->domain);
3983                 mono_jit_info_table_add (cfg->domain, cfg->jit_info);
3984
3985                 if (cfg->method->dynamic)
3986                         mono_dynamic_code_hash_lookup (cfg->domain, cfg->method)->ji = cfg->jit_info;
3987                 mono_domain_unlock (cfg->domain);
3988         }
3989
3990 #if 0
3991         if (cfg->gsharedvt)
3992                 printf ("GSHAREDVT: %s\n", mono_method_full_name (cfg->method, TRUE));
3993 #endif
3994
3995         /* collect statistics */
3996 #ifndef DISABLE_PERFCOUNTERS
3997         mono_perfcounters->jit_methods++;
3998         mono_perfcounters->jit_bytes += header->code_size;
3999 #endif
4000         mono_jit_stats.allocated_code_size += cfg->code_len;
4001         code_size_ratio = cfg->code_len;
4002         if (code_size_ratio > mono_jit_stats.biggest_method_size && mono_jit_stats.enabled) {
4003                 mono_jit_stats.biggest_method_size = code_size_ratio;
4004                 g_free (mono_jit_stats.biggest_method);
4005                 mono_jit_stats.biggest_method = g_strdup_printf ("%s::%s)", method->klass->name, method->name);
4006         }
4007         code_size_ratio = (code_size_ratio * 100) / header->code_size;
4008         if (code_size_ratio > mono_jit_stats.max_code_size_ratio && mono_jit_stats.enabled) {
4009                 mono_jit_stats.max_code_size_ratio = code_size_ratio;
4010                 g_free (mono_jit_stats.max_ratio_method);
4011                 mono_jit_stats.max_ratio_method = g_strdup_printf ("%s::%s)", method->klass->name, method->name);
4012         }
4013         mono_jit_stats.native_code_size += cfg->code_len;
4014
4015         if (MONO_METHOD_COMPILE_END_ENABLED ())
4016                 MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
4017
4018         return cfg;
4019 }
4020
4021 #else
4022
4023 MonoCompile*
4024 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFlags flags, int parts)
4025 {
4026         g_assert_not_reached ();
4027         return NULL;
4028 }
4029
4030 #endif /* DISABLE_JIT */
4031
4032 gpointer
4033 mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain, int opt, MonoException **jit_ex)
4034 {
4035         MonoCompile *cfg;
4036         gpointer code = NULL;
4037         MonoJitInfo *jinfo, *info;
4038         MonoVTable *vtable;
4039         MonoException *ex = NULL;
4040         guint32 prof_options;
4041         GTimer *jit_timer;
4042         MonoMethod *prof_method, *shared;
4043
4044         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
4045             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4046                 MonoMethod *nm;
4047                 MonoMethodPInvoke* piinfo = (MonoMethodPInvoke *) method;
4048
4049                 if (!piinfo->addr) {
4050                         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
4051                                 piinfo->addr = mono_lookup_internal_call (method);
4052                         else if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)
4053 #ifdef HOST_WIN32
4054                                 g_warning ("Method '%s' in assembly '%s' contains native code that cannot be executed by Mono in modules loaded from byte arrays. The assembly was probably created using C++/CLI.\n", mono_method_full_name (method, TRUE), method->klass->image->name);
4055 #else
4056                                 g_warning ("Method '%s' in assembly '%s' contains native code that cannot be executed by Mono on this platform. The assembly was probably created using C++/CLI.\n", mono_method_full_name (method, TRUE), method->klass->image->name);
4057 #endif
4058                         else
4059                                 mono_lookup_pinvoke_call (method, NULL, NULL);
4060                 }
4061                 nm = mono_marshal_get_native_wrapper (method, check_for_pending_exc, mono_aot_only);
4062                 code = mono_get_addr_from_ftnptr (mono_compile_method (nm));
4063                 jinfo = mono_jit_info_table_find (target_domain, code);
4064                 if (!jinfo)
4065                         jinfo = mono_jit_info_table_find (mono_domain_get (), code);
4066                 if (jinfo)
4067                         mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
4068                 return code;
4069         } else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
4070                 const char *name = method->name;
4071                 char *full_name, *msg;
4072                 MonoMethod *nm;
4073
4074                 if (method->klass->parent == mono_defaults.multicastdelegate_class) {
4075                         if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
4076                                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name ("mono_delegate_ctor");
4077                                 g_assert (mi);
4078                                 /*
4079                                  * We need to make sure this wrapper
4080                                  * is compiled because it might end up
4081                                  * in an (M)RGCTX if generic sharing
4082                                  * is enabled, and would be called
4083                                  * indirectly.  If it were a
4084                                  * trampoline we'd try to patch that
4085                                  * indirect call, which is not
4086                                  * possible.
4087                                  */
4088                                 return mono_get_addr_from_ftnptr ((gpointer)mono_icall_get_wrapper_full (mi, TRUE));
4089                         } else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
4090 #ifdef MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE
4091                                 return mono_create_delegate_trampoline (target_domain, method->klass);
4092 #else
4093                                 nm = mono_marshal_get_delegate_invoke (method, NULL);
4094                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
4095 #endif
4096                         } else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
4097                                 nm = mono_marshal_get_delegate_begin_invoke (method);
4098                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
4099                         } else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
4100                                 nm = mono_marshal_get_delegate_end_invoke (method);
4101                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
4102                         }
4103                 }
4104
4105                 full_name = mono_method_full_name (method, TRUE);
4106                 msg = g_strdup_printf ("Unrecognizable runtime implemented method '%s'", full_name);
4107                 *jit_ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "InvalidProgramException", msg);
4108                 g_free (full_name);
4109                 g_free (msg);
4110                 return NULL;
4111         }
4112
4113         if (method->wrapper_type == MONO_WRAPPER_UNKNOWN) {
4114                 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
4115
4116                 if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT) {
4117                         static MonoTrampInfo *in_tinfo, *out_tinfo;
4118                         MonoTrampInfo *tinfo;
4119                         MonoJitInfo *jinfo;
4120                         gboolean is_in = info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN;
4121
4122                         if (is_in && in_tinfo)
4123                                 return in_tinfo->code;
4124                         else if (!is_in && out_tinfo)
4125                                 return out_tinfo->code;
4126
4127                         /*
4128                          * This is a special wrapper whose body is implemented in assembly, like a trampoline. We use a wrapper so EH
4129                          * works.
4130                          * FIXME: The caller signature doesn't match the callee, which might cause problems on some platforms
4131                          */
4132                         if (mono_aot_only)
4133                                 mono_aot_get_trampoline_full (is_in ? "gsharedvt_trampoline" : "gsharedvt_out_trampoline", &tinfo);
4134                         else
4135                                 mono_arch_get_gsharedvt_trampoline (&tinfo, FALSE);
4136                         jinfo = create_jit_info_for_trampoline (method, tinfo);
4137                         mono_jit_info_table_add (mono_get_root_domain (), jinfo);
4138                         if (is_in)
4139                                 in_tinfo = tinfo;
4140                         else
4141                                 out_tinfo = tinfo;
4142                         return tinfo->code;
4143                 }
4144         }
4145
4146         if (mono_aot_only) {
4147                 char *fullname = mono_method_full_name (method, TRUE);
4148                 char *msg = g_strdup_printf ("Attempting to JIT compile method '%s' while running with --aot-only. See http://docs.xamarin.com/ios/about/limitations for more information.\n", fullname);
4149
4150                 *jit_ex = mono_get_exception_execution_engine (msg);
4151                 g_free (fullname);
4152                 g_free (msg);
4153                 
4154                 return NULL;
4155         }
4156
4157         jit_timer = g_timer_new ();
4158
4159         cfg = mini_method_compile (method, opt, target_domain, JIT_FLAG_RUN_CCTORS, 0);
4160         prof_method = cfg->method;
4161
4162         g_timer_stop (jit_timer);
4163         mono_jit_stats.jit_time += g_timer_elapsed (jit_timer, NULL);
4164         g_timer_destroy (jit_timer);
4165
4166         switch (cfg->exception_type) {
4167         case MONO_EXCEPTION_NONE:
4168                 break;
4169         case MONO_EXCEPTION_TYPE_LOAD:
4170         case MONO_EXCEPTION_MISSING_FIELD:
4171         case MONO_EXCEPTION_MISSING_METHOD:
4172         case MONO_EXCEPTION_FILE_NOT_FOUND:
4173         case MONO_EXCEPTION_BAD_IMAGE: {
4174                 /* Throw a type load exception if needed */
4175                 MonoLoaderError *error = mono_loader_get_last_error ();
4176
4177                 if (error) {
4178                         ex = mono_loader_error_prepare_exception (error);
4179                 } else {
4180                         if (cfg->exception_ptr) {
4181                                 ex = mono_class_get_exception_for_failure (cfg->exception_ptr);
4182                         } else {
4183                                 if (cfg->exception_type == MONO_EXCEPTION_MISSING_FIELD)
4184                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingFieldException", cfg->exception_message);
4185                                 else if (cfg->exception_type == MONO_EXCEPTION_MISSING_METHOD)
4186                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingMethodException", cfg->exception_message);
4187                                 else if (cfg->exception_type == MONO_EXCEPTION_TYPE_LOAD)
4188                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "TypeLoadException", cfg->exception_message);
4189                                 else if (cfg->exception_type == MONO_EXCEPTION_FILE_NOT_FOUND)
4190                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System.IO", "FileNotFoundException", cfg->exception_message);
4191                                 else if (cfg->exception_type == MONO_EXCEPTION_BAD_IMAGE)
4192                                         ex = mono_get_exception_bad_image_format (cfg->exception_message);
4193                                 else
4194                                         g_assert_not_reached ();
4195                         }
4196                 }
4197                 break;
4198         }
4199         case MONO_EXCEPTION_INVALID_PROGRAM:
4200                 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "InvalidProgramException", cfg->exception_message);
4201                 break;
4202         case MONO_EXCEPTION_UNVERIFIABLE_IL:
4203                 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System.Security", "VerificationException", cfg->exception_message);
4204                 break;
4205         case MONO_EXCEPTION_METHOD_ACCESS:
4206                 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MethodAccessException", cfg->exception_message);
4207                 break;
4208         case MONO_EXCEPTION_FIELD_ACCESS:
4209                 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "FieldAccessException", cfg->exception_message);
4210                 break;
4211 #ifndef DISABLE_SECURITY
4212         /* this can only be set if the security manager is active */
4213         case MONO_EXCEPTION_SECURITY_LINKDEMAND: {
4214                 MonoSecurityManager* secman = mono_security_manager_get_methods ();
4215                 MonoObject *exc = NULL;
4216                 gpointer args [2];
4217
4218                 args [0] = &cfg->exception_data;
4219                 args [1] = &method;
4220                 mono_runtime_invoke (secman->linkdemandsecurityexception, NULL, args, &exc);
4221
4222                 ex = (MonoException*)exc;
4223                 break;
4224         }
4225 #endif
4226         case MONO_EXCEPTION_OBJECT_SUPPLIED: {
4227                 MonoException *exp = cfg->exception_ptr;
4228                 MONO_GC_UNREGISTER_ROOT (cfg->exception_ptr);
4229
4230                 ex = exp;
4231                 break;
4232         }
4233         case MONO_EXCEPTION_OUT_OF_MEMORY:
4234                 ex = mono_domain_get ()->out_of_memory_ex;
4235                 break;
4236         case MONO_EXCEPTION_MONO_ERROR:
4237                 g_assert (!mono_error_ok (&cfg->error));
4238                 ex = mono_error_convert_to_exception (&cfg->error);
4239                 break;
4240         default:
4241                 g_assert_not_reached ();
4242         }
4243
4244         if (ex) {
4245                 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
4246                         mono_profiler_method_end_jit (method, NULL, MONO_PROFILE_FAILED);
4247
4248                 mono_destroy_compile (cfg);
4249                 *jit_ex = ex;
4250
4251                 return NULL;
4252         }
4253
4254         if (mono_method_is_generic_sharable (method, FALSE))
4255                 shared = mini_get_shared_method (method);
4256         else
4257                 shared = NULL;
4258
4259         mono_domain_lock (target_domain);
4260
4261         /* Check if some other thread already did the job. In this case, we can
4262        discard the code this thread generated. */
4263
4264         info = mini_lookup_method (target_domain, method, shared);
4265         if (info) {
4266                 /* We can't use a domain specific method in another domain */
4267                 if ((target_domain == mono_domain_get ()) || info->domain_neutral) {
4268                         code = info->code_start;
4269 //                      printf("Discarding code for method %s\n", method->name);
4270                 }
4271         }
4272         if (code == NULL) {
4273                 /* The lookup + insert is atomic since this is done inside the domain lock */
4274                 mono_domain_jit_code_hash_lock (target_domain);
4275                 mono_internal_hash_table_insert (&target_domain->jit_code_hash, cfg->jit_info->d.method, cfg->jit_info);
4276                 mono_domain_jit_code_hash_unlock (target_domain);
4277
4278                 code = cfg->native_code;
4279
4280                 if (cfg->generic_sharing_context && mono_method_is_generic_sharable (method, FALSE))
4281                         mono_stats.generics_shared_methods++;
4282                 if (cfg->gsharedvt)
4283                         mono_stats.gsharedvt_methods++;
4284         }
4285
4286         jinfo = cfg->jit_info;
4287
4288         prof_options = cfg->prof_options;
4289
4290         /*
4291          * Update global stats while holding a lock, instead of doing many
4292          * InterlockedIncrement operations during JITting.
4293          */
4294         mono_jit_stats.allocate_var += cfg->stat_allocate_var;
4295         mono_jit_stats.locals_stack_size += cfg->stat_locals_stack_size;
4296         mono_jit_stats.basic_blocks += cfg->stat_basic_blocks;
4297         mono_jit_stats.max_basic_blocks = MAX (cfg->stat_basic_blocks, mono_jit_stats.max_basic_blocks);
4298         mono_jit_stats.cil_code_size += cfg->stat_cil_code_size;
4299         mono_jit_stats.regvars += cfg->stat_n_regvars;
4300         mono_jit_stats.inlineable_methods += cfg->stat_inlineable_methods;
4301         mono_jit_stats.inlined_methods += cfg->stat_inlined_methods;
4302         mono_jit_stats.cas_demand_generation += cfg->stat_cas_demand_generation;
4303         mono_jit_stats.code_reallocs += cfg->stat_code_reallocs;
4304
4305         mono_destroy_compile (cfg);
4306
4307 #ifndef DISABLE_JIT
4308         if (domain_jit_info (target_domain)->jump_target_hash) {
4309                 MonoJumpInfo patch_info;
4310                 MonoJumpList *jlist;
4311                 GSList *tmp;
4312                 jlist = g_hash_table_lookup (domain_jit_info (target_domain)->jump_target_hash, method);
4313                 if (jlist) {
4314                         patch_info.next = NULL;
4315                         patch_info.ip.i = 0;
4316                         patch_info.type = MONO_PATCH_INFO_METHOD_JUMP;
4317                         patch_info.data.method = method;
4318                         g_hash_table_remove (domain_jit_info (target_domain)->jump_target_hash, method);
4319
4320 #if defined(__native_client_codegen__) && defined(__native_client__)
4321                         /* These patches are applied after a method has been installed, no target munging is needed. */
4322                         nacl_allow_target_modification (FALSE);
4323 #endif
4324 #ifdef MONO_ARCH_HAVE_PATCH_CODE_NEW
4325                         for (tmp = jlist->list; tmp; tmp = tmp->next) {
4326                                 gpointer target = mono_resolve_patch_target (NULL, target_domain, tmp->data, &patch_info, TRUE);
4327                                 mono_arch_patch_code_new (NULL, target_domain, tmp->data, &patch_info, target);
4328                         }
4329 #else
4330                         for (tmp = jlist->list; tmp; tmp = tmp->next)
4331                                 mono_arch_patch_code (NULL, NULL, target_domain, tmp->data, &patch_info, TRUE);
4332 #endif
4333 #if defined(__native_client_codegen__) && defined(__native_client__)
4334                         nacl_allow_target_modification (TRUE);
4335 #endif
4336                 }
4337         }
4338
4339         mono_emit_jit_map (jinfo);
4340 #endif
4341         mono_domain_unlock (target_domain);
4342
4343         vtable = mono_class_vtable (target_domain, method->klass);
4344         if (!vtable) {
4345                 ex = mono_class_get_exception_for_failure (method->klass);
4346                 g_assert (ex);
4347                 *jit_ex = ex;
4348                 return NULL;
4349         }
4350
4351         if (prof_options & MONO_PROFILE_JIT_COMPILATION) {
4352                 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
4353                         if (mono_marshal_method_from_wrapper (method)) {
4354                                 /* Native func wrappers have no method */
4355                                 /* The profiler doesn't know about wrappers, so pass the original icall method */
4356                                 mono_profiler_method_end_jit (mono_marshal_method_from_wrapper (method), jinfo, MONO_PROFILE_OK);
4357                         }
4358                 }
4359                 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
4360                 if (prof_method != method) {
4361                         mono_profiler_method_end_jit (prof_method, jinfo, MONO_PROFILE_OK);
4362                 }
4363         }
4364
4365         ex = mono_runtime_class_init_full (vtable, FALSE);
4366         if (ex) {
4367                 *jit_ex = ex;
4368                 return NULL;
4369         }
4370         return code;
4371 }
4372
4373 #ifndef DISABLE_JIT
4374
4375 void*
4376 mono_arch_instrument_epilog (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments) {
4377         return mono_arch_instrument_epilog_full (cfg, func, p, enable_arguments, FALSE);
4378 }
4379
4380 void
4381 mono_cfg_add_try_hole (MonoCompile *cfg, MonoExceptionClause *clause, guint8 *start, MonoBasicBlock *bb)
4382 {
4383         TryBlockHole *hole = mono_mempool_alloc (cfg->mempool, sizeof (TryBlockHole));
4384         hole->clause = clause;
4385         hole->start_offset = start - cfg->native_code;
4386         hole->basic_block = bb;
4387
4388         cfg->try_block_holes = g_slist_append_mempool (cfg->mempool, cfg->try_block_holes, hole);
4389 }
4390
4391 void
4392 mono_cfg_set_exception (MonoCompile *cfg, int type)
4393 {
4394         cfg->exception_type = type;
4395 }
4396
4397 #endif
4398
4399 /* Dummy versions of some arch specific functions to avoid ifdefs at call sites */
4400
4401 #ifndef MONO_ARCH_GSHAREDVT_SUPPORTED
4402
4403 gboolean
4404 mono_arch_gsharedvt_sig_supported (MonoMethodSignature *sig)
4405 {
4406         return FALSE;
4407 }
4408
4409 gpointer
4410 mono_arch_get_gsharedvt_call_info (gpointer addr, MonoMethodSignature *normal_sig, MonoMethodSignature *gsharedvt_sig, MonoGenericSharingContext *gsctx, gboolean gsharedvt_in, gint32 vcall_offset, gboolean calli)
4411 {
4412         g_assert_not_reached ();
4413         return NULL;
4414 }
4415
4416 gpointer
4417 mono_arch_get_gsharedvt_arg_trampoline (MonoDomain *domain, gpointer arg, gpointer addr)
4418 {
4419         g_assert_not_reached ();
4420         return NULL;
4421 }
4422
4423 gpointer
4424 mono_arch_get_gsharedvt_trampoline (MonoTrampInfo **info, gboolean aot)
4425 {
4426         g_assert_not_reached ();
4427         return NULL;
4428 }
4429
4430 #endif
4431
4432 #if defined(MONO_ARCH_GSHAREDVT_SUPPORTED) && !defined(ENABLE_GSHAREDVT)
4433
4434 gboolean
4435 mono_arch_gsharedvt_sig_supported (MonoMethodSignature *sig)
4436 {
4437         return FALSE;
4438 }
4439
4440 gpointer
4441 mono_arch_get_gsharedvt_call_info (gpointer addr, MonoMethodSignature *normal_sig, MonoMethodSignature *gsharedvt_sig, MonoGenericSharingContext *gsctx, gboolean gsharedvt_in, gint32 vcall_offset, gboolean calli)
4442 {
4443         NOT_IMPLEMENTED;
4444         return NULL;
4445 }
4446
4447 #endif
4448
4449 #ifdef USE_JUMP_TABLES
4450 #define DEFAULT_JUMPTABLE_CHUNK_ELEMENTS 128
4451
4452 typedef struct MonoJumpTableChunk {
4453         guint32 total;
4454         guint32 active;
4455         struct MonoJumpTableChunk *previous;
4456         /* gpointer entries[total]; */
4457 } MonoJumpTableChunk;
4458
4459 static MonoJumpTableChunk* g_jumptable;
4460 #define mono_jumptable_lock() mono_mutex_lock (&jumptable_mutex)
4461 #define mono_jumptable_unlock() mono_mutex_unlock (&jumptable_mutex)
4462 static mono_mutex_t jumptable_mutex;
4463
4464 static  MonoJumpTableChunk*
4465 mono_create_jumptable_chunk (guint32 max_entries)
4466 {
4467         guint32 size = sizeof (MonoJumpTableChunk) + max_entries * sizeof(gpointer);
4468         MonoJumpTableChunk *chunk = (MonoJumpTableChunk*) g_new0 (guchar, size);
4469         chunk->total = max_entries;
4470         return chunk;
4471 }
4472
4473 void
4474 mono_jumptable_init (void)
4475 {
4476         if (g_jumptable == NULL) {
4477                 mono_mutex_init_recursive (&jumptable_mutex);
4478                 g_jumptable = mono_create_jumptable_chunk (DEFAULT_JUMPTABLE_CHUNK_ELEMENTS);
4479         }
4480 }
4481
4482 gpointer*
4483 mono_jumptable_add_entry (void)
4484 {
4485         return mono_jumptable_add_entries (1);
4486 }
4487
4488 gpointer*
4489 mono_jumptable_add_entries (guint32 entries)
4490 {
4491         guint32 index;
4492         gpointer *result;
4493
4494         mono_jumptable_init ();
4495         mono_jumptable_lock ();
4496         index = g_jumptable->active;
4497         if (index + entries >= g_jumptable->total) {
4498                 /*
4499                  * Grow jumptable, by adding one more chunk.
4500                  * We cannot realloc jumptable, as there could be pointers
4501                  * to existing jump table entries in the code, so instead
4502                  * we just add one more chunk.
4503                  */
4504                 guint32 max_entries = entries;
4505                 MonoJumpTableChunk *new_chunk;
4506
4507                 if (max_entries < DEFAULT_JUMPTABLE_CHUNK_ELEMENTS)
4508                         max_entries = DEFAULT_JUMPTABLE_CHUNK_ELEMENTS;
4509                 new_chunk = mono_create_jumptable_chunk (max_entries);
4510                 /* Link old jumptable, so that we could free it up later. */
4511                 new_chunk->previous = g_jumptable;
4512                 g_jumptable = new_chunk;
4513                 index = 0;
4514         }
4515         g_jumptable->active = index + entries;
4516         result = (gpointer*)((guchar*)g_jumptable + sizeof(MonoJumpTableChunk)) + index;
4517         mono_jumptable_unlock();
4518
4519         return result;
4520 }
4521
4522 void
4523 mono_jumptable_cleanup (void)
4524 {
4525         if (g_jumptable) {
4526                 MonoJumpTableChunk *current = g_jumptable, *prev;
4527                 while (current != NULL) {
4528                         prev = current->previous;
4529                         g_free (current);
4530                         current = prev;
4531                 }
4532                 g_jumptable = NULL;
4533                 mono_mutex_destroy (&jumptable_mutex);
4534         }
4535 }
4536
4537 gpointer*
4538 mono_jumptable_get_entry (guint8 *code_ptr)
4539 {
4540         return mono_arch_jumptable_entry_from_code (code_ptr);
4541 }
4542 #endif
4543
4544 /*
4545  * mini_replace_type:
4546  *
4547  * Replace the type used in the metadata stream with what the JIT will actually use during compilation.
4548 */
4549 MonoType*
4550 mini_replace_type (MonoType *type)
4551 {
4552         type = mono_type_get_underlying_type (type);
4553         return mini_native_type_replace_type (type);
4554 }
4555
4556 /*
4557  * mini_get_underlying_type:
4558  *
4559  *   Return the type the JIT will use during compilation.
4560  * Handles: byref, enums, native types, generic sharing.
4561  * For gsharedvt types, it will return the original VAR/MVAR.
4562  */
4563 MonoType*
4564 mini_get_underlying_type (MonoCompile *cfg, MonoType *type)
4565 {
4566         type = mini_type_get_underlying_type (cfg->generic_sharing_context, type);
4567         return mini_native_type_replace_type (type);
4568 }
4569
4570 void
4571 mini_jit_init (void)
4572 {
4573         mono_mutex_init_recursive (&jit_mutex);
4574 }
4575
4576 void
4577 mini_jit_cleanup (void)
4578 {
4579         g_free (emul_opcode_map);
4580         g_free (emul_opcode_opcodes);
4581 }