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