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