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