2 * mini.c: The new Mono code generator.
5 * Paolo Molaro (lupus@ximian.com)
6 * Dietmar Maurer (dietmar@ximian.com)
8 * Copyright 2002-2003 Ximian, Inc.
9 * Copyright 2003-2010 Novell, Inc.
10 * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
11 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
22 #ifdef HAVE_SYS_TIME_H
26 #include <mono/utils/memcheck.h>
28 #include <mono/metadata/assembly.h>
29 #include <mono/metadata/loader.h>
30 #include <mono/metadata/tabledefs.h>
31 #include <mono/metadata/class.h>
32 #include <mono/metadata/object.h>
33 #include <mono/metadata/tokentype.h>
34 #include <mono/metadata/tabledefs.h>
35 #include <mono/metadata/threads.h>
36 #include <mono/metadata/appdomain.h>
37 #include <mono/metadata/debug-helpers.h>
38 #include "mono/metadata/profiler.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/utils/mono-math.h>
51 #include <mono/utils/mono-compiler.h>
52 #include <mono/utils/mono-counters.h>
53 #include <mono/utils/mono-error-internals.h>
54 #include <mono/utils/mono-logger-internals.h>
55 #include <mono/utils/mono-mmap.h>
56 #include <mono/utils/mono-path.h>
57 #include <mono/utils/mono-tls.h>
58 #include <mono/utils/mono-hwcap.h>
59 #include <mono/utils/dtrace.h>
60 #include <mono/utils/mono-threads.h>
61 #include <mono/utils/mono-threads-coop.h>
62 #include <mono/io-layer/io-layer.h>
65 #include "seq-points.h"
73 #include "jit-icalls.h"
76 #include "debugger-agent.h"
77 #include "llvm-runtime.h"
78 #include "mini-llvm.h"
80 MonoTraceSpec *mono_jit_trace_calls;
81 MonoMethodDesc *mono_inject_async_exc_method;
82 int mono_inject_async_exc_pos;
83 MonoMethodDesc *mono_break_at_bb_method;
84 int mono_break_at_bb_bb_num;
85 gboolean mono_do_x86_stack_align = TRUE;
86 gboolean mono_using_xdebug;
89 static guint32 discarded_code;
90 static double discarded_jit_time;
92 #define mono_jit_lock() mono_os_mutex_lock (&jit_mutex)
93 #define mono_jit_unlock() mono_os_mutex_unlock (&jit_mutex)
94 static mono_mutex_t jit_mutex;
96 MonoBackend *current_backend;
101 mono_realloc_native_code (MonoCompile *cfg)
103 return g_realloc (cfg->native_code, cfg->code_size);
107 MonoExceptionClause *clause;
108 MonoBasicBlock *basic_block;
113 * mono_emit_unwind_op:
115 * Add an unwind op with the given parameters for the list of unwind ops stored in
119 mono_emit_unwind_op (MonoCompile *cfg, int when, int tag, int reg, int val)
121 MonoUnwindOp *op = (MonoUnwindOp *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoUnwindOp));
128 cfg->unwind_ops = g_slist_append_mempool (cfg->mempool, cfg->unwind_ops, op);
129 if (cfg->verbose_level > 1) {
132 printf ("CFA: [%x] def_cfa: %s+0x%x\n", when, mono_arch_regname (reg), val);
134 case DW_CFA_def_cfa_register:
135 printf ("CFA: [%x] def_cfa_reg: %s\n", when, mono_arch_regname (reg));
137 case DW_CFA_def_cfa_offset:
138 printf ("CFA: [%x] def_cfa_offset: 0x%x\n", when, val);
141 printf ("CFA: [%x] offset: %s at cfa-0x%x\n", when, mono_arch_regname (reg), -val);
147 #define MONO_INIT_VARINFO(vi,id) do { \
148 (vi)->range.first_use.pos.bid = 0xffff; \
154 * mono_unlink_bblock:
156 * Unlink two basic blocks.
159 mono_unlink_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
165 for (i = 0; i < from->out_count; ++i) {
166 if (to == from->out_bb [i]) {
173 for (i = 0; i < from->out_count; ++i) {
174 if (from->out_bb [i] != to)
175 from->out_bb [pos ++] = from->out_bb [i];
177 g_assert (pos == from->out_count - 1);
182 for (i = 0; i < to->in_count; ++i) {
183 if (from == to->in_bb [i]) {
190 for (i = 0; i < to->in_count; ++i) {
191 if (to->in_bb [i] != from)
192 to->in_bb [pos ++] = to->in_bb [i];
194 g_assert (pos == to->in_count - 1);
200 * mono_bblocks_linked:
202 * Return whenever BB1 and BB2 are linked in the CFG.
205 mono_bblocks_linked (MonoBasicBlock *bb1, MonoBasicBlock *bb2)
209 for (i = 0; i < bb1->out_count; ++i) {
210 if (bb1->out_bb [i] == bb2)
218 mono_find_block_region_notry (MonoCompile *cfg, int offset)
220 MonoMethodHeader *header = cfg->header;
221 MonoExceptionClause *clause;
224 for (i = 0; i < header->num_clauses; ++i) {
225 clause = &header->clauses [i];
226 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->data.filter_offset) &&
227 (offset < (clause->handler_offset)))
228 return ((i + 1) << 8) | MONO_REGION_FILTER | clause->flags;
230 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
231 if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
232 return ((i + 1) << 8) | MONO_REGION_FINALLY | clause->flags;
233 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
234 return ((i + 1) << 8) | MONO_REGION_FAULT | clause->flags;
236 return ((i + 1) << 8) | MONO_REGION_CATCH | clause->flags;
244 * mono_get_block_region_notry:
246 * Return the region corresponding to REGION, ignoring try clauses nested inside
250 mono_get_block_region_notry (MonoCompile *cfg, int region)
252 if ((region & (0xf << 4)) == MONO_REGION_TRY) {
253 MonoMethodHeader *header = cfg->header;
256 * This can happen if a try clause is nested inside a finally clause.
258 int clause_index = (region >> 8) - 1;
259 g_assert (clause_index >= 0 && clause_index < header->num_clauses);
261 region = mono_find_block_region_notry (cfg, header->clauses [clause_index].try_offset);
268 mono_find_spvar_for_region (MonoCompile *cfg, int region)
270 region = mono_get_block_region_notry (cfg, region);
272 return (MonoInst *)g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
276 df_visit (MonoBasicBlock *start, int *dfn, MonoBasicBlock **array)
280 array [*dfn] = start;
281 /* g_print ("visit %d at %p (BB%ld)\n", *dfn, start->cil_code, start->block_num); */
282 for (i = 0; i < start->out_count; ++i) {
283 if (start->out_bb [i]->dfn)
286 start->out_bb [i]->dfn = *dfn;
287 start->out_bb [i]->df_parent = start;
288 array [*dfn] = start->out_bb [i];
289 df_visit (start->out_bb [i], dfn, array);
294 mono_reverse_branch_op (guint32 opcode)
296 static const int reverse_map [] = {
297 CEE_BNE_UN, CEE_BLT, CEE_BLE, CEE_BGT, CEE_BGE,
298 CEE_BEQ, CEE_BLT_UN, CEE_BLE_UN, CEE_BGT_UN, CEE_BGE_UN
300 static const int reverse_fmap [] = {
301 OP_FBNE_UN, OP_FBLT, OP_FBLE, OP_FBGT, OP_FBGE,
302 OP_FBEQ, OP_FBLT_UN, OP_FBLE_UN, OP_FBGT_UN, OP_FBGE_UN
304 static const int reverse_lmap [] = {
305 OP_LBNE_UN, OP_LBLT, OP_LBLE, OP_LBGT, OP_LBGE,
306 OP_LBEQ, OP_LBLT_UN, OP_LBLE_UN, OP_LBGT_UN, OP_LBGE_UN
308 static const int reverse_imap [] = {
309 OP_IBNE_UN, OP_IBLT, OP_IBLE, OP_IBGT, OP_IBGE,
310 OP_IBEQ, OP_IBLT_UN, OP_IBLE_UN, OP_IBGT_UN, OP_IBGE_UN
313 if (opcode >= CEE_BEQ && opcode <= CEE_BLT_UN) {
314 opcode = reverse_map [opcode - CEE_BEQ];
315 } else if (opcode >= OP_FBEQ && opcode <= OP_FBLT_UN) {
316 opcode = reverse_fmap [opcode - OP_FBEQ];
317 } else if (opcode >= OP_LBEQ && opcode <= OP_LBLT_UN) {
318 opcode = reverse_lmap [opcode - OP_LBEQ];
319 } else if (opcode >= OP_IBEQ && opcode <= OP_IBLT_UN) {
320 opcode = reverse_imap [opcode - OP_IBEQ];
322 g_assert_not_reached ();
328 mono_type_to_store_membase (MonoCompile *cfg, MonoType *type)
330 type = mini_get_underlying_type (type);
333 switch (type->type) {
336 return OP_STOREI1_MEMBASE_REG;
339 return OP_STOREI2_MEMBASE_REG;
342 return OP_STOREI4_MEMBASE_REG;
346 case MONO_TYPE_FNPTR:
347 return OP_STORE_MEMBASE_REG;
348 case MONO_TYPE_CLASS:
349 case MONO_TYPE_STRING:
350 case MONO_TYPE_OBJECT:
351 case MONO_TYPE_SZARRAY:
352 case MONO_TYPE_ARRAY:
353 return OP_STORE_MEMBASE_REG;
356 return OP_STOREI8_MEMBASE_REG;
358 return OP_STORER4_MEMBASE_REG;
360 return OP_STORER8_MEMBASE_REG;
361 case MONO_TYPE_VALUETYPE:
362 if (type->data.klass->enumtype) {
363 type = mono_class_enum_basetype (type->data.klass);
366 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
367 return OP_STOREX_MEMBASE;
368 return OP_STOREV_MEMBASE;
369 case MONO_TYPE_TYPEDBYREF:
370 return OP_STOREV_MEMBASE;
371 case MONO_TYPE_GENERICINST:
372 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
373 return OP_STOREX_MEMBASE;
374 type = &type->data.generic_class->container_class->byval_arg;
378 g_assert (mini_type_var_is_vt (type));
379 return OP_STOREV_MEMBASE;
381 g_error ("unknown type 0x%02x in type_to_store_membase", type->type);
387 mono_type_to_load_membase (MonoCompile *cfg, MonoType *type)
389 type = mini_get_underlying_type (type);
391 switch (type->type) {
393 return OP_LOADI1_MEMBASE;
395 return OP_LOADU1_MEMBASE;
397 return OP_LOADI2_MEMBASE;
399 return OP_LOADU2_MEMBASE;
401 return OP_LOADI4_MEMBASE;
403 return OP_LOADU4_MEMBASE;
407 case MONO_TYPE_FNPTR:
408 return OP_LOAD_MEMBASE;
409 case MONO_TYPE_CLASS:
410 case MONO_TYPE_STRING:
411 case MONO_TYPE_OBJECT:
412 case MONO_TYPE_SZARRAY:
413 case MONO_TYPE_ARRAY:
414 return OP_LOAD_MEMBASE;
417 return OP_LOADI8_MEMBASE;
419 return OP_LOADR4_MEMBASE;
421 return OP_LOADR8_MEMBASE;
422 case MONO_TYPE_VALUETYPE:
423 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
424 return OP_LOADX_MEMBASE;
425 case MONO_TYPE_TYPEDBYREF:
426 return OP_LOADV_MEMBASE;
427 case MONO_TYPE_GENERICINST:
428 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
429 return OP_LOADX_MEMBASE;
430 if (mono_type_generic_inst_is_valuetype (type))
431 return OP_LOADV_MEMBASE;
433 return OP_LOAD_MEMBASE;
437 g_assert (cfg->gshared);
438 g_assert (mini_type_var_is_vt (type));
439 return OP_LOADV_MEMBASE;
441 g_error ("unknown type 0x%02x in type_to_load_membase", type->type);
447 mini_type_to_stind (MonoCompile* cfg, MonoType *type)
449 type = mini_get_underlying_type (type);
450 if (cfg->gshared && !type->byref && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)) {
451 g_assert (mini_type_var_is_vt (type));
454 return mono_type_to_stind (type);
458 mono_op_imm_to_op (int opcode)
462 #if SIZEOF_REGISTER == 4
480 #if SIZEOF_REGISTER == 4
486 #if SIZEOF_REGISTER == 4
492 #if SIZEOF_REGISTER == 4
538 #if SIZEOF_REGISTER == 4
544 #if SIZEOF_REGISTER == 4
563 case OP_ICOMPARE_IMM:
565 case OP_LOCALLOC_IMM:
573 * mono_decompose_op_imm:
575 * Replace the OP_.._IMM INS with its non IMM variant.
578 mono_decompose_op_imm (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins)
580 int opcode2 = mono_op_imm_to_op (ins->opcode);
583 const char *spec = INS_INFO (ins->opcode);
585 if (spec [MONO_INST_SRC2] == 'l') {
586 dreg = mono_alloc_lreg (cfg);
588 /* Load the 64bit constant using decomposed ops */
589 MONO_INST_NEW (cfg, temp, OP_ICONST);
590 temp->inst_c0 = ins->inst_ls_word;
591 temp->dreg = MONO_LVREG_LS (dreg);
592 mono_bblock_insert_before_ins (bb, ins, temp);
594 MONO_INST_NEW (cfg, temp, OP_ICONST);
595 temp->inst_c0 = ins->inst_ms_word;
596 temp->dreg = MONO_LVREG_MS (dreg);
598 dreg = mono_alloc_ireg (cfg);
600 MONO_INST_NEW (cfg, temp, OP_ICONST);
601 temp->inst_c0 = ins->inst_imm;
605 mono_bblock_insert_before_ins (bb, ins, temp);
608 g_error ("mono_op_imm_to_op failed for %s\n", mono_inst_name (ins->opcode));
609 ins->opcode = opcode2;
611 if (ins->opcode == OP_LOCALLOC)
616 bb->max_vreg = MAX (bb->max_vreg, cfg->next_vreg);
620 set_vreg_to_inst (MonoCompile *cfg, int vreg, MonoInst *inst)
622 if (vreg >= cfg->vreg_to_inst_len) {
623 MonoInst **tmp = cfg->vreg_to_inst;
624 int size = cfg->vreg_to_inst_len;
626 while (vreg >= cfg->vreg_to_inst_len)
627 cfg->vreg_to_inst_len = cfg->vreg_to_inst_len ? cfg->vreg_to_inst_len * 2 : 32;
628 cfg->vreg_to_inst = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * cfg->vreg_to_inst_len);
630 memcpy (cfg->vreg_to_inst, tmp, size * sizeof (MonoInst*));
632 cfg->vreg_to_inst [vreg] = inst;
635 #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)))
636 #define mono_type_is_float(type) (!(type)->byref && (((type)->type == MONO_TYPE_R8) || ((type)->type == MONO_TYPE_R4)))
639 mono_compile_create_var_for_vreg (MonoCompile *cfg, MonoType *type, int opcode, int vreg)
642 int num = cfg->num_varinfo;
645 type = mini_get_underlying_type (type);
647 if ((num + 1) >= cfg->varinfo_count) {
648 int orig_count = cfg->varinfo_count;
649 cfg->varinfo_count = cfg->varinfo_count ? (cfg->varinfo_count * 2) : 32;
650 cfg->varinfo = (MonoInst **)g_realloc (cfg->varinfo, sizeof (MonoInst*) * cfg->varinfo_count);
651 cfg->vars = (MonoMethodVar *)g_realloc (cfg->vars, sizeof (MonoMethodVar) * cfg->varinfo_count);
652 memset (&cfg->vars [orig_count], 0, (cfg->varinfo_count - orig_count) * sizeof (MonoMethodVar));
655 cfg->stat_allocate_var++;
657 MONO_INST_NEW (cfg, inst, opcode);
659 inst->inst_vtype = type;
660 inst->klass = mono_class_from_mono_type (type);
661 type_to_eval_stack_type (cfg, type, inst);
662 /* if set to 1 the variable is native */
663 inst->backend.is_pinvoke = 0;
666 if (mono_class_has_failure (inst->klass))
667 mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD);
669 if (cfg->compute_gc_maps) {
671 mono_mark_vreg_as_mp (cfg, vreg);
673 if ((MONO_TYPE_ISSTRUCT (type) && inst->klass->has_references) || mini_type_is_reference (type)) {
674 inst->flags |= MONO_INST_GC_TRACK;
675 mono_mark_vreg_as_ref (cfg, vreg);
680 cfg->varinfo [num] = inst;
682 MONO_INIT_VARINFO (&cfg->vars [num], num);
683 MONO_VARINFO (cfg, num)->vreg = vreg;
686 set_vreg_to_inst (cfg, vreg, inst);
688 #if SIZEOF_REGISTER == 4
689 if (mono_arch_is_soft_float ()) {
690 regpair = mono_type_is_long (type) || mono_type_is_float (type);
692 regpair = mono_type_is_long (type);
702 * These two cannot be allocated using create_var_for_vreg since that would
703 * put it into the cfg->varinfo array, confusing many parts of the JIT.
707 * Set flags to VOLATILE so SSA skips it.
710 if (cfg->verbose_level >= 4) {
711 printf (" Create LVAR R%d (R%d, R%d)\n", inst->dreg, MONO_LVREG_LS (inst->dreg), MONO_LVREG_MS (inst->dreg));
714 if (mono_arch_is_soft_float () && cfg->opt & MONO_OPT_SSA) {
715 if (mono_type_is_float (type))
716 inst->flags = MONO_INST_VOLATILE;
719 /* Allocate a dummy MonoInst for the first vreg */
720 MONO_INST_NEW (cfg, tree, OP_LOCAL);
721 tree->dreg = MONO_LVREG_LS (inst->dreg);
722 if (cfg->opt & MONO_OPT_SSA)
723 tree->flags = MONO_INST_VOLATILE;
725 tree->type = STACK_I4;
726 tree->inst_vtype = &mono_defaults.int32_class->byval_arg;
727 tree->klass = mono_class_from_mono_type (tree->inst_vtype);
729 set_vreg_to_inst (cfg, MONO_LVREG_LS (inst->dreg), tree);
731 /* Allocate a dummy MonoInst for the second vreg */
732 MONO_INST_NEW (cfg, tree, OP_LOCAL);
733 tree->dreg = MONO_LVREG_MS (inst->dreg);
734 if (cfg->opt & MONO_OPT_SSA)
735 tree->flags = MONO_INST_VOLATILE;
737 tree->type = STACK_I4;
738 tree->inst_vtype = &mono_defaults.int32_class->byval_arg;
739 tree->klass = mono_class_from_mono_type (tree->inst_vtype);
741 set_vreg_to_inst (cfg, MONO_LVREG_MS (inst->dreg), tree);
745 if (cfg->verbose_level > 2)
746 g_print ("created temp %d (R%d) of type %s\n", num, vreg, mono_type_get_name (type));
751 mono_compile_create_var (MonoCompile *cfg, MonoType *type, int opcode)
754 type = mini_get_underlying_type (type);
756 if (mono_type_is_long (type))
757 dreg = mono_alloc_dreg (cfg, STACK_I8);
758 else if (mono_arch_is_soft_float () && mono_type_is_float (type))
759 dreg = mono_alloc_dreg (cfg, STACK_R8);
761 /* All the others are unified */
762 dreg = mono_alloc_preg (cfg);
764 return mono_compile_create_var_for_vreg (cfg, type, opcode, dreg);
768 mini_get_int_to_float_spill_area (MonoCompile *cfg)
771 if (!cfg->iconv_raw_var) {
772 cfg->iconv_raw_var = mono_compile_create_var (cfg, &mono_defaults.int32_class->byval_arg, OP_LOCAL);
773 cfg->iconv_raw_var->flags |= MONO_INST_VOLATILE; /*FIXME, use the don't regalloc flag*/
775 return cfg->iconv_raw_var;
782 mono_mark_vreg_as_ref (MonoCompile *cfg, int vreg)
784 if (vreg >= cfg->vreg_is_ref_len) {
785 gboolean *tmp = cfg->vreg_is_ref;
786 int size = cfg->vreg_is_ref_len;
788 while (vreg >= cfg->vreg_is_ref_len)
789 cfg->vreg_is_ref_len = cfg->vreg_is_ref_len ? cfg->vreg_is_ref_len * 2 : 32;
790 cfg->vreg_is_ref = (gboolean *)mono_mempool_alloc0 (cfg->mempool, sizeof (gboolean) * cfg->vreg_is_ref_len);
792 memcpy (cfg->vreg_is_ref, tmp, size * sizeof (gboolean));
794 cfg->vreg_is_ref [vreg] = TRUE;
798 mono_mark_vreg_as_mp (MonoCompile *cfg, int vreg)
800 if (vreg >= cfg->vreg_is_mp_len) {
801 gboolean *tmp = cfg->vreg_is_mp;
802 int size = cfg->vreg_is_mp_len;
804 while (vreg >= cfg->vreg_is_mp_len)
805 cfg->vreg_is_mp_len = cfg->vreg_is_mp_len ? cfg->vreg_is_mp_len * 2 : 32;
806 cfg->vreg_is_mp = (gboolean *)mono_mempool_alloc0 (cfg->mempool, sizeof (gboolean) * cfg->vreg_is_mp_len);
808 memcpy (cfg->vreg_is_mp, tmp, size * sizeof (gboolean));
810 cfg->vreg_is_mp [vreg] = TRUE;
814 type_from_stack_type (MonoInst *ins)
817 case STACK_I4: return &mono_defaults.int32_class->byval_arg;
818 case STACK_I8: return &mono_defaults.int64_class->byval_arg;
819 case STACK_PTR: return &mono_defaults.int_class->byval_arg;
820 case STACK_R8: return &mono_defaults.double_class->byval_arg;
823 * this if used to be commented without any specific reason, but
824 * it breaks #80235 when commented
827 return &ins->klass->this_arg;
829 return &mono_defaults.object_class->this_arg;
831 /* ins->klass may not be set for ldnull.
832 * Also, if we have a boxed valuetype, we want an object lass,
833 * not the valuetype class
835 if (ins->klass && !ins->klass->valuetype)
836 return &ins->klass->byval_arg;
837 return &mono_defaults.object_class->byval_arg;
838 case STACK_VTYPE: return &ins->klass->byval_arg;
840 g_error ("stack type %d to montype not handled\n", ins->type);
846 mono_type_from_stack_type (MonoInst *ins)
848 return type_from_stack_type (ins);
852 * mono_add_ins_to_end:
854 * Same as MONO_ADD_INS, but add INST before any branches at the end of BB.
857 mono_add_ins_to_end (MonoBasicBlock *bb, MonoInst *inst)
862 MONO_ADD_INS (bb, inst);
866 switch (bb->last_ins->opcode) {
880 mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
883 if (MONO_IS_COND_BRANCH_OP (bb->last_ins)) {
884 /* Need to insert the ins before the compare */
885 if (bb->code == bb->last_ins) {
886 mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
890 if (bb->code->next == bb->last_ins) {
891 /* Only two instructions */
892 opcode = bb->code->opcode;
894 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)) {
896 mono_bblock_insert_before_ins (bb, bb->code, inst);
898 mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
901 opcode = bb->last_ins->prev->opcode;
903 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)) {
905 mono_bblock_insert_before_ins (bb, bb->last_ins->prev, inst);
907 mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
912 MONO_ADD_INS (bb, inst);
918 mono_create_jump_table (MonoCompile *cfg, MonoInst *label, MonoBasicBlock **bbs, int num_blocks)
920 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
921 MonoJumpInfoBBTable *table;
923 table = (MonoJumpInfoBBTable *)mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfoBBTable));
925 table->table_size = num_blocks;
927 ji->ip.label = label;
928 ji->type = MONO_PATCH_INFO_SWITCH;
929 ji->data.table = table;
930 ji->next = cfg->patch_info;
931 cfg->patch_info = ji;
934 static MonoMethodSignature *
935 mono_get_array_new_va_signature (int arity)
937 static GHashTable *sighash;
938 MonoMethodSignature *res;
943 sighash = g_hash_table_new (NULL, NULL);
945 else if ((res = (MonoMethodSignature *)g_hash_table_lookup (sighash, GINT_TO_POINTER (arity)))) {
950 res = mono_metadata_signature_alloc (mono_defaults.corlib, arity + 1);
953 if (ARCH_VARARG_ICALLS)
954 /* Only set this only some archs since not all backends can handle varargs+pinvoke */
955 res->call_convention = MONO_CALL_VARARG;
958 res->call_convention = MONO_CALL_C;
961 res->params [0] = &mono_defaults.int_class->byval_arg;
962 for (i = 0; i < arity; i++)
963 res->params [i + 1] = &mono_defaults.int_class->byval_arg;
965 res->ret = &mono_defaults.object_class->byval_arg;
967 g_hash_table_insert (sighash, GINT_TO_POINTER (arity), res);
974 mono_get_array_new_va_icall (int rank)
976 MonoMethodSignature *esig;
977 char icall_name [256];
979 MonoJitICallInfo *info;
981 /* Need to register the icall so it gets an icall wrapper */
982 sprintf (icall_name, "ves_array_new_va_%d", rank);
985 info = mono_find_jit_icall_by_name (icall_name);
987 esig = mono_get_array_new_va_signature (rank);
988 name = g_strdup (icall_name);
989 info = mono_register_jit_icall (mono_array_new_va, name, esig, FALSE);
997 mini_class_is_system_array (MonoClass *klass)
999 if (klass->parent == mono_defaults.array_class)
1006 mini_assembly_can_skip_verification (MonoDomain *domain, MonoMethod *method)
1008 MonoAssembly *assembly = method->klass->image->assembly;
1009 if (method->wrapper_type != MONO_WRAPPER_NONE && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
1011 if (assembly->in_gac || assembly->image == mono_defaults.corlib)
1013 return mono_assembly_has_skip_verification (assembly);
1017 * mini_method_verify:
1019 * Verify the method using the verfier.
1021 * Returns true if the method is invalid.
1024 mini_method_verify (MonoCompile *cfg, MonoMethod *method, gboolean fail_compile)
1027 gboolean is_fulltrust;
1029 if (method->verification_success)
1032 if (!mono_verifier_is_enabled_for_method (method))
1035 /*skip verification implies the assembly must be */
1036 is_fulltrust = mono_verifier_is_method_full_trust (method) || mini_assembly_can_skip_verification (cfg->domain, method);
1038 res = mono_method_verify_with_current_settings (method, cfg->skip_visibility, is_fulltrust);
1041 for (tmp = res; tmp; tmp = tmp->next) {
1042 MonoVerifyInfoExtended *info = (MonoVerifyInfoExtended *)tmp->data;
1043 if (info->info.status == MONO_VERIFY_ERROR) {
1045 char *method_name = mono_method_full_name (method, TRUE);
1046 cfg->exception_type = info->exception_type;
1047 cfg->exception_message = g_strdup_printf ("Error verifying %s: %s", method_name, info->info.message);
1048 g_free (method_name);
1050 mono_free_verify_list (res);
1053 if (info->info.status == MONO_VERIFY_NOT_VERIFIABLE && (!is_fulltrust || info->exception_type == MONO_EXCEPTION_METHOD_ACCESS || info->exception_type == MONO_EXCEPTION_FIELD_ACCESS)) {
1055 char *method_name = mono_method_full_name (method, TRUE);
1056 char *msg = g_strdup_printf ("Error verifying %s: %s", method_name, info->info.message);
1058 if (info->exception_type == MONO_EXCEPTION_METHOD_ACCESS)
1059 mono_error_set_generic_error (&cfg->error, "System", "MethodAccessException", "%s", msg);
1060 else if (info->exception_type == MONO_EXCEPTION_FIELD_ACCESS)
1061 mono_error_set_generic_error (&cfg->error, "System", "FieldAccessException", "%s", msg);
1062 else if (info->exception_type == MONO_EXCEPTION_UNVERIFIABLE_IL)
1063 mono_error_set_generic_error (&cfg->error, "System.Security", "VerificationException", "%s", msg);
1064 if (!mono_error_ok (&cfg->error)) {
1065 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
1068 cfg->exception_type = info->exception_type;
1069 cfg->exception_message = msg;
1071 g_free (method_name);
1073 mono_free_verify_list (res);
1077 mono_free_verify_list (res);
1079 method->verification_success = 1;
1083 /*Returns true if something went wrong*/
1085 mono_compile_is_broken (MonoCompile *cfg, MonoMethod *method, gboolean fail_compile)
1087 MonoMethod *method_definition = method;
1088 gboolean dont_verify = method->klass->image->assembly->corlib_internal;
1090 while (method_definition->is_inflated) {
1091 MonoMethodInflated *imethod = (MonoMethodInflated *) method_definition;
1092 method_definition = imethod->declaring;
1095 return !dont_verify && mini_method_verify (cfg, method_definition, fail_compile);
1099 mono_dynamic_code_hash_insert (MonoDomain *domain, MonoMethod *method, MonoJitDynamicMethodInfo *ji)
1101 if (!domain_jit_info (domain)->dynamic_code_hash)
1102 domain_jit_info (domain)->dynamic_code_hash = g_hash_table_new (NULL, NULL);
1103 g_hash_table_insert (domain_jit_info (domain)->dynamic_code_hash, method, ji);
1106 static MonoJitDynamicMethodInfo*
1107 mono_dynamic_code_hash_lookup (MonoDomain *domain, MonoMethod *method)
1109 MonoJitDynamicMethodInfo *res;
1111 if (domain_jit_info (domain)->dynamic_code_hash)
1112 res = (MonoJitDynamicMethodInfo *)g_hash_table_lookup (domain_jit_info (domain)->dynamic_code_hash, method);
1120 GList *active, *inactive;
1125 compare_by_interval_start_pos_func (gconstpointer a, gconstpointer b)
1127 MonoMethodVar *v1 = (MonoMethodVar*)a;
1128 MonoMethodVar *v2 = (MonoMethodVar*)b;
1132 else if (v1->interval->range && v2->interval->range)
1133 return v1->interval->range->from - v2->interval->range->from;
1134 else if (v1->interval->range)
1141 #define LSCAN_DEBUG(a) do { a; } while (0)
1143 #define LSCAN_DEBUG(a)
1147 mono_allocate_stack_slots2 (MonoCompile *cfg, gboolean backward, guint32 *stack_size, guint32 *stack_align)
1149 int i, slot, offset, size;
1154 GList *vars = NULL, *l, *unhandled;
1155 StackSlotInfo *scalar_stack_slots, *vtype_stack_slots, *slot_info;
1158 gboolean reuse_slot;
1160 LSCAN_DEBUG (printf ("Allocate Stack Slots 2 for %s:\n", mono_method_full_name (cfg->method, TRUE)));
1162 scalar_stack_slots = (StackSlotInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * MONO_TYPE_PINNED);
1163 vtype_stack_slots = NULL;
1166 offsets = (gint32 *)mono_mempool_alloc (cfg->mempool, sizeof (gint32) * cfg->num_varinfo);
1167 for (i = 0; i < cfg->num_varinfo; ++i)
1170 for (i = cfg->locals_start; i < cfg->num_varinfo; i++) {
1171 inst = cfg->varinfo [i];
1172 vmv = MONO_VARINFO (cfg, i);
1174 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR || inst->opcode == OP_REGOFFSET)
1177 vars = g_list_prepend (vars, vmv);
1180 vars = g_list_sort (vars, compare_by_interval_start_pos_func);
1185 for (unhandled = vars; unhandled; unhandled = unhandled->next) {
1186 MonoMethodVar *current = unhandled->data;
1188 if (current->interval->range) {
1189 g_assert (current->interval->range->from >= i);
1190 i = current->interval->range->from;
1197 for (unhandled = vars; unhandled; unhandled = unhandled->next) {
1198 MonoMethodVar *current = (MonoMethodVar *)unhandled->data;
1201 inst = cfg->varinfo [vmv->idx];
1203 t = mono_type_get_underlying_type (inst->inst_vtype);
1204 if (cfg->gsharedvt && mini_is_gsharedvt_variable_type (t))
1207 /* inst->backend.is_pinvoke indicates native sized value types, this is used by the
1208 * pinvoke wrappers when they call functions returning structures */
1209 if (inst->backend.is_pinvoke && MONO_TYPE_ISSTRUCT (t) && t->type != MONO_TYPE_TYPEDBYREF) {
1210 size = mono_class_native_size (mono_class_from_mono_type (t), &align);
1215 size = mini_type_stack_size (t, &ialign);
1218 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (t)))
1223 if (cfg->disable_reuse_stack_slots)
1226 t = mini_get_underlying_type (t);
1228 case MONO_TYPE_GENERICINST:
1229 if (!mono_type_generic_inst_is_valuetype (t)) {
1230 slot_info = &scalar_stack_slots [t->type];
1234 case MONO_TYPE_VALUETYPE:
1235 if (!vtype_stack_slots)
1236 vtype_stack_slots = (StackSlotInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * 256);
1237 for (i = 0; i < nvtypes; ++i)
1238 if (t->data.klass == vtype_stack_slots [i].vtype)
1241 slot_info = &vtype_stack_slots [i];
1243 g_assert (nvtypes < 256);
1244 vtype_stack_slots [nvtypes].vtype = t->data.klass;
1245 slot_info = &vtype_stack_slots [nvtypes];
1248 if (cfg->disable_reuse_ref_stack_slots)
1255 #if SIZEOF_VOID_P == 4
1260 if (cfg->disable_ref_noref_stack_slot_share) {
1261 slot_info = &scalar_stack_slots [MONO_TYPE_I];
1266 case MONO_TYPE_CLASS:
1267 case MONO_TYPE_OBJECT:
1268 case MONO_TYPE_ARRAY:
1269 case MONO_TYPE_SZARRAY:
1270 case MONO_TYPE_STRING:
1271 /* Share non-float stack slots of the same size */
1272 slot_info = &scalar_stack_slots [MONO_TYPE_CLASS];
1273 if (cfg->disable_reuse_ref_stack_slots)
1278 slot_info = &scalar_stack_slots [t->type];
1282 if (cfg->comp_done & MONO_COMP_LIVENESS) {
1286 //printf ("START %2d %08x %08x\n", vmv->idx, vmv->range.first_use.abs_pos, vmv->range.last_use.abs_pos);
1288 if (!current->interval->range) {
1289 if (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))
1293 inst->flags |= MONO_INST_IS_DEAD;
1298 pos = current->interval->range->from;
1300 LSCAN_DEBUG (printf ("process R%d ", inst->dreg));
1301 if (current->interval->range)
1302 LSCAN_DEBUG (mono_linterval_print (current->interval));
1303 LSCAN_DEBUG (printf ("\n"));
1305 /* Check for intervals in active which expired or inactive */
1307 /* FIXME: Optimize this */
1310 for (l = slot_info->active; l != NULL; l = l->next) {
1311 MonoMethodVar *v = (MonoMethodVar*)l->data;
1313 if (v->interval->last_range->to < pos) {
1314 slot_info->active = g_list_delete_link (slot_info->active, l);
1315 slot_info->slots = g_slist_prepend_mempool (cfg->mempool, slot_info->slots, GINT_TO_POINTER (offsets [v->idx]));
1316 LSCAN_DEBUG (printf ("Interval R%d has expired, adding 0x%x to slots\n", cfg->varinfo [v->idx]->dreg, offsets [v->idx]));
1320 else if (!mono_linterval_covers (v->interval, pos)) {
1321 slot_info->inactive = g_list_append (slot_info->inactive, v);
1322 slot_info->active = g_list_delete_link (slot_info->active, l);
1323 LSCAN_DEBUG (printf ("Interval R%d became inactive\n", cfg->varinfo [v->idx]->dreg));
1330 /* Check for intervals in inactive which expired or active */
1332 /* FIXME: Optimize this */
1335 for (l = slot_info->inactive; l != NULL; l = l->next) {
1336 MonoMethodVar *v = (MonoMethodVar*)l->data;
1338 if (v->interval->last_range->to < pos) {
1339 slot_info->inactive = g_list_delete_link (slot_info->inactive, l);
1340 // FIXME: Enabling this seems to cause impossible to debug crashes
1341 //slot_info->slots = g_slist_prepend_mempool (cfg->mempool, slot_info->slots, GINT_TO_POINTER (offsets [v->idx]));
1342 LSCAN_DEBUG (printf ("Interval R%d has expired, adding 0x%x to slots\n", cfg->varinfo [v->idx]->dreg, offsets [v->idx]));
1346 else if (mono_linterval_covers (v->interval, pos)) {
1347 slot_info->active = g_list_append (slot_info->active, v);
1348 slot_info->inactive = g_list_delete_link (slot_info->inactive, l);
1349 LSCAN_DEBUG (printf ("\tInterval R%d became active\n", cfg->varinfo [v->idx]->dreg));
1357 * This also handles the case when the variable is used in an
1358 * exception region, as liveness info is not computed there.
1361 * FIXME: All valuetypes are marked as INDIRECT because of LDADDR
1364 if (! (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
1365 if (slot_info->slots) {
1366 slot = GPOINTER_TO_INT (slot_info->slots->data);
1368 slot_info->slots = slot_info->slots->next;
1371 /* FIXME: We might want to consider the inactive intervals as well if slot_info->slots is empty */
1373 slot_info->active = mono_varlist_insert_sorted (cfg, slot_info->active, vmv, TRUE);
1379 static int count = 0;
1382 if (count == atoi (g_getenv ("COUNT3")))
1383 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
1384 if (count > atoi (g_getenv ("COUNT3")))
1387 mono_print_ins (inst);
1392 LSCAN_DEBUG (printf ("R%d %s -> 0x%x\n", inst->dreg, mono_type_full_name (t), slot));
1394 if (inst->flags & MONO_INST_LMF) {
1395 size = sizeof (MonoLMF);
1396 align = sizeof (mgreg_t);
1403 if (slot == 0xffffff) {
1405 * Allways allocate valuetypes to sizeof (gpointer) to allow more
1406 * efficient copying (and to work around the fact that OP_MEMCPY
1407 * and OP_MEMSET ignores alignment).
1409 if (MONO_TYPE_ISSTRUCT (t)) {
1410 align = MAX (align, sizeof (gpointer));
1411 align = MAX (align, mono_class_min_align (mono_class_from_mono_type (t)));
1416 offset += align - 1;
1417 offset &= ~(align - 1);
1421 offset += align - 1;
1422 offset &= ~(align - 1);
1427 if (*stack_align == 0)
1428 *stack_align = align;
1431 offsets [vmv->idx] = slot;
1434 for (i = 0; i < MONO_TYPE_PINNED; ++i) {
1435 if (scalar_stack_slots [i].active)
1436 g_list_free (scalar_stack_slots [i].active);
1438 for (i = 0; i < nvtypes; ++i) {
1439 if (vtype_stack_slots [i].active)
1440 g_list_free (vtype_stack_slots [i].active);
1443 cfg->stat_locals_stack_size += offset;
1445 *stack_size = offset;
1450 * mono_allocate_stack_slots:
1452 * Allocate stack slots for all non register allocated variables using a
1453 * linear scan algorithm.
1454 * Returns: an array of stack offsets.
1455 * STACK_SIZE is set to the amount of stack space needed.
1456 * STACK_ALIGN is set to the alignment needed by the locals area.
1459 mono_allocate_stack_slots (MonoCompile *cfg, gboolean backward, guint32 *stack_size, guint32 *stack_align)
1461 int i, slot, offset, size;
1466 GList *vars = NULL, *l;
1467 StackSlotInfo *scalar_stack_slots, *vtype_stack_slots, *slot_info;
1470 gboolean reuse_slot;
1472 if ((cfg->num_varinfo > 0) && MONO_VARINFO (cfg, 0)->interval)
1473 return mono_allocate_stack_slots2 (cfg, backward, stack_size, stack_align);
1475 scalar_stack_slots = (StackSlotInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * MONO_TYPE_PINNED);
1476 vtype_stack_slots = NULL;
1479 offsets = (gint32 *)mono_mempool_alloc (cfg->mempool, sizeof (gint32) * cfg->num_varinfo);
1480 for (i = 0; i < cfg->num_varinfo; ++i)
1483 for (i = cfg->locals_start; i < cfg->num_varinfo; i++) {
1484 inst = cfg->varinfo [i];
1485 vmv = MONO_VARINFO (cfg, i);
1487 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR || inst->opcode == OP_REGOFFSET)
1490 vars = g_list_prepend (vars, vmv);
1493 vars = mono_varlist_sort (cfg, vars, 0);
1495 *stack_align = sizeof(mgreg_t);
1496 for (l = vars; l; l = l->next) {
1497 vmv = (MonoMethodVar *)l->data;
1498 inst = cfg->varinfo [vmv->idx];
1500 t = mono_type_get_underlying_type (inst->inst_vtype);
1501 if (cfg->gsharedvt && mini_is_gsharedvt_variable_type (t))
1504 /* inst->backend.is_pinvoke indicates native sized value types, this is used by the
1505 * pinvoke wrappers when they call functions returning structures */
1506 if (inst->backend.is_pinvoke && MONO_TYPE_ISSTRUCT (t) && t->type != MONO_TYPE_TYPEDBYREF) {
1507 size = mono_class_native_size (mono_class_from_mono_type (t), &align);
1511 size = mini_type_stack_size (t, &ialign);
1514 if (mono_class_has_failure (mono_class_from_mono_type (t)))
1515 mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD);
1517 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (t)))
1522 if (cfg->disable_reuse_stack_slots)
1525 t = mini_get_underlying_type (t);
1527 case MONO_TYPE_GENERICINST:
1528 if (!mono_type_generic_inst_is_valuetype (t)) {
1529 slot_info = &scalar_stack_slots [t->type];
1533 case MONO_TYPE_VALUETYPE:
1534 if (!vtype_stack_slots)
1535 vtype_stack_slots = (StackSlotInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * 256);
1536 for (i = 0; i < nvtypes; ++i)
1537 if (t->data.klass == vtype_stack_slots [i].vtype)
1540 slot_info = &vtype_stack_slots [i];
1542 g_assert (nvtypes < 256);
1543 vtype_stack_slots [nvtypes].vtype = t->data.klass;
1544 slot_info = &vtype_stack_slots [nvtypes];
1547 if (cfg->disable_reuse_ref_stack_slots)
1554 #if SIZEOF_VOID_P == 4
1559 if (cfg->disable_ref_noref_stack_slot_share) {
1560 slot_info = &scalar_stack_slots [MONO_TYPE_I];
1565 case MONO_TYPE_CLASS:
1566 case MONO_TYPE_OBJECT:
1567 case MONO_TYPE_ARRAY:
1568 case MONO_TYPE_SZARRAY:
1569 case MONO_TYPE_STRING:
1570 /* Share non-float stack slots of the same size */
1571 slot_info = &scalar_stack_slots [MONO_TYPE_CLASS];
1572 if (cfg->disable_reuse_ref_stack_slots)
1576 case MONO_TYPE_MVAR:
1577 slot_info = &scalar_stack_slots [t->type];
1580 slot_info = &scalar_stack_slots [t->type];
1585 if (cfg->comp_done & MONO_COMP_LIVENESS) {
1586 //printf ("START %2d %08x %08x\n", vmv->idx, vmv->range.first_use.abs_pos, vmv->range.last_use.abs_pos);
1588 /* expire old intervals in active */
1589 while (slot_info->active) {
1590 MonoMethodVar *amv = (MonoMethodVar *)slot_info->active->data;
1592 if (amv->range.last_use.abs_pos > vmv->range.first_use.abs_pos)
1595 //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);
1597 slot_info->active = g_list_delete_link (slot_info->active, slot_info->active);
1598 slot_info->slots = g_slist_prepend_mempool (cfg->mempool, slot_info->slots, GINT_TO_POINTER (offsets [amv->idx]));
1602 * This also handles the case when the variable is used in an
1603 * exception region, as liveness info is not computed there.
1606 * FIXME: All valuetypes are marked as INDIRECT because of LDADDR
1609 if (! (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
1610 if (slot_info->slots) {
1611 slot = GPOINTER_TO_INT (slot_info->slots->data);
1613 slot_info->slots = slot_info->slots->next;
1616 slot_info->active = mono_varlist_insert_sorted (cfg, slot_info->active, vmv, TRUE);
1621 static int count = 0;
1625 if (count == atoi (g_getenv ("COUNT")))
1626 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
1627 if (count > atoi (g_getenv ("COUNT")))
1630 mono_print_ins (inst);
1635 if (inst->flags & MONO_INST_LMF) {
1637 * This variable represents a MonoLMF structure, which has no corresponding
1638 * CLR type, so hard-code its size/alignment.
1640 size = sizeof (MonoLMF);
1641 align = sizeof (mgreg_t);
1648 if (slot == 0xffffff) {
1650 * Allways allocate valuetypes to sizeof (gpointer) to allow more
1651 * efficient copying (and to work around the fact that OP_MEMCPY
1652 * and OP_MEMSET ignores alignment).
1654 if (MONO_TYPE_ISSTRUCT (t)) {
1655 align = MAX (align, sizeof (gpointer));
1656 align = MAX (align, mono_class_min_align (mono_class_from_mono_type (t)));
1658 * Align the size too so the code generated for passing vtypes in
1659 * registers doesn't overwrite random locals.
1661 size = (size + (align - 1)) & ~(align -1);
1666 offset += align - 1;
1667 offset &= ~(align - 1);
1671 offset += align - 1;
1672 offset &= ~(align - 1);
1677 *stack_align = MAX (*stack_align, align);
1680 offsets [vmv->idx] = slot;
1683 for (i = 0; i < MONO_TYPE_PINNED; ++i) {
1684 if (scalar_stack_slots [i].active)
1685 g_list_free (scalar_stack_slots [i].active);
1687 for (i = 0; i < nvtypes; ++i) {
1688 if (vtype_stack_slots [i].active)
1689 g_list_free (vtype_stack_slots [i].active);
1692 cfg->stat_locals_stack_size += offset;
1694 *stack_size = offset;
1698 #define EMUL_HIT_SHIFT 3
1699 #define EMUL_HIT_MASK ((1 << EMUL_HIT_SHIFT) - 1)
1700 /* small hit bitmap cache */
1701 static mono_byte emul_opcode_hit_cache [(OP_LAST>>EMUL_HIT_SHIFT) + 1] = {0};
1702 static short emul_opcode_num = 0;
1703 static short emul_opcode_alloced = 0;
1704 static short *emul_opcode_opcodes;
1705 static MonoJitICallInfo **emul_opcode_map;
1708 mono_find_jit_opcode_emulation (int opcode)
1710 g_assert (opcode >= 0 && opcode <= OP_LAST);
1711 if (emul_opcode_hit_cache [opcode >> (EMUL_HIT_SHIFT + 3)] & (1 << (opcode & EMUL_HIT_MASK))) {
1713 for (i = 0; i < emul_opcode_num; ++i) {
1714 if (emul_opcode_opcodes [i] == opcode)
1715 return emul_opcode_map [i];
1722 mini_register_opcode_emulation (int opcode, const char *name, const char *sigstr, gpointer func, const char *symbol, gboolean no_throw)
1724 MonoJitICallInfo *info;
1725 MonoMethodSignature *sig = mono_create_icall_signature (sigstr);
1727 g_assert (!sig->hasthis);
1728 g_assert (sig->param_count < 3);
1730 /* Opcode emulation functions are assumed to don't call mono_raise_exception () */
1731 info = mono_register_jit_icall_full (func, name, sig, no_throw, TRUE, symbol);
1733 if (emul_opcode_num >= emul_opcode_alloced) {
1734 int incr = emul_opcode_alloced? emul_opcode_alloced/2: 16;
1735 emul_opcode_alloced += incr;
1736 emul_opcode_map = (MonoJitICallInfo **)g_realloc (emul_opcode_map, sizeof (emul_opcode_map [0]) * emul_opcode_alloced);
1737 emul_opcode_opcodes = (short *)g_realloc (emul_opcode_opcodes, sizeof (emul_opcode_opcodes [0]) * emul_opcode_alloced);
1739 emul_opcode_map [emul_opcode_num] = info;
1740 emul_opcode_opcodes [emul_opcode_num] = opcode;
1742 emul_opcode_hit_cache [opcode >> (EMUL_HIT_SHIFT + 3)] |= (1 << (opcode & EMUL_HIT_MASK));
1746 print_dfn (MonoCompile *cfg)
1754 char *method_name = mono_method_full_name (cfg->method, TRUE);
1755 g_print ("IR code for method %s\n", method_name);
1756 g_free (method_name);
1759 for (i = 0; i < cfg->num_bblocks; ++i) {
1760 bb = cfg->bblocks [i];
1761 /*if (bb->cil_code) {
1762 char* code1, *code2;
1763 code1 = mono_disasm_code_one (NULL, cfg->method, bb->cil_code, NULL);
1764 if (bb->last_ins->cil_code)
1765 code2 = mono_disasm_code_one (NULL, cfg->method, bb->last_ins->cil_code, NULL);
1767 code2 = g_strdup ("");
1769 code1 [strlen (code1) - 1] = 0;
1770 code = g_strdup_printf ("%s -> %s", code1, code2);
1774 code = g_strdup ("\n");
1775 g_print ("\nBB%d (%d) (len: %d): %s", bb->block_num, i, bb->cil_length, code);
1776 MONO_BB_FOR_EACH_INS (bb, c) {
1777 mono_print_ins_index (-1, c);
1780 g_print ("\tprev:");
1781 for (j = 0; j < bb->in_count; ++j) {
1782 g_print (" BB%d", bb->in_bb [j]->block_num);
1784 g_print ("\t\tsucc:");
1785 for (j = 0; j < bb->out_count; ++j) {
1786 g_print (" BB%d", bb->out_bb [j]->block_num);
1788 g_print ("\n\tidom: BB%d\n", bb->idom? bb->idom->block_num: -1);
1791 g_assert (mono_bitset_test_fast (bb->dominators, bb->idom->dfn));
1794 mono_blockset_print (cfg, bb->dominators, "\tdominators", bb->idom? bb->idom->dfn: -1);
1796 mono_blockset_print (cfg, bb->dfrontier, "\tdfrontier", -1);
1804 mono_bblock_add_inst (MonoBasicBlock *bb, MonoInst *inst)
1806 MONO_ADD_INS (bb, inst);
1810 mono_bblock_insert_after_ins (MonoBasicBlock *bb, MonoInst *ins, MonoInst *ins_to_insert)
1814 bb->code = ins_to_insert;
1816 /* Link with next */
1817 ins_to_insert->next = ins;
1819 ins->prev = ins_to_insert;
1821 if (bb->last_ins == NULL)
1822 bb->last_ins = ins_to_insert;
1824 /* Link with next */
1825 ins_to_insert->next = ins->next;
1827 ins->next->prev = ins_to_insert;
1829 /* Link with previous */
1830 ins->next = ins_to_insert;
1831 ins_to_insert->prev = ins;
1833 if (bb->last_ins == ins)
1834 bb->last_ins = ins_to_insert;
1839 mono_bblock_insert_before_ins (MonoBasicBlock *bb, MonoInst *ins, MonoInst *ins_to_insert)
1844 ins->prev = ins_to_insert;
1845 bb->code = ins_to_insert;
1846 ins_to_insert->next = ins;
1847 if (bb->last_ins == NULL)
1848 bb->last_ins = ins_to_insert;
1850 /* Link with previous */
1852 ins->prev->next = ins_to_insert;
1853 ins_to_insert->prev = ins->prev;
1855 /* Link with next */
1856 ins->prev = ins_to_insert;
1857 ins_to_insert->next = ins;
1859 if (bb->code == ins)
1860 bb->code = ins_to_insert;
1865 * mono_verify_bblock:
1867 * Verify that the next and prev pointers are consistent inside the instructions in BB.
1870 mono_verify_bblock (MonoBasicBlock *bb)
1872 MonoInst *ins, *prev;
1875 for (ins = bb->code; ins; ins = ins->next) {
1876 g_assert (ins->prev == prev);
1880 g_assert (!bb->last_ins->next);
1886 * Perform consistency checks on the JIT data structures and the IR
1889 mono_verify_cfg (MonoCompile *cfg)
1893 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
1894 mono_verify_bblock (bb);
1897 // This will free many fields in cfg to save
1898 // memory. Note that this must be safe to call
1899 // multiple times. It must be idempotent.
1901 mono_empty_compile (MonoCompile *cfg)
1903 mono_free_loop_info (cfg);
1905 // These live in the mempool, and so must be freed
1907 for (GSList *l = cfg->headers_to_free; l; l = l->next) {
1908 mono_metadata_free_mh ((MonoMethodHeader *)l->data);
1910 cfg->headers_to_free = NULL;
1913 //mono_mempool_stats (cfg->mempool);
1914 mono_mempool_destroy (cfg->mempool);
1915 cfg->mempool = NULL;
1918 g_free (cfg->varinfo);
1919 cfg->varinfo = NULL;
1925 mono_regstate_free (cfg->rs);
1931 mono_destroy_compile (MonoCompile *cfg)
1933 mono_empty_compile (cfg);
1936 mono_metadata_free_mh (cfg->header);
1939 g_hash_table_destroy (cfg->spvars);
1941 g_hash_table_destroy (cfg->exvars);
1943 g_list_free (cfg->ldstr_list);
1945 if (cfg->token_info_hash)
1946 g_hash_table_destroy (cfg->token_info_hash);
1948 if (cfg->abs_patches)
1949 g_hash_table_destroy (cfg->abs_patches);
1951 mono_debug_free_method (cfg);
1953 g_free (cfg->varinfo);
1955 g_free (cfg->exception_message);
1960 mono_create_tls_get_offset (MonoCompile *cfg, int offset)
1964 if (!cfg->backend->have_tls_get)
1970 MONO_INST_NEW (cfg, ins, OP_TLS_GET);
1971 ins->dreg = mono_alloc_preg (cfg);
1972 ins->inst_offset = offset;
1977 mini_tls_get_supported (MonoCompile *cfg, MonoTlsKey key)
1979 if (!cfg->backend->have_tls_get)
1982 if (cfg->compile_aot)
1983 return cfg->backend->have_tls_get_reg;
1985 return mini_get_tls_offset (key) != -1;
1989 mono_create_tls_get (MonoCompile *cfg, MonoTlsKey key)
1991 if (!cfg->backend->have_tls_get)
1994 #ifdef HAVE_KW_THREAD
1996 * MONO_THREAD_VAR_OFFSET definitions don't work when loading mono as a
1997 * dynamic library. This means that we need to be conservative and don't
1998 * aot code that contains these tls chunks.
2000 * FIXME Remove HAVE_KW_THREAD altogether and use only pthread since it
2001 * simplifies the code alot.
2004 cfg->disable_aot = TRUE;
2007 * TLS offsets might be different at AOT time, so load them from a GOT slot and
2008 * use a different opcode.
2010 if (cfg->compile_aot) {
2011 if (cfg->backend->have_tls_get_reg) {
2014 EMIT_NEW_TLS_OFFSETCONST (cfg, c, key);
2015 MONO_INST_NEW (cfg, ins, OP_TLS_GET_REG);
2016 ins->dreg = mono_alloc_preg (cfg);
2017 ins->sreg1 = c->dreg;
2024 return mono_create_tls_get_offset (cfg, mini_get_tls_offset (key));
2028 mono_get_jit_tls_intrinsic (MonoCompile *cfg)
2030 return mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
2034 mono_get_domain_intrinsic (MonoCompile* cfg)
2036 return mono_create_tls_get (cfg, TLS_KEY_DOMAIN);
2040 mono_get_thread_intrinsic (MonoCompile* cfg)
2042 return mono_create_tls_get (cfg, TLS_KEY_THREAD);
2046 mono_get_lmf_intrinsic (MonoCompile* cfg)
2048 return mono_create_tls_get (cfg, TLS_KEY_LMF);
2052 mono_get_lmf_addr_intrinsic (MonoCompile* cfg)
2054 return mono_create_tls_get (cfg, TLS_KEY_LMF_ADDR);
2058 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
2060 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfo));
2064 ji->data.target = target;
2065 ji->next = cfg->patch_info;
2067 cfg->patch_info = ji;
2071 mono_add_patch_info_rel (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target, int relocation)
2073 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfo));
2077 ji->relocation = relocation;
2078 ji->data.target = target;
2079 ji->next = cfg->patch_info;
2081 cfg->patch_info = ji;
2085 mono_remove_patch_info (MonoCompile *cfg, int ip)
2087 MonoJumpInfo **ji = &cfg->patch_info;
2090 if ((*ji)->ip.i == ip)
2093 ji = &((*ji)->next);
2098 mono_add_seq_point (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins, int native_offset)
2100 ins->inst_offset = native_offset;
2101 g_ptr_array_add (cfg->seq_points, ins);
2103 bb->seq_points = g_slist_prepend_mempool (cfg->mempool, bb->seq_points, ins);
2104 bb->last_seq_point = ins;
2109 mono_add_var_location (MonoCompile *cfg, MonoInst *var, gboolean is_reg, int reg, int offset, int from, int to)
2111 MonoDwarfLocListEntry *entry = (MonoDwarfLocListEntry *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoDwarfLocListEntry));
2114 g_assert (offset == 0);
2116 entry->is_reg = is_reg;
2118 entry->offset = offset;
2122 if (var == cfg->args [0])
2123 cfg->this_loclist = g_slist_append_mempool (cfg->mempool, cfg->this_loclist, entry);
2124 else if (var == cfg->rgctx_var)
2125 cfg->rgctx_loclist = g_slist_append_mempool (cfg->mempool, cfg->rgctx_loclist, entry);
2129 mono_compile_create_vars (MonoCompile *cfg)
2131 MonoMethodSignature *sig;
2132 MonoMethodHeader *header;
2135 header = cfg->header;
2137 sig = mono_method_signature (cfg->method);
2139 if (!MONO_TYPE_IS_VOID (sig->ret)) {
2140 cfg->ret = mono_compile_create_var (cfg, sig->ret, OP_ARG);
2141 /* Inhibit optimizations */
2142 cfg->ret->flags |= MONO_INST_VOLATILE;
2144 if (cfg->verbose_level > 2)
2145 g_print ("creating vars\n");
2147 cfg->args = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, (sig->param_count + sig->hasthis) * sizeof (MonoInst*));
2150 cfg->args [0] = mono_compile_create_var (cfg, &cfg->method->klass->this_arg, OP_ARG);
2151 cfg->this_arg = cfg->args [0];
2154 for (i = 0; i < sig->param_count; ++i) {
2155 cfg->args [i + sig->hasthis] = mono_compile_create_var (cfg, sig->params [i], OP_ARG);
2158 if (cfg->verbose_level > 2) {
2160 printf ("\treturn : ");
2161 mono_print_ins (cfg->ret);
2165 printf ("\tthis: ");
2166 mono_print_ins (cfg->args [0]);
2169 for (i = 0; i < sig->param_count; ++i) {
2170 printf ("\targ [%d]: ", i);
2171 mono_print_ins (cfg->args [i + sig->hasthis]);
2175 cfg->locals_start = cfg->num_varinfo;
2176 cfg->locals = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, header->num_locals * sizeof (MonoInst*));
2178 if (cfg->verbose_level > 2)
2179 g_print ("creating locals\n");
2181 for (i = 0; i < header->num_locals; ++i)
2182 cfg->locals [i] = mono_compile_create_var (cfg, header->locals [i], OP_LOCAL);
2184 if (cfg->verbose_level > 2)
2185 g_print ("locals done\n");
2188 if (COMPILE_LLVM (cfg))
2189 mono_llvm_create_vars (cfg);
2191 mono_arch_create_vars (cfg);
2193 mono_arch_create_vars (cfg);
2196 if (cfg->method->save_lmf && cfg->create_lmf_var) {
2197 MonoInst *lmf_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
2198 lmf_var->flags |= MONO_INST_VOLATILE;
2199 lmf_var->flags |= MONO_INST_LMF;
2200 cfg->lmf_var = lmf_var;
2205 mono_print_code (MonoCompile *cfg, const char* msg)
2209 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
2210 mono_print_bb (bb, msg);
2214 mono_postprocess_patches (MonoCompile *cfg)
2216 MonoJumpInfo *patch_info;
2219 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2220 switch (patch_info->type) {
2221 case MONO_PATCH_INFO_ABS: {
2222 MonoJitICallInfo *info = mono_find_jit_icall_by_addr (patch_info->data.target);
2225 * Change patches of type MONO_PATCH_INFO_ABS into patches describing the
2229 //printf ("TEST %s %p\n", info->name, patch_info->data.target);
2230 /* for these array methods we currently register the same function pointer
2231 * since it's a vararg function. But this means that mono_find_jit_icall_by_addr ()
2232 * will return the incorrect one depending on the order they are registered.
2233 * See tests/test-arr.cs
2235 if (strstr (info->name, "ves_array_new_va_") == NULL && strstr (info->name, "ves_array_element_address_") == NULL) {
2236 patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
2237 patch_info->data.name = info->name;
2241 if (patch_info->type == MONO_PATCH_INFO_ABS) {
2242 if (cfg->abs_patches) {
2243 MonoJumpInfo *abs_ji = (MonoJumpInfo *)g_hash_table_lookup (cfg->abs_patches, patch_info->data.target);
2245 patch_info->type = abs_ji->type;
2246 patch_info->data.target = abs_ji->data.target;
2253 case MONO_PATCH_INFO_SWITCH: {
2255 #if defined(__native_client__) && defined(__native_client_codegen__)
2256 /* This memory will leak. */
2257 /* TODO: can we free this when */
2258 /* making the final jump table? */
2259 table = g_malloc0 (sizeof(gpointer) * patch_info->data.table->table_size);
2261 if (cfg->method->dynamic) {
2262 table = (void **)mono_code_manager_reserve (cfg->dynamic_info->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
2264 table = (void **)mono_domain_code_reserve (cfg->domain, sizeof (gpointer) * patch_info->data.table->table_size);
2268 for (i = 0; i < patch_info->data.table->table_size; i++) {
2269 /* Might be NULL if the switch is eliminated */
2270 if (patch_info->data.table->table [i]) {
2271 g_assert (patch_info->data.table->table [i]->native_offset);
2272 table [i] = GINT_TO_POINTER (patch_info->data.table->table [i]->native_offset);
2277 patch_info->data.table->table = (MonoBasicBlock**)table;
2280 case MONO_PATCH_INFO_METHOD_JUMP: {
2281 MonoJumpList *jlist;
2282 MonoDomain *domain = cfg->domain;
2283 unsigned char *ip = cfg->native_code + patch_info->ip.i;
2285 mono_domain_lock (domain);
2286 jlist = (MonoJumpList *)g_hash_table_lookup (domain_jit_info (domain)->jump_target_hash, patch_info->data.method);
2288 jlist = (MonoJumpList *)mono_domain_alloc0 (domain, sizeof (MonoJumpList));
2289 g_hash_table_insert (domain_jit_info (domain)->jump_target_hash, patch_info->data.method, jlist);
2291 jlist->list = g_slist_prepend (jlist->list, ip);
2292 mono_domain_unlock (domain);
2303 mono_codegen (MonoCompile *cfg)
2306 int max_epilog_size;
2308 MonoDomain *code_domain;
2309 guint unwindlen = 0;
2311 if (mono_using_xdebug)
2313 * Recent gdb versions have trouble processing symbol files containing
2314 * overlapping address ranges, so allocate all code from the code manager
2315 * of the root domain. (#666152).
2317 code_domain = mono_get_root_domain ();
2319 code_domain = cfg->domain;
2321 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2322 cfg->spill_count = 0;
2323 /* we reuse dfn here */
2324 /* bb->dfn = bb_count++; */
2326 mono_arch_lowering_pass (cfg, bb);
2328 if (cfg->opt & MONO_OPT_PEEPHOLE)
2329 mono_arch_peephole_pass_1 (cfg, bb);
2331 mono_local_regalloc (cfg, bb);
2333 if (cfg->opt & MONO_OPT_PEEPHOLE)
2334 mono_arch_peephole_pass_2 (cfg, bb);
2336 if (cfg->gen_seq_points && !cfg->gen_sdb_seq_points)
2337 mono_bb_deduplicate_op_il_seq_points (cfg, bb);
2340 if (cfg->prof_options & MONO_PROFILE_COVERAGE)
2341 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, cfg->num_bblocks);
2343 code = mono_arch_emit_prolog (cfg);
2345 cfg->code_len = code - cfg->native_code;
2346 cfg->prolog_end = cfg->code_len;
2347 cfg->cfa_reg = cfg->cur_cfa_reg;
2348 cfg->cfa_offset = cfg->cur_cfa_offset;
2350 mono_debug_open_method (cfg);
2352 /* emit code all basic blocks */
2353 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2354 bb->native_offset = cfg->code_len;
2355 bb->real_native_offset = cfg->code_len;
2356 //if ((bb == cfg->bb_entry) || !(bb->region == -1 && !bb->dfn))
2357 mono_arch_output_basic_block (cfg, bb);
2358 bb->native_length = cfg->code_len - bb->native_offset;
2360 if (bb == cfg->bb_exit) {
2361 cfg->epilog_begin = cfg->code_len;
2362 mono_arch_emit_epilog (cfg);
2363 cfg->epilog_end = cfg->code_len;
2367 mono_arch_emit_exceptions (cfg);
2369 max_epilog_size = 0;
2371 /* we always allocate code in cfg->domain->code_mp to increase locality */
2372 cfg->code_size = cfg->code_len + max_epilog_size;
2374 /* fixme: align to MONO_ARCH_CODE_ALIGNMENT */
2376 #ifdef MONO_ARCH_HAVE_UNWIND_TABLE
2377 unwindlen = mono_arch_unwindinfo_get_size (cfg->arch.unwindinfo);
2380 if (cfg->method->dynamic) {
2381 /* Allocate the code into a separate memory pool so it can be freed */
2382 cfg->dynamic_info = g_new0 (MonoJitDynamicMethodInfo, 1);
2383 cfg->dynamic_info->code_mp = mono_code_manager_new_dynamic ();
2384 mono_domain_lock (cfg->domain);
2385 mono_dynamic_code_hash_insert (cfg->domain, cfg->method, cfg->dynamic_info);
2386 mono_domain_unlock (cfg->domain);
2388 if (mono_using_xdebug)
2389 /* See the comment for cfg->code_domain */
2390 code = (guint8 *)mono_domain_code_reserve (code_domain, cfg->code_size + cfg->thunk_area + unwindlen);
2392 code = (guint8 *)mono_code_manager_reserve (cfg->dynamic_info->code_mp, cfg->code_size + cfg->thunk_area + unwindlen);
2394 code = (guint8 *)mono_domain_code_reserve (code_domain, cfg->code_size + cfg->thunk_area + unwindlen);
2397 if (cfg->thunk_area) {
2398 cfg->thunks_offset = cfg->code_size + unwindlen;
2399 cfg->thunks = code + cfg->thunks_offset;
2400 memset (cfg->thunks, 0, cfg->thunk_area);
2404 memcpy (code, cfg->native_code, cfg->code_len);
2405 g_free (cfg->native_code);
2406 cfg->native_code = code;
2407 code = cfg->native_code + cfg->code_len;
2409 /* g_assert (((int)cfg->native_code & (MONO_ARCH_CODE_ALIGNMENT - 1)) == 0); */
2410 mono_postprocess_patches (cfg);
2412 #ifdef VALGRIND_JIT_REGISTER_MAP
2413 if (valgrind_register){
2414 char* nm = mono_method_full_name (cfg->method, TRUE);
2415 VALGRIND_JIT_REGISTER_MAP (nm, cfg->native_code, cfg->native_code + cfg->code_len);
2420 if (cfg->verbose_level > 0) {
2421 char* nm = mono_method_get_full_name (cfg->method);
2422 g_print ("Method %s emitted at %p to %p (code length %d) [%s]\n",
2424 cfg->native_code, cfg->native_code + cfg->code_len, cfg->code_len, cfg->domain->friendly_name);
2429 gboolean is_generic = FALSE;
2431 if (cfg->method->is_inflated || mono_method_get_generic_container (cfg->method) ||
2432 mono_class_is_gtd (cfg->method->klass) || mono_class_is_ginst (cfg->method->klass)) {
2437 g_assert (is_generic);
2440 #ifdef MONO_ARCH_HAVE_SAVE_UNWIND_INFO
2441 mono_arch_save_unwind_info (cfg);
2444 #ifdef MONO_ARCH_HAVE_PATCH_CODE_NEW
2449 for (ji = cfg->patch_info; ji; ji = ji->next) {
2450 if (cfg->compile_aot) {
2452 case MONO_PATCH_INFO_BB:
2453 case MONO_PATCH_INFO_LABEL:
2456 /* No need to patch these */
2461 if (ji->type == MONO_PATCH_INFO_NONE)
2464 target = mono_resolve_patch_target (cfg->method, cfg->domain, cfg->native_code, ji, cfg->run_cctors, &cfg->error);
2465 if (!mono_error_ok (&cfg->error)) {
2466 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
2469 mono_arch_patch_code_new (cfg, cfg->domain, cfg->native_code, ji, target);
2473 mono_arch_patch_code (cfg, cfg->method, cfg->domain, cfg->native_code, cfg->patch_info, cfg->run_cctors, &cfg->error);
2474 if (!is_ok (&cfg->error)) {
2475 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
2480 if (cfg->method->dynamic) {
2481 if (mono_using_xdebug)
2482 mono_domain_code_commit (code_domain, cfg->native_code, cfg->code_size, cfg->code_len);
2484 mono_code_manager_commit (cfg->dynamic_info->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
2486 mono_domain_code_commit (code_domain, cfg->native_code, cfg->code_size, cfg->code_len);
2488 #if defined(__native_client_codegen__) && defined(__native_client__)
2489 cfg->native_code = code_dest;
2491 mono_profiler_code_buffer_new (cfg->native_code, cfg->code_len, MONO_PROFILER_CODE_BUFFER_METHOD, cfg->method);
2493 mono_arch_flush_icache (cfg->native_code, cfg->code_len);
2495 mono_debug_close_method (cfg);
2497 #ifdef MONO_ARCH_HAVE_UNWIND_TABLE
2498 mono_arch_unwindinfo_install_unwind_info (&cfg->arch.unwindinfo, cfg->native_code, cfg->code_len);
2503 compute_reachable (MonoBasicBlock *bb)
2507 if (!(bb->flags & BB_VISITED)) {
2508 bb->flags |= BB_VISITED;
2509 for (i = 0; i < bb->out_count; ++i)
2510 compute_reachable (bb->out_bb [i]);
2514 static void mono_bb_ordering (MonoCompile *cfg)
2517 /* Depth-first ordering on basic blocks */
2518 cfg->bblocks = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
2520 cfg->max_block_num = cfg->num_bblocks;
2522 df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
2523 if (cfg->num_bblocks != dfn + 1) {
2526 cfg->num_bblocks = dfn + 1;
2528 /* remove unreachable code, because the code in them may be
2529 * inconsistent (access to dead variables for example) */
2530 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
2531 bb->flags &= ~BB_VISITED;
2532 compute_reachable (cfg->bb_entry);
2533 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
2534 if (bb->flags & BB_EXCEPTION_HANDLER)
2535 compute_reachable (bb);
2536 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2537 if (!(bb->flags & BB_VISITED)) {
2538 if (cfg->verbose_level > 1)
2539 g_print ("found unreachable code in BB%d\n", bb->block_num);
2540 bb->code = bb->last_ins = NULL;
2541 while (bb->out_count)
2542 mono_unlink_bblock (cfg, bb, bb->out_bb [0]);
2545 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
2546 bb->flags &= ~BB_VISITED;
2551 mono_handle_out_of_line_bblock (MonoCompile *cfg)
2554 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2555 if (bb->next_bb && bb->next_bb->out_of_line && bb->last_ins && !MONO_IS_BRANCH_OP (bb->last_ins)) {
2557 MONO_INST_NEW (cfg, ins, OP_BR);
2558 MONO_ADD_INS (bb, ins);
2559 ins->inst_target_bb = bb->next_bb;
2565 create_jit_info (MonoCompile *cfg, MonoMethod *method_to_compile)
2568 MonoMethodHeader *header;
2570 MonoJitInfoFlags flags = JIT_INFO_NONE;
2571 int num_clauses, num_holes = 0;
2572 guint32 stack_size = 0;
2574 g_assert (method_to_compile == cfg->method);
2575 header = cfg->header;
2578 flags = (MonoJitInfoFlags)(flags | JIT_INFO_HAS_GENERIC_JIT_INFO);
2580 if (cfg->arch_eh_jit_info) {
2581 MonoJitArgumentInfo *arg_info;
2582 MonoMethodSignature *sig = mono_method_signature (cfg->method_to_register);
2585 * This cannot be computed during stack walking, as
2586 * mono_arch_get_argument_info () is not signal safe.
2588 arg_info = g_newa (MonoJitArgumentInfo, sig->param_count + 1);
2589 stack_size = mono_arch_get_argument_info (sig, sig->param_count, arg_info);
2592 flags = (MonoJitInfoFlags)(flags | JIT_INFO_HAS_ARCH_EH_INFO);
2595 if (cfg->has_unwind_info_for_epilog && !(flags & JIT_INFO_HAS_ARCH_EH_INFO))
2596 flags = (MonoJitInfoFlags)(flags | JIT_INFO_HAS_ARCH_EH_INFO);
2598 if (cfg->thunk_area)
2599 flags = (MonoJitInfoFlags)(flags | JIT_INFO_HAS_THUNK_INFO);
2601 if (cfg->try_block_holes) {
2602 for (tmp = cfg->try_block_holes; tmp; tmp = tmp->next) {
2603 TryBlockHole *hole = (TryBlockHole *)tmp->data;
2604 MonoExceptionClause *ec = hole->clause;
2605 int hole_end = hole->basic_block->native_offset + hole->basic_block->native_length;
2606 MonoBasicBlock *clause_last_bb = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
2607 g_assert (clause_last_bb);
2609 /* Holes at the end of a try region can be represented by simply reducing the size of the block itself.*/
2610 if (clause_last_bb->native_offset != hole_end)
2614 flags = (MonoJitInfoFlags)(flags | JIT_INFO_HAS_TRY_BLOCK_HOLES);
2615 if (G_UNLIKELY (cfg->verbose_level >= 4))
2616 printf ("Number of try block holes %d\n", num_holes);
2619 if (COMPILE_LLVM (cfg))
2620 num_clauses = cfg->llvm_ex_info_len;
2622 num_clauses = header->num_clauses;
2624 if (cfg->method->dynamic)
2625 jinfo = (MonoJitInfo *)g_malloc0 (mono_jit_info_size (flags, num_clauses, num_holes));
2627 jinfo = (MonoJitInfo *)mono_domain_alloc0 (cfg->domain, mono_jit_info_size (flags, num_clauses, num_holes));
2628 mono_jit_info_init (jinfo, cfg->method_to_register, cfg->native_code, cfg->code_len, flags, num_clauses, num_holes);
2629 jinfo->domain_neutral = (cfg->opt & MONO_OPT_SHARED) != 0;
2631 if (COMPILE_LLVM (cfg))
2632 jinfo->from_llvm = TRUE;
2636 MonoGenericJitInfo *gi;
2637 GSList *loclist = NULL;
2639 gi = mono_jit_info_get_generic_jit_info (jinfo);
2642 if (cfg->method->dynamic)
2643 gi->generic_sharing_context = g_new0 (MonoGenericSharingContext, 1);
2645 gi->generic_sharing_context = (MonoGenericSharingContext *)mono_domain_alloc0 (cfg->domain, sizeof (MonoGenericSharingContext));
2646 mini_init_gsctx (cfg->method->dynamic ? NULL : cfg->domain, NULL, cfg->gsctx_context, gi->generic_sharing_context);
2648 if ((method_to_compile->flags & METHOD_ATTRIBUTE_STATIC) ||
2649 mini_method_get_context (method_to_compile)->method_inst ||
2650 method_to_compile->klass->valuetype) {
2651 g_assert (cfg->rgctx_var);
2656 if ((method_to_compile->flags & METHOD_ATTRIBUTE_STATIC) ||
2657 mini_method_get_context (method_to_compile)->method_inst ||
2658 method_to_compile->klass->valuetype) {
2659 inst = cfg->rgctx_var;
2660 if (!COMPILE_LLVM (cfg))
2661 g_assert (inst->opcode == OP_REGOFFSET);
2662 loclist = cfg->rgctx_loclist;
2664 inst = cfg->args [0];
2665 loclist = cfg->this_loclist;
2669 /* Needed to handle async exceptions */
2673 gi->nlocs = g_slist_length (loclist);
2674 if (cfg->method->dynamic)
2675 gi->locations = (MonoDwarfLocListEntry *)g_malloc0 (gi->nlocs * sizeof (MonoDwarfLocListEntry));
2677 gi->locations = (MonoDwarfLocListEntry *)mono_domain_alloc0 (cfg->domain, gi->nlocs * sizeof (MonoDwarfLocListEntry));
2679 for (l = loclist; l; l = l->next) {
2680 memcpy (&(gi->locations [i]), l->data, sizeof (MonoDwarfLocListEntry));
2685 if (COMPILE_LLVM (cfg)) {
2686 g_assert (cfg->llvm_this_reg != -1);
2687 gi->this_in_reg = 0;
2688 gi->this_reg = cfg->llvm_this_reg;
2689 gi->this_offset = cfg->llvm_this_offset;
2690 } else if (inst->opcode == OP_REGVAR) {
2691 gi->this_in_reg = 1;
2692 gi->this_reg = inst->dreg;
2694 g_assert (inst->opcode == OP_REGOFFSET);
2696 g_assert (inst->inst_basereg == X86_EBP);
2697 #elif defined(TARGET_AMD64)
2698 g_assert (inst->inst_basereg == X86_EBP || inst->inst_basereg == X86_ESP);
2700 g_assert (inst->inst_offset >= G_MININT32 && inst->inst_offset <= G_MAXINT32);
2702 gi->this_in_reg = 0;
2703 gi->this_reg = inst->inst_basereg;
2704 gi->this_offset = inst->inst_offset;
2709 MonoTryBlockHoleTableJitInfo *table;
2712 table = mono_jit_info_get_try_block_hole_table_info (jinfo);
2713 table->num_holes = (guint16)num_holes;
2715 for (tmp = cfg->try_block_holes; tmp; tmp = tmp->next) {
2716 guint32 start_bb_offset;
2717 MonoTryBlockHoleJitInfo *hole;
2718 TryBlockHole *hole_data = (TryBlockHole *)tmp->data;
2719 MonoExceptionClause *ec = hole_data->clause;
2720 int hole_end = hole_data->basic_block->native_offset + hole_data->basic_block->native_length;
2721 MonoBasicBlock *clause_last_bb = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
2722 g_assert (clause_last_bb);
2724 /* Holes at the end of a try region can be represented by simply reducing the size of the block itself.*/
2725 if (clause_last_bb->native_offset == hole_end)
2728 start_bb_offset = hole_data->start_offset - hole_data->basic_block->native_offset;
2729 hole = &table->holes [i++];
2730 hole->clause = hole_data->clause - &header->clauses [0];
2731 hole->offset = (guint32)hole_data->start_offset;
2732 hole->length = (guint16)(hole_data->basic_block->native_length - start_bb_offset);
2734 if (G_UNLIKELY (cfg->verbose_level >= 4))
2735 printf ("\tTry block hole at eh clause %d offset %x length %x\n", hole->clause, hole->offset, hole->length);
2737 g_assert (i == num_holes);
2740 if (jinfo->has_arch_eh_info) {
2741 MonoArchEHJitInfo *info;
2743 info = mono_jit_info_get_arch_eh_info (jinfo);
2745 info->stack_size = stack_size;
2748 if (cfg->thunk_area) {
2749 MonoThunkJitInfo *info;
2751 info = mono_jit_info_get_thunk_info (jinfo);
2752 info->thunks_offset = cfg->thunks_offset;
2753 info->thunks_size = cfg->thunk_area;
2756 if (COMPILE_LLVM (cfg)) {
2758 memcpy (&jinfo->clauses [0], &cfg->llvm_ex_info [0], num_clauses * sizeof (MonoJitExceptionInfo));
2759 } else if (header->num_clauses) {
2762 for (i = 0; i < header->num_clauses; i++) {
2763 MonoExceptionClause *ec = &header->clauses [i];
2764 MonoJitExceptionInfo *ei = &jinfo->clauses [i];
2765 MonoBasicBlock *tblock;
2766 MonoInst *exvar, *spvar;
2768 ei->flags = ec->flags;
2770 if (G_UNLIKELY (cfg->verbose_level >= 4))
2771 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);
2774 * The spvars are needed by mono_arch_install_handler_block_guard ().
2776 if (ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY) {
2779 region = ((i + 1) << 8) | MONO_REGION_FINALLY | ec->flags;
2780 spvar = mono_find_spvar_for_region (cfg, region);
2782 ei->exvar_offset = spvar->inst_offset;
2784 exvar = mono_find_exvar_for_offset (cfg, ec->handler_offset);
2785 ei->exvar_offset = exvar ? exvar->inst_offset : 0;
2788 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
2789 tblock = cfg->cil_offset_to_bb [ec->data.filter_offset];
2791 ei->data.filter = cfg->native_code + tblock->native_offset;
2793 ei->data.catch_class = ec->data.catch_class;
2796 tblock = cfg->cil_offset_to_bb [ec->try_offset];
2798 g_assert (tblock->native_offset);
2799 ei->try_start = cfg->native_code + tblock->native_offset;
2800 if (tblock->extend_try_block) {
2802 * Extend the try block backwards to include parts of the previous call
2805 ei->try_start = (guint8*)ei->try_start - cfg->backend->monitor_enter_adjustment;
2807 if (ec->try_offset + ec->try_len < header->code_size)
2808 tblock = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
2810 tblock = cfg->bb_exit;
2811 if (G_UNLIKELY (cfg->verbose_level >= 4))
2812 printf ("looking for end of try [%d, %d] -> %p (code size %d)\n", ec->try_offset, ec->try_len, tblock, header->code_size);
2814 if (!tblock->native_offset) {
2816 for (j = ec->try_offset + ec->try_len, end = ec->try_offset; j >= end; --j) {
2817 MonoBasicBlock *bb = cfg->cil_offset_to_bb [j];
2818 if (bb && bb->native_offset) {
2824 ei->try_end = cfg->native_code + tblock->native_offset;
2825 g_assert (tblock->native_offset);
2826 tblock = cfg->cil_offset_to_bb [ec->handler_offset];
2828 ei->handler_start = cfg->native_code + tblock->native_offset;
2830 for (tmp = cfg->try_block_holes; tmp; tmp = tmp->next) {
2831 TryBlockHole *hole = (TryBlockHole *)tmp->data;
2832 gpointer hole_end = cfg->native_code + (hole->basic_block->native_offset + hole->basic_block->native_length);
2833 if (hole->clause == ec && hole_end == ei->try_end) {
2834 if (G_UNLIKELY (cfg->verbose_level >= 4))
2835 printf ("\tShortening try block %d from %x to %x\n", i, (int)((guint8*)ei->try_end - cfg->native_code), hole->start_offset);
2837 ei->try_end = cfg->native_code + hole->start_offset;
2842 if (ec->flags == MONO_EXCEPTION_CLAUSE_FINALLY) {
2844 if (ec->handler_offset + ec->handler_len < header->code_size) {
2845 tblock = cfg->cil_offset_to_bb [ec->handler_offset + ec->handler_len];
2846 if (tblock->native_offset) {
2847 end_offset = tblock->native_offset;
2851 for (j = ec->handler_offset + ec->handler_len, end = ec->handler_offset; j >= end; --j) {
2852 MonoBasicBlock *bb = cfg->cil_offset_to_bb [j];
2853 if (bb && bb->native_offset) {
2858 end_offset = tblock->native_offset + tblock->native_length;
2861 end_offset = cfg->epilog_begin;
2863 ei->data.handler_end = cfg->native_code + end_offset;
2868 if (G_UNLIKELY (cfg->verbose_level >= 4)) {
2870 for (i = 0; i < jinfo->num_clauses; i++) {
2871 MonoJitExceptionInfo *ei = &jinfo->clauses [i];
2872 int start = (guint8*)ei->try_start - cfg->native_code;
2873 int end = (guint8*)ei->try_end - cfg->native_code;
2874 int handler = (guint8*)ei->handler_start - cfg->native_code;
2875 int handler_end = (guint8*)ei->data.handler_end - cfg->native_code;
2877 printf ("JitInfo EH clause %d flags %x try %x-%x handler %x-%x\n", i, ei->flags, start, end, handler, handler_end);
2881 if (cfg->encoded_unwind_ops) {
2882 /* Generated by LLVM */
2883 jinfo->unwind_info = mono_cache_unwind_info (cfg->encoded_unwind_ops, cfg->encoded_unwind_ops_len);
2884 g_free (cfg->encoded_unwind_ops);
2885 } else if (cfg->unwind_ops) {
2887 guint8 *unwind_info = mono_unwind_ops_encode (cfg->unwind_ops, &info_len);
2888 guint32 unwind_desc;
2890 unwind_desc = mono_cache_unwind_info (unwind_info, info_len);
2892 if (cfg->has_unwind_info_for_epilog) {
2893 MonoArchEHJitInfo *info;
2895 info = mono_jit_info_get_arch_eh_info (jinfo);
2897 info->epilog_size = cfg->code_len - cfg->epilog_begin;
2899 jinfo->unwind_info = unwind_desc;
2900 g_free (unwind_info);
2902 jinfo->unwind_info = cfg->used_int_regs;
2908 /* Return whenever METHOD is a gsharedvt method */
2910 is_gsharedvt_method (MonoMethod *method)
2912 MonoGenericContext *context;
2913 MonoGenericInst *inst;
2916 if (!method->is_inflated)
2918 context = mono_method_get_context (method);
2919 inst = context->class_inst;
2921 for (i = 0; i < inst->type_argc; ++i)
2922 if (mini_is_gsharedvt_gparam (inst->type_argv [i]))
2925 inst = context->method_inst;
2927 for (i = 0; i < inst->type_argc; ++i)
2928 if (mini_is_gsharedvt_gparam (inst->type_argv [i]))
2935 is_open_method (MonoMethod *method)
2937 MonoGenericContext *context;
2939 if (!method->is_inflated)
2941 context = mono_method_get_context (method);
2942 if (context->class_inst && context->class_inst->is_open)
2944 if (context->method_inst && context->method_inst->is_open)
2950 mono_insert_nop_in_empty_bb (MonoCompile *cfg)
2953 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2957 MONO_INST_NEW (cfg, nop, OP_NOP);
2958 MONO_ADD_INS (bb, nop);
2962 mono_create_gc_safepoint (MonoCompile *cfg, MonoBasicBlock *bblock)
2964 MonoInst *poll_addr, *ins;
2966 if (cfg->disable_gc_safe_points)
2969 if (cfg->verbose_level > 1)
2970 printf ("ADDING SAFE POINT TO BB %d\n", bblock->block_num);
2972 #if defined(__native_client_codegen__)
2973 NEW_AOTCONST (cfg, poll_addr, MONO_PATCH_INFO_GC_SAFE_POINT_FLAG, (gpointer)&__nacl_thread_suspension_needed);
2975 g_assert (mono_threads_is_coop_enabled ());
2976 NEW_AOTCONST (cfg, poll_addr, MONO_PATCH_INFO_GC_SAFE_POINT_FLAG, (gpointer)&mono_polling_required);
2979 MONO_INST_NEW (cfg, ins, OP_GC_SAFE_POINT);
2980 ins->sreg1 = poll_addr->dreg;
2982 if (bblock->flags & BB_EXCEPTION_HANDLER) {
2983 MonoInst *eh_op = bblock->code;
2985 if (eh_op && eh_op->opcode != OP_START_HANDLER && eh_op->opcode != OP_GET_EX_OBJ) {
2988 MonoInst *next_eh_op = eh_op ? eh_op->next : NULL;
2989 // skip all EH relateds ops
2990 while (next_eh_op && (next_eh_op->opcode == OP_START_HANDLER || next_eh_op->opcode == OP_GET_EX_OBJ)) {
2992 next_eh_op = eh_op->next;
2996 mono_bblock_insert_after_ins (bblock, eh_op, poll_addr);
2997 mono_bblock_insert_after_ins (bblock, poll_addr, ins);
2998 } else if (bblock == cfg->bb_entry) {
2999 mono_bblock_insert_after_ins (bblock, bblock->last_ins, poll_addr);
3000 mono_bblock_insert_after_ins (bblock, poll_addr, ins);
3003 mono_bblock_insert_before_ins (bblock, NULL, poll_addr);
3004 mono_bblock_insert_after_ins (bblock, poll_addr, ins);
3009 This code inserts safepoints into managed code at important code paths.
3012 -the first basic block
3013 -landing BB for exception handlers
3018 mono_insert_safepoints (MonoCompile *cfg)
3022 #if !defined(__native_client_codegen__)
3023 if (!mono_threads_is_coop_enabled ())
3027 if (cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3028 WrapperInfo *info = mono_marshal_get_wrapper_info (cfg->method);
3029 #if defined(__native_client__) || defined(__native_client_codegen__)
3030 gpointer poll_func = &mono_nacl_gc;
3032 g_assert (mono_threads_is_coop_enabled ());
3033 gpointer poll_func = &mono_threads_state_poll;
3036 if (info && info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER && info->d.icall.func == poll_func) {
3037 if (cfg->verbose_level > 1)
3038 printf ("SKIPPING SAFEPOINTS for the polling function icall\n");
3043 if (cfg->method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
3044 if (cfg->verbose_level > 1)
3045 printf ("SKIPPING SAFEPOINTS for native-to-managed wrappers.\n");
3049 if (cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3050 WrapperInfo *info = mono_marshal_get_wrapper_info (cfg->method);
3052 if (info && info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER &&
3053 (info->d.icall.func == mono_thread_interruption_checkpoint ||
3054 info->d.icall.func == mono_threads_exit_gc_safe_region_unbalanced)) {
3055 /* These wrappers are called from the wrapper for the polling function, leading to potential stack overflow */
3056 if (cfg->verbose_level > 1)
3057 printf ("SKIPPING SAFEPOINTS for wrapper %s\n", cfg->method->name);
3062 if (cfg->verbose_level > 1)
3063 printf ("INSERTING SAFEPOINTS\n");
3064 if (cfg->verbose_level > 2)
3065 mono_print_code (cfg, "BEFORE SAFEPOINTS");
3067 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3068 if (bb->loop_body_start || bb == cfg->bb_entry || bb->flags & BB_EXCEPTION_HANDLER)
3069 mono_create_gc_safepoint (cfg, bb);
3072 if (cfg->verbose_level > 2)
3073 mono_print_code (cfg, "AFTER SAFEPOINTS");
3079 mono_insert_branches_between_bblocks (MonoCompile *cfg)
3083 /* Add branches between non-consecutive bblocks */
3084 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3085 if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins) &&
3086 bb->last_ins->inst_false_bb && bb->next_bb != bb->last_ins->inst_false_bb) {
3087 /* we are careful when inverting, since bugs like #59580
3088 * could show up when dealing with NaNs.
3090 if (MONO_IS_COND_BRANCH_NOFP(bb->last_ins) && bb->next_bb == bb->last_ins->inst_true_bb) {
3091 MonoBasicBlock *tmp = bb->last_ins->inst_true_bb;
3092 bb->last_ins->inst_true_bb = bb->last_ins->inst_false_bb;
3093 bb->last_ins->inst_false_bb = tmp;
3095 bb->last_ins->opcode = mono_reverse_branch_op (bb->last_ins->opcode);
3097 MonoInst *inst = (MonoInst *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
3098 inst->opcode = OP_BR;
3099 inst->inst_target_bb = bb->last_ins->inst_false_bb;
3100 mono_bblock_add_inst (bb, inst);
3105 if (cfg->verbose_level >= 4) {
3106 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3107 MonoInst *tree = bb->code;
3108 g_print ("DUMP BLOCK %d:\n", bb->block_num);
3111 for (; tree; tree = tree->next) {
3112 mono_print_ins_index (-1, tree);
3118 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3119 bb->max_vreg = cfg->next_vreg;
3124 init_backend (MonoBackend *backend)
3126 #ifdef MONO_ARCH_NEED_GOT_VAR
3127 backend->need_got_var = 1;
3129 #ifdef MONO_ARCH_HAVE_CARD_TABLE_WBARRIER
3130 backend->have_card_table_wb = 1;
3132 #ifdef MONO_ARCH_HAVE_OP_GENERIC_CLASS_INIT
3133 backend->have_op_generic_class_init = 1;
3135 #ifdef MONO_ARCH_EMULATE_MUL_DIV
3136 backend->emulate_mul_div = 1;
3138 #ifdef MONO_ARCH_EMULATE_DIV
3139 backend->emulate_div = 1;
3141 #if !defined(MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS)
3142 backend->emulate_long_shift_opts = 1;
3144 #ifdef MONO_ARCH_HAVE_OBJC_GET_SELECTOR
3145 backend->have_objc_get_selector = 1;
3147 #ifdef MONO_ARCH_HAVE_GENERALIZED_IMT_TRAMPOLINE
3148 backend->have_generalized_imt_trampoline = 1;
3150 #ifdef MONO_ARCH_GSHARED_SUPPORTED
3151 backend->gshared_supported = 1;
3153 if (MONO_ARCH_HAVE_TLS_GET)
3154 backend->have_tls_get = 1;
3155 #ifdef MONO_ARCH_HAVE_TLS_GET_REG
3156 backend->have_tls_get_reg = 1;
3158 if (MONO_ARCH_USE_FPSTACK)
3159 backend->use_fpstack = 1;
3160 #ifdef MONO_ARCH_HAVE_LIVERANGE_OPS
3161 backend->have_liverange_ops = 1;
3163 #ifdef MONO_ARCH_HAVE_OP_TAIL_CALL
3164 backend->have_op_tail_call = 1;
3166 #ifndef MONO_ARCH_MONITOR_ENTER_ADJUSTMENT
3167 backend->monitor_enter_adjustment = 1;
3169 backend->monitor_enter_adjustment = MONO_ARCH_MONITOR_ENTER_ADJUSTMENT;
3171 #if defined(__mono_ilp32__)
3174 #ifdef MONO_ARCH_HAVE_DUMMY_INIT
3175 backend->have_dummy_init = 1;
3177 #ifdef MONO_ARCH_NEED_DIV_CHECK
3178 backend->need_div_check = 1;
3180 #ifdef NO_UNALIGNED_ACCESS
3181 backend->no_unaligned_access = 1;
3183 #ifdef MONO_ARCH_DYN_CALL_PARAM_AREA
3184 backend->dyn_call_param_area = MONO_ARCH_DYN_CALL_PARAM_AREA;
3186 #ifdef MONO_ARCH_NO_DIV_WITH_MUL
3187 backend->disable_div_with_mul = 1;
3192 * mini_method_compile:
3193 * @method: the method to compile
3194 * @opts: the optimization flags to use
3195 * @domain: the domain where the method will be compiled in
3196 * @flags: compilation flags
3197 * @parts: debug flag
3199 * Returns: a MonoCompile* pointer. Caller must check the exception_type
3200 * field in the returned struct to see if compilation succeded.
3203 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFlags flags, int parts, int aot_method_index)
3205 MonoMethodHeader *header;
3206 MonoMethodSignature *sig;
3209 int i, code_size_ratio;
3210 gboolean try_generic_shared, try_llvm = FALSE;
3211 MonoMethod *method_to_compile, *method_to_register;
3212 gboolean method_is_gshared = FALSE;
3213 gboolean run_cctors = (flags & JIT_FLAG_RUN_CCTORS) ? 1 : 0;
3214 gboolean compile_aot = (flags & JIT_FLAG_AOT) ? 1 : 0;
3215 gboolean full_aot = (flags & JIT_FLAG_FULL_AOT) ? 1 : 0;
3216 gboolean disable_direct_icalls = (flags & JIT_FLAG_NO_DIRECT_ICALLS) ? 1 : 0;
3217 gboolean gsharedvt_method = FALSE;
3219 gboolean llvm = (flags & JIT_FLAG_LLVM) ? 1 : 0;
3221 static gboolean verbose_method_inited;
3222 static const char *verbose_method_name;
3224 InterlockedIncrement (&mono_jit_stats.methods_compiled);
3225 if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)
3226 mono_profiler_method_jit (method);
3227 if (MONO_METHOD_COMPILE_BEGIN_ENABLED ())
3228 MONO_PROBE_METHOD_COMPILE_BEGIN (method);
3230 gsharedvt_method = is_gsharedvt_method (method);
3233 * In AOT mode, method can be the following:
3234 * - a gsharedvt method.
3235 * - a method inflated with type parameters. This is for ref/partial sharing.
3236 * - a method inflated with concrete types.
3239 if (is_open_method (method)) {
3240 try_generic_shared = TRUE;
3241 method_is_gshared = TRUE;
3243 try_generic_shared = FALSE;
3245 g_assert (opts & MONO_OPT_GSHARED);
3247 try_generic_shared = mono_class_generic_sharing_enabled (method->klass) &&
3248 (opts & MONO_OPT_GSHARED) && mono_method_is_generic_sharable (method, FALSE);
3249 if (mini_is_gsharedvt_sharable_method (method)) {
3251 if (!mono_debug_count ())
3252 try_generic_shared = FALSE;
3258 if (try_generic_shared && !mono_debug_count ())
3259 try_generic_shared = FALSE;
3262 if (opts & MONO_OPT_GSHARED) {
3263 if (try_generic_shared)
3264 mono_stats.generics_sharable_methods++;
3265 else if (mono_method_is_generic_impl (method))
3266 mono_stats.generics_unsharable_methods++;
3270 try_llvm = mono_use_llvm || llvm;
3274 if (method_is_gshared) {
3275 method_to_compile = method;
3277 if (try_generic_shared) {
3278 method_to_compile = mini_get_shared_method (method);
3279 g_assert (method_to_compile);
3281 method_to_compile = method;
3285 cfg = g_new0 (MonoCompile, 1);
3286 cfg->method = method_to_compile;
3287 cfg->mempool = mono_mempool_new ();
3289 cfg->prof_options = mono_profiler_get_events ();
3290 cfg->run_cctors = run_cctors;
3291 cfg->domain = domain;
3292 cfg->verbose_level = mini_verbose;
3293 cfg->compile_aot = compile_aot;
3294 cfg->full_aot = full_aot;
3295 cfg->disable_omit_fp = debug_options.disable_omit_fp;
3296 cfg->skip_visibility = method->skip_visibility;
3297 cfg->orig_method = method;
3298 cfg->gen_seq_points = !debug_options.no_seq_points_compact_data || debug_options.gen_sdb_seq_points;
3299 cfg->gen_sdb_seq_points = debug_options.gen_sdb_seq_points;
3300 cfg->llvm_only = (flags & JIT_FLAG_LLVM_ONLY) != 0;
3301 cfg->backend = current_backend;
3303 #ifdef PLATFORM_ANDROID
3304 if (cfg->method->wrapper_type != MONO_WRAPPER_NONE) {
3305 /* FIXME: Why is this needed */
3306 cfg->gen_seq_points = FALSE;
3307 cfg->gen_sdb_seq_points = FALSE;
3310 if (cfg->method->wrapper_type == MONO_WRAPPER_ALLOC) {
3311 /* We can't have seq points inside gc critical regions */
3312 cfg->gen_seq_points = FALSE;
3313 cfg->gen_sdb_seq_points = FALSE;
3315 /* coop / nacl requires loop detection to happen */
3316 #if defined(__native_client_codegen__)
3317 cfg->opt |= MONO_OPT_LOOP;
3319 if (mono_threads_is_coop_enabled ())
3320 cfg->opt |= MONO_OPT_LOOP;
3322 cfg->explicit_null_checks = debug_options.explicit_null_checks || (flags & JIT_FLAG_EXPLICIT_NULL_CHECKS);
3323 cfg->soft_breakpoints = debug_options.soft_breakpoints;
3324 cfg->check_pinvoke_callconv = debug_options.check_pinvoke_callconv;
3325 cfg->disable_direct_icalls = disable_direct_icalls;
3326 cfg->direct_pinvoke = (flags & JIT_FLAG_DIRECT_PINVOKE) != 0;
3327 if (try_generic_shared)
3328 cfg->gshared = TRUE;
3329 cfg->compile_llvm = try_llvm;
3330 cfg->token_info_hash = g_hash_table_new (NULL, NULL);
3331 if (cfg->compile_aot)
3332 cfg->method_index = aot_method_index;
3335 if (!mono_debug_count ())
3336 cfg->opt &= ~MONO_OPT_FLOAT32;
3339 cfg->opt &= ~MONO_OPT_SIMD;
3340 cfg->r4fp = (cfg->opt & MONO_OPT_FLOAT32) ? 1 : 0;
3341 cfg->r4_stack_type = cfg->r4fp ? STACK_R4 : STACK_R8;
3343 if (cfg->gen_seq_points)
3344 cfg->seq_points = g_ptr_array_new ();
3345 mono_error_init (&cfg->error);
3347 if (cfg->compile_aot && !try_generic_shared && (method->is_generic || mono_class_is_gtd (method->klass) || method_is_gshared)) {
3348 cfg->exception_type = MONO_EXCEPTION_GENERIC_SHARING_FAILED;
3352 if (cfg->gshared && (gsharedvt_method || mini_is_gsharedvt_sharable_method (method))) {
3353 MonoMethodInflated *inflated;
3354 MonoGenericContext *context;
3356 if (gsharedvt_method) {
3357 g_assert (method->is_inflated);
3358 inflated = (MonoMethodInflated*)method;
3359 context = &inflated->context;
3361 /* We are compiling a gsharedvt method directly */
3362 g_assert (compile_aot);
3364 g_assert (method_to_compile->is_inflated);
3365 inflated = (MonoMethodInflated*)method_to_compile;
3366 context = &inflated->context;
3369 mini_init_gsctx (NULL, cfg->mempool, context, &cfg->gsctx);
3370 cfg->gsctx_context = context;
3372 cfg->gsharedvt = TRUE;
3373 if (!cfg->llvm_only) {
3374 cfg->disable_llvm = TRUE;
3375 cfg->exception_message = g_strdup ("gsharedvt");
3380 method_to_register = method_to_compile;
3382 g_assert (method == method_to_compile);
3383 method_to_register = method;
3385 cfg->method_to_register = method_to_register;
3387 mono_error_init (&err);
3388 sig = mono_method_signature_checked (cfg->method, &err);
3390 cfg->exception_type = MONO_EXCEPTION_TYPE_LOAD;
3391 cfg->exception_message = g_strdup (mono_error_get_message (&err));
3392 mono_error_cleanup (&err);
3393 if (MONO_METHOD_COMPILE_END_ENABLED ())
3394 MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
3398 header = cfg->header = mono_method_get_header_checked (cfg->method, &cfg->error);
3400 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
3401 if (MONO_METHOD_COMPILE_END_ENABLED ())
3402 MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
3408 static gboolean inited;
3414 * Check for methods which cannot be compiled by LLVM early, to avoid
3415 * the extra compilation pass.
3417 if (COMPILE_LLVM (cfg)) {
3418 mono_llvm_check_method_supported (cfg);
3419 if (cfg->disable_llvm) {
3420 if (cfg->verbose_level >= (cfg->llvm_only ? 0 : 1)) {
3421 //nm = mono_method_full_name (cfg->method, TRUE);
3422 printf ("LLVM failed for '%s': %s\n", method->name, cfg->exception_message);
3425 if (cfg->llvm_only) {
3426 g_free (cfg->exception_message);
3427 cfg->disable_aot = TRUE;
3430 mono_destroy_compile (cfg);
3432 goto restart_compile;
3438 /* The debugger has no liveness information, so avoid sharing registers/stack slots */
3439 if (debug_options.mdb_optimizations) {
3440 cfg->disable_reuse_registers = TRUE;
3441 cfg->disable_reuse_stack_slots = TRUE;
3443 * This decreases the change the debugger will read registers/stack slots which are
3444 * not yet initialized.
3446 cfg->disable_initlocals_opt = TRUE;
3448 cfg->extend_live_ranges = TRUE;
3450 /* The debugger needs all locals to be on the stack or in a global register */
3451 cfg->disable_vreg_to_lvreg = TRUE;
3453 /* Don't remove unused variables when running inside the debugger since the user
3454 * may still want to view them. */
3455 cfg->disable_deadce_vars = TRUE;
3457 cfg->opt &= ~MONO_OPT_DEADCE;
3458 cfg->opt &= ~MONO_OPT_INLINE;
3459 cfg->opt &= ~MONO_OPT_COPYPROP;
3460 cfg->opt &= ~MONO_OPT_CONSPROP;
3462 /* This is needed for the soft debugger, which doesn't like code after the epilog */
3463 cfg->disable_out_of_line_bblocks = TRUE;
3466 if (mono_using_xdebug) {
3468 * Make each variable use its own register/stack slot and extend
3469 * their liveness to cover the whole method, making them displayable
3470 * in gdb even after they are dead.
3472 cfg->disable_reuse_registers = TRUE;
3473 cfg->disable_reuse_stack_slots = TRUE;
3474 cfg->extend_live_ranges = TRUE;
3475 cfg->compute_precise_live_ranges = TRUE;
3478 mini_gc_init_cfg (cfg);
3480 if (method->wrapper_type == MONO_WRAPPER_UNKNOWN) {
3481 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3483 /* These wrappers are using linkonce linkage, so they can't access GOT slots */
3484 if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG))) {
3485 cfg->disable_gc_safe_points = TRUE;
3486 /* This is safe, these wrappers only store to the stack */
3487 cfg->gen_write_barriers = FALSE;
3491 if (COMPILE_LLVM (cfg)) {
3492 cfg->opt |= MONO_OPT_ABCREM;
3495 if (!verbose_method_inited) {
3496 verbose_method_name = g_getenv ("MONO_VERBOSE_METHOD");
3497 verbose_method_inited = TRUE;
3499 if (verbose_method_name) {
3500 const char *name = verbose_method_name;
3502 if ((strchr (name, '.') > name) || strchr (name, ':')) {
3503 MonoMethodDesc *desc;
3505 desc = mono_method_desc_new (name, TRUE);
3506 if (mono_method_desc_full_match (desc, cfg->method)) {
3507 cfg->verbose_level = 4;
3509 mono_method_desc_free (desc);
3511 if (strcmp (cfg->method->name, name) == 0)
3512 cfg->verbose_level = 4;
3516 cfg->intvars = (guint16 *)mono_mempool_alloc0 (cfg->mempool, sizeof (guint16) * STACK_MAX * header->max_stack);
3518 if (cfg->verbose_level > 0) {
3521 method_name = mono_method_get_full_name (method);
3522 g_print ("converting %s%s%smethod %s\n", COMPILE_LLVM (cfg) ? "llvm " : "", cfg->gsharedvt ? "gsharedvt " : "", (cfg->gshared && !cfg->gsharedvt) ? "gshared " : "", method_name);
3524 if (COMPILE_LLVM (cfg))
3525 g_print ("converting llvm method %s\n", method_name = mono_method_full_name (method, TRUE));
3526 else if (cfg->gsharedvt)
3527 g_print ("converting gsharedvt method %s\n", method_name = mono_method_full_name (method_to_compile, TRUE));
3528 else if (cfg->gshared)
3529 g_print ("converting shared method %s\n", method_name = mono_method_full_name (method_to_compile, TRUE));
3531 g_print ("converting method %s\n", method_name = mono_method_full_name (method, TRUE));
3533 g_free (method_name);
3536 if (cfg->opt & MONO_OPT_ABCREM)
3537 cfg->opt |= MONO_OPT_SSA;
3539 cfg->rs = mono_regstate_new ();
3540 cfg->next_vreg = cfg->rs->next_vreg;
3542 /* FIXME: Fix SSA to handle branches inside bblocks */
3543 if (cfg->opt & MONO_OPT_SSA)
3544 cfg->enable_extended_bblocks = FALSE;
3547 * FIXME: This confuses liveness analysis because variables which are assigned after
3548 * a branch inside a bblock become part of the kill set, even though the assignment
3549 * might not get executed. This causes the optimize_initlocals pass to delete some
3550 * assignments which are needed.
3551 * Also, the mono_if_conversion pass needs to be modified to recognize the code
3554 //cfg->enable_extended_bblocks = TRUE;
3556 /*We must verify the method before doing any IR generation as mono_compile_create_vars can assert.*/
3557 if (mono_compile_is_broken (cfg, cfg->method, TRUE)) {
3558 if (mini_get_debug_options ()->break_on_unverified)
3564 * create MonoInst* which represents arguments and local variables
3566 mono_compile_create_vars (cfg);
3568 mono_cfg_dump_create_context (cfg);
3569 mono_cfg_dump_begin_group (cfg);
3571 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));
3572 mono_cfg_dump_ir (cfg, "method-to-ir");
3574 if (cfg->gdump_ctx != NULL) {
3575 /* workaround for graph visualization, as it doesn't handle empty basic blocks properly */
3576 mono_insert_nop_in_empty_bb (cfg);
3577 mono_cfg_dump_ir (cfg, "mono_insert_nop_in_empty_bb");
3581 if (try_generic_shared && cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
3583 if (MONO_METHOD_COMPILE_END_ENABLED ())
3584 MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
3587 mono_destroy_compile (cfg);
3588 try_generic_shared = FALSE;
3589 goto restart_compile;
3591 g_assert (cfg->exception_type != MONO_EXCEPTION_GENERIC_SHARING_FAILED);
3593 if (MONO_METHOD_COMPILE_END_ENABLED ())
3594 MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
3595 /* cfg contains the details of the failure, so let the caller cleanup */
3599 cfg->stat_basic_blocks += cfg->num_bblocks;
3601 if (COMPILE_LLVM (cfg)) {
3604 /* The IR has to be in SSA form for LLVM */
3605 cfg->opt |= MONO_OPT_SSA;
3609 // Allow SSA on the result value
3610 cfg->ret->flags &= ~MONO_INST_VOLATILE;
3612 // Add an explicit return instruction referencing the return value
3613 MONO_INST_NEW (cfg, ins, OP_SETRET);
3614 ins->sreg1 = cfg->ret->dreg;
3616 MONO_ADD_INS (cfg->bb_exit, ins);
3619 cfg->opt &= ~MONO_OPT_LINEARS;
3622 cfg->opt &= ~MONO_OPT_BRANCH;
3625 /* todo: remove code when we have verified that the liveness for try/catch blocks
3629 * Currently, this can't be commented out since exception blocks are not
3630 * processed during liveness analysis.
3631 * It is also needed, because otherwise the local optimization passes would
3632 * delete assignments in cases like this:
3634 * <something which throws>
3636 * This also allows SSA to be run on methods containing exception clauses, since
3637 * SSA will ignore variables marked VOLATILE.
3639 MONO_TIME_TRACK (mono_jit_stats.jit_liveness_handle_exception_clauses, mono_liveness_handle_exception_clauses (cfg));
3640 mono_cfg_dump_ir (cfg, "liveness_handle_exception_clauses");
3642 MONO_TIME_TRACK (mono_jit_stats.jit_handle_out_of_line_bblock, mono_handle_out_of_line_bblock (cfg));
3643 mono_cfg_dump_ir (cfg, "handle_out_of_line_bblock");
3645 /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/
3647 if (!COMPILE_LLVM (cfg)) {
3648 MONO_TIME_TRACK (mono_jit_stats.jit_decompose_long_opts, mono_decompose_long_opts (cfg));
3649 mono_cfg_dump_ir (cfg, "decompose_long_opts");
3652 /* Should be done before branch opts */
3653 if (cfg->opt & (MONO_OPT_CONSPROP | MONO_OPT_COPYPROP)) {
3654 MONO_TIME_TRACK (mono_jit_stats.jit_local_cprop, mono_local_cprop (cfg));
3655 mono_cfg_dump_ir (cfg, "local_cprop");
3658 if (cfg->flags & MONO_CFG_HAS_TYPE_CHECK) {
3659 MONO_TIME_TRACK (mono_jit_stats.jit_decompose_typechecks, mono_decompose_typechecks (cfg));
3660 if (cfg->gdump_ctx != NULL) {
3661 /* workaround for graph visualization, as it doesn't handle empty basic blocks properly */
3662 mono_insert_nop_in_empty_bb (cfg);
3664 mono_cfg_dump_ir (cfg, "decompose_typechecks");
3668 * Should be done after cprop which can do strength reduction on
3669 * some of these ops, after propagating immediates.
3671 if (cfg->has_emulated_ops) {
3672 MONO_TIME_TRACK (mono_jit_stats.jit_local_emulate_ops, mono_local_emulate_ops (cfg));
3673 mono_cfg_dump_ir (cfg, "local_emulate_ops");
3676 if (cfg->opt & MONO_OPT_BRANCH) {
3677 MONO_TIME_TRACK (mono_jit_stats.jit_optimize_branches, mono_optimize_branches (cfg));
3678 mono_cfg_dump_ir (cfg, "optimize_branches");
3681 /* This must be done _before_ global reg alloc and _after_ decompose */
3682 MONO_TIME_TRACK (mono_jit_stats.jit_handle_global_vregs, mono_handle_global_vregs (cfg));
3683 mono_cfg_dump_ir (cfg, "handle_global_vregs");
3684 if (cfg->opt & MONO_OPT_DEADCE) {
3685 MONO_TIME_TRACK (mono_jit_stats.jit_local_deadce, mono_local_deadce (cfg));
3686 mono_cfg_dump_ir (cfg, "local_deadce");
3688 if (cfg->opt & MONO_OPT_ALIAS_ANALYSIS) {
3689 MONO_TIME_TRACK (mono_jit_stats.jit_local_alias_analysis, mono_local_alias_analysis (cfg));
3690 mono_cfg_dump_ir (cfg, "local_alias_analysis");
3692 /* Disable this for LLVM to make the IR easier to handle */
3693 if (!COMPILE_LLVM (cfg)) {
3694 MONO_TIME_TRACK (mono_jit_stats.jit_if_conversion, mono_if_conversion (cfg));
3695 mono_cfg_dump_ir (cfg, "if_conversion");
3698 mono_threads_safepoint ();
3700 MONO_TIME_TRACK (mono_jit_stats.jit_bb_ordering, mono_bb_ordering (cfg));
3701 mono_cfg_dump_ir (cfg, "bb_ordering");
3703 if (((cfg->num_varinfo > 2000) || (cfg->num_bblocks > 1000)) && !cfg->compile_aot) {
3705 * we disable some optimizations if there are too many variables
3706 * because JIT time may become too expensive. The actual number needs
3707 * to be tweaked and eventually the non-linear algorithms should be fixed.
3709 cfg->opt &= ~ (MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP);
3710 cfg->disable_ssa = TRUE;
3713 if (cfg->opt & MONO_OPT_LOOP) {
3714 MONO_TIME_TRACK (mono_jit_stats.jit_compile_dominator_info, mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM));
3715 MONO_TIME_TRACK (mono_jit_stats.jit_compute_natural_loops, mono_compute_natural_loops (cfg));
3718 MONO_TIME_TRACK (mono_jit_stats.jit_insert_safepoints, mono_insert_safepoints (cfg));
3719 mono_cfg_dump_ir (cfg, "insert_safepoints");
3721 /* after method_to_ir */
3723 if (MONO_METHOD_COMPILE_END_ENABLED ())
3724 MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
3729 if (header->num_clauses)
3730 cfg->disable_ssa = TRUE;
3733 //#define DEBUGSSA "logic_run"
3734 //#define DEBUGSSA_CLASS "Tests"
3737 if (!cfg->disable_ssa) {
3738 mono_local_cprop (cfg);
3741 mono_ssa_compute (cfg);
3745 if (cfg->opt & MONO_OPT_SSA) {
3746 if (!(cfg->comp_done & MONO_COMP_SSA) && !cfg->disable_ssa) {
3748 MONO_TIME_TRACK (mono_jit_stats.jit_ssa_compute, mono_ssa_compute (cfg));
3749 mono_cfg_dump_ir (cfg, "ssa_compute");
3752 if (cfg->verbose_level >= 2) {
3759 /* after SSA translation */
3761 if (MONO_METHOD_COMPILE_END_ENABLED ())
3762 MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
3766 if ((cfg->opt & MONO_OPT_CONSPROP) || (cfg->opt & MONO_OPT_COPYPROP)) {
3767 if (cfg->comp_done & MONO_COMP_SSA && !COMPILE_LLVM (cfg)) {
3769 MONO_TIME_TRACK (mono_jit_stats.jit_ssa_cprop, mono_ssa_cprop (cfg));
3770 mono_cfg_dump_ir (cfg, "ssa_cprop");
3776 if (cfg->comp_done & MONO_COMP_SSA && !COMPILE_LLVM (cfg)) {
3777 //mono_ssa_strength_reduction (cfg);
3779 if (cfg->opt & MONO_OPT_DEADCE) {
3780 MONO_TIME_TRACK (mono_jit_stats.jit_ssa_deadce, mono_ssa_deadce (cfg));
3781 mono_cfg_dump_ir (cfg, "ssa_deadce");
3784 if ((cfg->flags & (MONO_CFG_HAS_LDELEMA|MONO_CFG_HAS_CHECK_THIS)) && (cfg->opt & MONO_OPT_ABCREM)) {
3785 MONO_TIME_TRACK (mono_jit_stats.jit_perform_abc_removal, mono_perform_abc_removal (cfg));
3786 mono_cfg_dump_ir (cfg, "perform_abc_removal");
3789 MONO_TIME_TRACK (mono_jit_stats.jit_ssa_remove, mono_ssa_remove (cfg));
3790 mono_cfg_dump_ir (cfg, "ssa_remove");
3791 MONO_TIME_TRACK (mono_jit_stats.jit_local_cprop2, mono_local_cprop (cfg));
3792 mono_cfg_dump_ir (cfg, "local_cprop2");
3793 MONO_TIME_TRACK (mono_jit_stats.jit_handle_global_vregs2, mono_handle_global_vregs (cfg));
3794 mono_cfg_dump_ir (cfg, "handle_global_vregs2");
3795 if (cfg->opt & MONO_OPT_DEADCE) {
3796 MONO_TIME_TRACK (mono_jit_stats.jit_local_deadce2, mono_local_deadce (cfg));
3797 mono_cfg_dump_ir (cfg, "local_deadce2");
3800 if (cfg->opt & MONO_OPT_BRANCH) {
3801 MONO_TIME_TRACK (mono_jit_stats.jit_optimize_branches2, mono_optimize_branches (cfg));
3802 mono_cfg_dump_ir (cfg, "optimize_branches2");
3807 if (cfg->comp_done & MONO_COMP_SSA && COMPILE_LLVM (cfg)) {
3808 mono_ssa_loop_invariant_code_motion (cfg);
3809 mono_cfg_dump_ir (cfg, "loop_invariant_code_motion");
3810 /* This removes MONO_INST_FAULT flags too so perform it unconditionally */
3811 if (cfg->opt & MONO_OPT_ABCREM) {
3812 mono_perform_abc_removal (cfg);
3813 mono_cfg_dump_ir (cfg, "abc_removal");
3817 /* after SSA removal */
3819 if (MONO_METHOD_COMPILE_END_ENABLED ())
3820 MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
3824 if (cfg->llvm_only && cfg->gsharedvt)
3825 mono_ssa_remove_gsharedvt (cfg);
3827 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
3828 if (COMPILE_SOFT_FLOAT (cfg))
3829 mono_decompose_soft_float (cfg);
3831 MONO_TIME_TRACK (mono_jit_stats.jit_decompose_vtype_opts, mono_decompose_vtype_opts (cfg));
3832 if (cfg->flags & MONO_CFG_HAS_ARRAY_ACCESS) {
3833 MONO_TIME_TRACK (mono_jit_stats.jit_decompose_array_access_opts, mono_decompose_array_access_opts (cfg));
3834 mono_cfg_dump_ir (cfg, "decompose_array_access_opts");
3838 #ifndef MONO_ARCH_GOT_REG
3843 g_assert (cfg->got_var_allocated);
3846 * Allways allocate the GOT var to a register, because keeping it
3847 * in memory will increase the number of live temporaries in some
3848 * code created by inssel.brg, leading to the well known spills+
3849 * branches problem. Testcase: mcs crash in
3850 * System.MonoCustomAttrs:GetCustomAttributes.
3852 #ifdef MONO_ARCH_GOT_REG
3853 got_reg = MONO_ARCH_GOT_REG;
3855 regs = mono_arch_get_global_int_regs (cfg);
3857 got_reg = GPOINTER_TO_INT (regs->data);
3860 cfg->got_var->opcode = OP_REGVAR;
3861 cfg->got_var->dreg = got_reg;
3862 cfg->used_int_regs |= 1LL << cfg->got_var->dreg;
3866 * Have to call this again to process variables added since the first call.
3868 MONO_TIME_TRACK(mono_jit_stats.jit_liveness_handle_exception_clauses2, mono_liveness_handle_exception_clauses (cfg));
3870 if (cfg->opt & MONO_OPT_LINEARS) {
3871 GList *vars, *regs, *l;
3873 /* fixme: maybe we can avoid to compute livenesss here if already computed ? */
3874 cfg->comp_done &= ~MONO_COMP_LIVENESS;
3875 if (!(cfg->comp_done & MONO_COMP_LIVENESS))
3876 MONO_TIME_TRACK (mono_jit_stats.jit_analyze_liveness, mono_analyze_liveness (cfg));
3878 if ((vars = mono_arch_get_allocatable_int_vars (cfg))) {
3879 regs = mono_arch_get_global_int_regs (cfg);
3880 /* Remove the reg reserved for holding the GOT address */
3882 for (l = regs; l; l = l->next) {
3883 if (GPOINTER_TO_UINT (l->data) == cfg->got_var->dreg) {
3884 regs = g_list_delete_link (regs, l);
3889 MONO_TIME_TRACK (mono_jit_stats.jit_linear_scan, mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs));
3890 mono_cfg_dump_ir (cfg, "linear_scan");
3894 //mono_print_code (cfg, "");
3898 /* variables are allocated after decompose, since decompose could create temps */
3899 if (!COMPILE_LLVM (cfg)) {
3900 MONO_TIME_TRACK (mono_jit_stats.jit_arch_allocate_vars, mono_arch_allocate_vars (cfg));
3901 mono_cfg_dump_ir (cfg, "arch_allocate_vars");
3902 if (cfg->exception_type)
3907 mono_allocate_gsharedvt_vars (cfg);
3909 if (!COMPILE_LLVM (cfg)) {
3910 gboolean need_local_opts;
3911 MONO_TIME_TRACK (mono_jit_stats.jit_spill_global_vars, mono_spill_global_vars (cfg, &need_local_opts));
3912 mono_cfg_dump_ir (cfg, "spill_global_vars");
3914 if (need_local_opts || cfg->compile_aot) {
3915 /* To optimize code created by spill_global_vars */
3916 MONO_TIME_TRACK (mono_jit_stats.jit_local_cprop3, mono_local_cprop (cfg));
3917 if (cfg->opt & MONO_OPT_DEADCE)
3918 MONO_TIME_TRACK (mono_jit_stats.jit_local_deadce3, mono_local_deadce (cfg));
3919 mono_cfg_dump_ir (cfg, "needs_local_opts");
3923 mono_insert_branches_between_bblocks (cfg);
3925 if (COMPILE_LLVM (cfg)) {
3929 /* The IR has to be in SSA form for LLVM */
3930 if (!(cfg->comp_done & MONO_COMP_SSA)) {
3931 cfg->exception_message = g_strdup ("SSA disabled.");
3932 cfg->disable_llvm = TRUE;
3935 if (cfg->flags & MONO_CFG_HAS_ARRAY_ACCESS)
3936 mono_decompose_array_access_opts (cfg);
3938 if (!cfg->disable_llvm)
3939 mono_llvm_emit_method (cfg);
3940 if (cfg->disable_llvm) {
3941 if (cfg->verbose_level >= (cfg->llvm_only ? 0 : 1)) {
3942 //nm = mono_method_full_name (cfg->method, TRUE);
3943 printf ("LLVM failed for '%s': %s\n", method->name, cfg->exception_message);
3946 if (cfg->llvm_only) {
3947 cfg->disable_aot = TRUE;
3950 mono_destroy_compile (cfg);
3952 goto restart_compile;
3955 if (cfg->verbose_level > 0 && !cfg->compile_aot) {
3956 nm = mono_method_full_name (cfg->method, TRUE);
3957 g_print ("LLVM Method %s emitted at %p to %p (code length %d) [%s]\n",
3959 cfg->native_code, cfg->native_code + cfg->code_len, cfg->code_len, cfg->domain->friendly_name);
3964 MONO_TIME_TRACK (mono_jit_stats.jit_codegen, mono_codegen (cfg));
3965 mono_cfg_dump_ir (cfg, "codegen");
3966 if (cfg->exception_type)
3970 if (COMPILE_LLVM (cfg))
3971 InterlockedIncrement (&mono_jit_stats.methods_with_llvm);
3973 InterlockedIncrement (&mono_jit_stats.methods_without_llvm);
3975 MONO_TIME_TRACK (mono_jit_stats.jit_create_jit_info, cfg->jit_info = create_jit_info (cfg, method_to_compile));
3977 #ifdef MONO_ARCH_HAVE_LIVERANGE_OPS
3978 if (cfg->extend_live_ranges) {
3979 /* Extend live ranges to cover the whole method */
3980 for (i = 0; i < cfg->num_varinfo; ++i)
3981 MONO_VARINFO (cfg, i)->live_range_end = cfg->code_len;
3985 if (!cfg->compile_aot)
3986 mono_save_xdebug_info (cfg);
3988 MONO_TIME_TRACK (mono_jit_stats.jit_gc_create_gc_map, mini_gc_create_gc_map (cfg));
3990 MONO_TIME_TRACK (mono_jit_stats.jit_save_seq_point_info, mono_save_seq_point_info (cfg));
3992 if (cfg->verbose_level >= 2) {
3993 char *id = mono_method_full_name (cfg->method, FALSE);
3994 mono_disassemble_code (cfg, cfg->native_code, cfg->code_len, id + 3);
3998 if (!cfg->compile_aot) {
3999 mono_domain_lock (cfg->domain);
4000 mono_jit_info_table_add (cfg->domain, cfg->jit_info);
4002 if (cfg->method->dynamic)
4003 mono_dynamic_code_hash_lookup (cfg->domain, cfg->method)->ji = cfg->jit_info;
4004 mono_domain_unlock (cfg->domain);
4009 printf ("GSHAREDVT: %s\n", mono_method_full_name (cfg->method, TRUE));
4012 /* collect statistics */
4013 #ifndef DISABLE_PERFCOUNTERS
4014 mono_perfcounters->jit_methods++;
4015 mono_perfcounters->jit_bytes += header->code_size;
4017 mono_jit_stats.allocated_code_size += cfg->code_len;
4018 code_size_ratio = cfg->code_len;
4019 if (code_size_ratio > mono_jit_stats.biggest_method_size && mono_jit_stats.enabled) {
4020 mono_jit_stats.biggest_method_size = code_size_ratio;
4021 g_free (mono_jit_stats.biggest_method);
4022 mono_jit_stats.biggest_method = g_strdup_printf ("%s::%s)", method->klass->name, method->name);
4024 code_size_ratio = (code_size_ratio * 100) / header->code_size;
4025 if (code_size_ratio > mono_jit_stats.max_code_size_ratio && mono_jit_stats.enabled) {
4026 mono_jit_stats.max_code_size_ratio = code_size_ratio;
4027 g_free (mono_jit_stats.max_ratio_method);
4028 mono_jit_stats.max_ratio_method = g_strdup_printf ("%s::%s)", method->klass->name, method->name);
4030 mono_jit_stats.native_code_size += cfg->code_len;
4032 if (MONO_METHOD_COMPILE_END_ENABLED ())
4033 MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
4035 mono_cfg_dump_close_group (cfg);
4041 mono_arch_instrument_epilog (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments)
4043 return mono_arch_instrument_epilog_full (cfg, func, p, enable_arguments, FALSE);
4047 mono_cfg_add_try_hole (MonoCompile *cfg, MonoExceptionClause *clause, guint8 *start, MonoBasicBlock *bb)
4049 TryBlockHole *hole = (TryBlockHole *)mono_mempool_alloc (cfg->mempool, sizeof (TryBlockHole));
4050 hole->clause = clause;
4051 hole->start_offset = start - cfg->native_code;
4052 hole->basic_block = bb;
4054 cfg->try_block_holes = g_slist_append_mempool (cfg->mempool, cfg->try_block_holes, hole);
4058 mono_cfg_set_exception (MonoCompile *cfg, int type)
4060 cfg->exception_type = type;
4063 /* Assumes ownership of the MSG argument */
4065 mono_cfg_set_exception_invalid_program (MonoCompile *cfg, char *msg)
4067 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
4068 mono_error_set_generic_error (&cfg->error, "System", "InvalidProgramException", "%s", msg);
4071 #endif /* DISABLE_JIT */
4074 create_jit_info_for_trampoline (MonoMethod *wrapper, MonoTrampInfo *info)
4076 MonoDomain *domain = mono_get_root_domain ();
4081 if (info->uw_info) {
4082 uw_info = info->uw_info;
4083 info_len = info->uw_info_len;
4085 uw_info = mono_unwind_ops_encode (info->unwind_ops, &info_len);
4088 jinfo = (MonoJitInfo *)mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO);
4089 jinfo->d.method = wrapper;
4090 jinfo->code_start = info->code;
4091 jinfo->code_size = info->code_size;
4092 jinfo->unwind_info = mono_cache_unwind_info (uw_info, info_len);
4100 GTimer *mono_time_track_start ()
4102 return g_timer_new ();
4105 void mono_time_track_end (double *time, GTimer *timer)
4107 g_timer_stop (timer);
4108 *time += g_timer_elapsed (timer, NULL);
4109 g_timer_destroy (timer);
4112 void mono_update_jit_stats (MonoCompile *cfg)
4114 mono_jit_stats.allocate_var += cfg->stat_allocate_var;
4115 mono_jit_stats.locals_stack_size += cfg->stat_locals_stack_size;
4116 mono_jit_stats.basic_blocks += cfg->stat_basic_blocks;
4117 mono_jit_stats.max_basic_blocks = MAX (cfg->stat_basic_blocks, mono_jit_stats.max_basic_blocks);
4118 mono_jit_stats.cil_code_size += cfg->stat_cil_code_size;
4119 mono_jit_stats.regvars += cfg->stat_n_regvars;
4120 mono_jit_stats.inlineable_methods += cfg->stat_inlineable_methods;
4121 mono_jit_stats.inlined_methods += cfg->stat_inlined_methods;
4122 mono_jit_stats.code_reallocs += cfg->stat_code_reallocs;
4126 * mono_jit_compile_method_inner:
4128 * Main entry point for the JIT.
4131 mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain, int opt, MonoError *error)
4134 gpointer code = NULL;
4135 MonoJitInfo *jinfo, *info;
4137 MonoException *ex = NULL;
4138 guint32 prof_options;
4140 MonoMethod *prof_method, *shared;
4142 mono_error_init (error);
4144 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
4145 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4147 MonoMethodPInvoke* piinfo = (MonoMethodPInvoke *) method;
4149 if (!piinfo->addr) {
4150 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
4151 piinfo->addr = mono_lookup_internal_call (method);
4152 else if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)
4154 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);
4156 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);
4159 mono_lookup_pinvoke_call (method, NULL, NULL);
4161 nm = mono_marshal_get_native_wrapper (method, TRUE, mono_aot_only);
4162 gpointer compiled_method = mono_compile_method_checked (nm, error);
4163 return_val_if_nok (error, NULL);
4164 code = mono_get_addr_from_ftnptr (compiled_method);
4165 jinfo = mono_jit_info_table_find (target_domain, (char *)code);
4167 jinfo = mono_jit_info_table_find (mono_domain_get (), (char *)code);
4169 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
4171 } else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
4172 const char *name = method->name;
4173 char *full_name, *msg;
4176 if (method->klass->parent == mono_defaults.multicastdelegate_class) {
4177 if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
4178 MonoJitICallInfo *mi = mono_find_jit_icall_by_name ("ves_icall_mono_delegate_ctor");
4181 * We need to make sure this wrapper
4182 * is compiled because it might end up
4183 * in an (M)RGCTX if generic sharing
4184 * is enabled, and would be called
4185 * indirectly. If it were a
4186 * trampoline we'd try to patch that
4187 * indirect call, which is not
4190 return mono_get_addr_from_ftnptr ((gpointer)mono_icall_get_wrapper_full (mi, TRUE));
4191 } else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
4192 if (mono_llvm_only) {
4193 nm = mono_marshal_get_delegate_invoke (method, NULL);
4194 gpointer compiled_ptr = mono_compile_method_checked (nm, error);
4195 mono_error_assert_ok (error);
4196 return mono_get_addr_from_ftnptr (compiled_ptr);
4198 return mono_create_delegate_trampoline (target_domain, method->klass);
4199 } else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
4200 nm = mono_marshal_get_delegate_begin_invoke (method);
4201 gpointer compiled_ptr = mono_compile_method_checked (nm, error);
4202 mono_error_assert_ok (error);
4203 return mono_get_addr_from_ftnptr (compiled_ptr);
4204 } else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
4205 nm = mono_marshal_get_delegate_end_invoke (method);
4206 gpointer compiled_ptr = mono_compile_method_checked (nm, error);
4207 mono_error_assert_ok (error);
4208 return mono_get_addr_from_ftnptr (compiled_ptr);
4212 full_name = mono_method_full_name (method, TRUE);
4213 msg = g_strdup_printf ("Unrecognizable runtime implemented method '%s'", full_name);
4214 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "InvalidProgramException", msg);
4215 mono_error_set_exception_instance (error, ex);
4221 if (method->wrapper_type == MONO_WRAPPER_UNKNOWN) {
4222 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
4224 if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT) {
4225 static MonoTrampInfo *in_tinfo, *out_tinfo;
4226 MonoTrampInfo *tinfo;
4228 gboolean is_in = info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN;
4230 if (is_in && in_tinfo)
4231 return in_tinfo->code;
4232 else if (!is_in && out_tinfo)
4233 return out_tinfo->code;
4236 * This is a special wrapper whose body is implemented in assembly, like a trampoline. We use a wrapper so EH
4238 * FIXME: The caller signature doesn't match the callee, which might cause problems on some platforms
4241 mono_aot_get_trampoline_full (is_in ? "gsharedvt_trampoline" : "gsharedvt_out_trampoline", &tinfo);
4243 mono_arch_get_gsharedvt_trampoline (&tinfo, FALSE);
4244 jinfo = create_jit_info_for_trampoline (method, tinfo);
4245 mono_jit_info_table_add (mono_get_root_domain (), jinfo);
4254 if (mono_aot_only) {
4255 char *fullname = mono_method_full_name (method, TRUE);
4256 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);
4262 jit_timer = mono_time_track_start ();
4263 cfg = mini_method_compile (method, opt, target_domain, JIT_FLAG_RUN_CCTORS, 0, -1);
4264 double jit_time = 0.0;
4265 mono_time_track_end (&jit_time, jit_timer);
4266 mono_jit_stats.jit_time += jit_time;
4268 prof_method = cfg->method;
4270 switch (cfg->exception_type) {
4271 case MONO_EXCEPTION_NONE:
4273 case MONO_EXCEPTION_TYPE_LOAD:
4274 case MONO_EXCEPTION_MISSING_FIELD:
4275 case MONO_EXCEPTION_MISSING_METHOD:
4276 case MONO_EXCEPTION_FILE_NOT_FOUND:
4277 case MONO_EXCEPTION_BAD_IMAGE:
4278 case MONO_EXCEPTION_INVALID_PROGRAM: {
4279 /* Throw a type load exception if needed */
4280 if (cfg->exception_ptr) {
4281 ex = mono_class_get_exception_for_failure ((MonoClass *)cfg->exception_ptr);
4283 if (cfg->exception_type == MONO_EXCEPTION_MISSING_FIELD)
4284 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingFieldException", cfg->exception_message);
4285 else if (cfg->exception_type == MONO_EXCEPTION_MISSING_METHOD)
4286 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingMethodException", cfg->exception_message);
4287 else if (cfg->exception_type == MONO_EXCEPTION_TYPE_LOAD)
4288 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "TypeLoadException", cfg->exception_message);
4289 else if (cfg->exception_type == MONO_EXCEPTION_FILE_NOT_FOUND)
4290 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System.IO", "FileNotFoundException", cfg->exception_message);
4291 else if (cfg->exception_type == MONO_EXCEPTION_BAD_IMAGE)
4292 ex = mono_get_exception_bad_image_format (cfg->exception_message);
4293 else if (cfg->exception_type == MONO_EXCEPTION_INVALID_PROGRAM)
4294 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "InvalidProgramException", cfg->exception_message);
4296 g_assert_not_reached ();
4300 case MONO_EXCEPTION_MONO_ERROR:
4301 // FIXME: MonoError has no copy ctor
4302 g_assert (!mono_error_ok (&cfg->error));
4303 ex = mono_error_convert_to_exception (&cfg->error);
4306 g_assert_not_reached ();
4310 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
4311 mono_profiler_method_end_jit (method, NULL, MONO_PROFILE_FAILED);
4313 mono_destroy_compile (cfg);
4314 mono_error_set_exception_instance (error, ex);
4319 if (mono_method_is_generic_sharable (method, FALSE))
4320 shared = mini_get_shared_method (method);
4324 mono_domain_lock (target_domain);
4326 /* Check if some other thread already did the job. In this case, we can
4327 discard the code this thread generated. */
4329 info = mini_lookup_method (target_domain, method, shared);
4331 /* We can't use a domain specific method in another domain */
4332 if ((target_domain == mono_domain_get ()) || info->domain_neutral) {
4333 code = info->code_start;
4335 discarded_jit_time += jit_time;
4339 /* The lookup + insert is atomic since this is done inside the domain lock */
4340 mono_domain_jit_code_hash_lock (target_domain);
4341 mono_internal_hash_table_insert (&target_domain->jit_code_hash, cfg->jit_info->d.method, cfg->jit_info);
4342 mono_domain_jit_code_hash_unlock (target_domain);
4344 code = cfg->native_code;
4346 if (cfg->gshared && mono_method_is_generic_sharable (method, FALSE))
4347 mono_stats.generics_shared_methods++;
4349 mono_stats.gsharedvt_methods++;
4352 jinfo = cfg->jit_info;
4354 prof_options = cfg->prof_options;
4357 * Update global stats while holding a lock, instead of doing many
4358 * InterlockedIncrement operations during JITting.
4360 mono_update_jit_stats (cfg);
4362 mono_destroy_compile (cfg);
4365 if (domain_jit_info (target_domain)->jump_target_hash) {
4366 MonoJumpInfo patch_info;
4367 MonoJumpList *jlist;
4369 jlist = (MonoJumpList *)g_hash_table_lookup (domain_jit_info (target_domain)->jump_target_hash, method);
4371 patch_info.next = NULL;
4372 patch_info.ip.i = 0;
4373 patch_info.type = MONO_PATCH_INFO_METHOD_JUMP;
4374 patch_info.data.method = method;
4375 g_hash_table_remove (domain_jit_info (target_domain)->jump_target_hash, method);
4377 #ifdef MONO_ARCH_HAVE_PATCH_CODE_NEW
4378 for (tmp = jlist->list; tmp; tmp = tmp->next) {
4379 gpointer target = mono_resolve_patch_target (NULL, target_domain, (guint8 *)tmp->data, &patch_info, TRUE, error);
4380 if (!mono_error_ok (error))
4382 mono_arch_patch_code_new (NULL, target_domain, (guint8 *)tmp->data, &patch_info, target);
4385 for (tmp = jlist->list; tmp; tmp = tmp->next) {
4386 mono_arch_patch_code (NULL, NULL, target_domain, tmp->data, &patch_info, TRUE, error);
4394 /* Update llvm callees */
4395 if (domain_jit_info (target_domain)->llvm_jit_callees) {
4396 GSList *callees = g_hash_table_lookup (domain_jit_info (target_domain)->llvm_jit_callees, method);
4399 for (l = callees; l; l = l->next) {
4400 gpointer *addr = (gpointer*)l->data;
4406 mono_emit_jit_map (jinfo);
4408 mono_domain_unlock (target_domain);
4410 if (!mono_error_ok (error))
4413 vtable = mono_class_vtable (target_domain, method->klass);
4415 g_assert (mono_class_has_failure (method->klass));
4416 mono_error_set_for_class_failure (error, method->klass);
4420 if (prof_options & MONO_PROFILE_JIT_COMPILATION) {
4421 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
4422 if (mono_marshal_method_from_wrapper (method)) {
4423 /* Native func wrappers have no method */
4424 /* The profiler doesn't know about wrappers, so pass the original icall method */
4425 mono_profiler_method_end_jit (mono_marshal_method_from_wrapper (method), jinfo, MONO_PROFILE_OK);
4428 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
4429 if (prof_method != method) {
4430 mono_profiler_method_end_jit (prof_method, jinfo, MONO_PROFILE_OK);
4434 if (!mono_runtime_class_init_full (vtable, error))
4440 * mini_get_underlying_type:
4442 * Return the type the JIT will use during compilation.
4443 * Handles: byref, enums, native types, generic sharing.
4444 * For gsharedvt types, it will return the original VAR/MVAR.
4447 mini_get_underlying_type (MonoType *type)
4449 return mini_type_get_underlying_type (type);
4453 mini_jit_init (void)
4455 mono_counters_register ("Discarded method code", MONO_COUNTER_JIT | MONO_COUNTER_INT, &discarded_code);
4456 mono_counters_register ("Time spent JITting discarded code", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &discarded_jit_time);
4458 mono_os_mutex_init_recursive (&jit_mutex);
4460 current_backend = g_new0 (MonoBackend, 1);
4461 init_backend (current_backend);
4466 mini_jit_cleanup (void)
4469 g_free (emul_opcode_map);
4470 g_free (emul_opcode_opcodes);
4476 mono_llvm_emit_aot_file_info (MonoAotFileInfo *info, gboolean has_jitted_code)
4478 g_assert_not_reached ();
4481 void mono_llvm_emit_aot_data (const char *symbol, guint8 *data, int data_len)
4483 g_assert_not_reached ();
4488 #if !defined(ENABLE_LLVM_RUNTIME) && !defined(ENABLE_LLVM)
4491 mono_llvm_cpp_throw_exception (void)
4493 g_assert_not_reached ();
4501 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFlags flags, int parts, int aot_method_index)
4503 g_assert_not_reached ();
4508 mono_destroy_compile (MonoCompile *cfg)
4510 g_assert_not_reached ();
4514 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
4516 g_assert_not_reached ();
4519 #endif /* DISABLE_JIT */