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;
88 #define mono_jit_lock() mono_os_mutex_lock (&jit_mutex)
89 #define mono_jit_unlock() mono_os_mutex_unlock (&jit_mutex)
90 static mono_mutex_t jit_mutex;
92 MonoBackend *current_backend;
97 mono_realloc_native_code (MonoCompile *cfg)
99 return g_realloc (cfg->native_code, cfg->code_size);
103 MonoExceptionClause *clause;
104 MonoBasicBlock *basic_block;
109 * mono_emit_unwind_op:
111 * Add an unwind op with the given parameters for the list of unwind ops stored in
115 mono_emit_unwind_op (MonoCompile *cfg, int when, int tag, int reg, int val)
117 MonoUnwindOp *op = (MonoUnwindOp *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoUnwindOp));
124 cfg->unwind_ops = g_slist_append_mempool (cfg->mempool, cfg->unwind_ops, op);
125 if (cfg->verbose_level > 1) {
128 printf ("CFA: [%x] def_cfa: %s+0x%x\n", when, mono_arch_regname (reg), val);
130 case DW_CFA_def_cfa_register:
131 printf ("CFA: [%x] def_cfa_reg: %s\n", when, mono_arch_regname (reg));
133 case DW_CFA_def_cfa_offset:
134 printf ("CFA: [%x] def_cfa_offset: 0x%x\n", when, val);
137 printf ("CFA: [%x] offset: %s at cfa-0x%x\n", when, mono_arch_regname (reg), -val);
143 #define MONO_INIT_VARINFO(vi,id) do { \
144 (vi)->range.first_use.pos.bid = 0xffff; \
150 * mono_unlink_bblock:
152 * Unlink two basic blocks.
155 mono_unlink_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
161 for (i = 0; i < from->out_count; ++i) {
162 if (to == from->out_bb [i]) {
169 for (i = 0; i < from->out_count; ++i) {
170 if (from->out_bb [i] != to)
171 from->out_bb [pos ++] = from->out_bb [i];
173 g_assert (pos == from->out_count - 1);
178 for (i = 0; i < to->in_count; ++i) {
179 if (from == to->in_bb [i]) {
186 for (i = 0; i < to->in_count; ++i) {
187 if (to->in_bb [i] != from)
188 to->in_bb [pos ++] = to->in_bb [i];
190 g_assert (pos == to->in_count - 1);
196 * mono_bblocks_linked:
198 * Return whenever BB1 and BB2 are linked in the CFG.
201 mono_bblocks_linked (MonoBasicBlock *bb1, MonoBasicBlock *bb2)
205 for (i = 0; i < bb1->out_count; ++i) {
206 if (bb1->out_bb [i] == bb2)
214 mono_find_block_region_notry (MonoCompile *cfg, int offset)
216 MonoMethodHeader *header = cfg->header;
217 MonoExceptionClause *clause;
220 for (i = 0; i < header->num_clauses; ++i) {
221 clause = &header->clauses [i];
222 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->data.filter_offset) &&
223 (offset < (clause->handler_offset)))
224 return ((i + 1) << 8) | MONO_REGION_FILTER | clause->flags;
226 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
227 if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
228 return ((i + 1) << 8) | MONO_REGION_FINALLY | clause->flags;
229 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
230 return ((i + 1) << 8) | MONO_REGION_FAULT | clause->flags;
232 return ((i + 1) << 8) | MONO_REGION_CATCH | clause->flags;
240 * mono_get_block_region_notry:
242 * Return the region corresponding to REGION, ignoring try clauses nested inside
246 mono_get_block_region_notry (MonoCompile *cfg, int region)
248 if ((region & (0xf << 4)) == MONO_REGION_TRY) {
249 MonoMethodHeader *header = cfg->header;
252 * This can happen if a try clause is nested inside a finally clause.
254 int clause_index = (region >> 8) - 1;
255 g_assert (clause_index >= 0 && clause_index < header->num_clauses);
257 region = mono_find_block_region_notry (cfg, header->clauses [clause_index].try_offset);
264 mono_find_spvar_for_region (MonoCompile *cfg, int region)
266 region = mono_get_block_region_notry (cfg, region);
268 return (MonoInst *)g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
272 df_visit (MonoBasicBlock *start, int *dfn, MonoBasicBlock **array)
276 array [*dfn] = start;
277 /* g_print ("visit %d at %p (BB%ld)\n", *dfn, start->cil_code, start->block_num); */
278 for (i = 0; i < start->out_count; ++i) {
279 if (start->out_bb [i]->dfn)
282 start->out_bb [i]->dfn = *dfn;
283 start->out_bb [i]->df_parent = start;
284 array [*dfn] = start->out_bb [i];
285 df_visit (start->out_bb [i], dfn, array);
290 mono_reverse_branch_op (guint32 opcode)
292 static const int reverse_map [] = {
293 CEE_BNE_UN, CEE_BLT, CEE_BLE, CEE_BGT, CEE_BGE,
294 CEE_BEQ, CEE_BLT_UN, CEE_BLE_UN, CEE_BGT_UN, CEE_BGE_UN
296 static const int reverse_fmap [] = {
297 OP_FBNE_UN, OP_FBLT, OP_FBLE, OP_FBGT, OP_FBGE,
298 OP_FBEQ, OP_FBLT_UN, OP_FBLE_UN, OP_FBGT_UN, OP_FBGE_UN
300 static const int reverse_lmap [] = {
301 OP_LBNE_UN, OP_LBLT, OP_LBLE, OP_LBGT, OP_LBGE,
302 OP_LBEQ, OP_LBLT_UN, OP_LBLE_UN, OP_LBGT_UN, OP_LBGE_UN
304 static const int reverse_imap [] = {
305 OP_IBNE_UN, OP_IBLT, OP_IBLE, OP_IBGT, OP_IBGE,
306 OP_IBEQ, OP_IBLT_UN, OP_IBLE_UN, OP_IBGT_UN, OP_IBGE_UN
309 if (opcode >= CEE_BEQ && opcode <= CEE_BLT_UN) {
310 opcode = reverse_map [opcode - CEE_BEQ];
311 } else if (opcode >= OP_FBEQ && opcode <= OP_FBLT_UN) {
312 opcode = reverse_fmap [opcode - OP_FBEQ];
313 } else if (opcode >= OP_LBEQ && opcode <= OP_LBLT_UN) {
314 opcode = reverse_lmap [opcode - OP_LBEQ];
315 } else if (opcode >= OP_IBEQ && opcode <= OP_IBLT_UN) {
316 opcode = reverse_imap [opcode - OP_IBEQ];
318 g_assert_not_reached ();
324 mono_type_to_store_membase (MonoCompile *cfg, MonoType *type)
326 type = mini_get_underlying_type (type);
329 switch (type->type) {
332 return OP_STOREI1_MEMBASE_REG;
335 return OP_STOREI2_MEMBASE_REG;
338 return OP_STOREI4_MEMBASE_REG;
342 case MONO_TYPE_FNPTR:
343 return OP_STORE_MEMBASE_REG;
344 case MONO_TYPE_CLASS:
345 case MONO_TYPE_STRING:
346 case MONO_TYPE_OBJECT:
347 case MONO_TYPE_SZARRAY:
348 case MONO_TYPE_ARRAY:
349 return OP_STORE_MEMBASE_REG;
352 return OP_STOREI8_MEMBASE_REG;
354 return OP_STORER4_MEMBASE_REG;
356 return OP_STORER8_MEMBASE_REG;
357 case MONO_TYPE_VALUETYPE:
358 if (type->data.klass->enumtype) {
359 type = mono_class_enum_basetype (type->data.klass);
362 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
363 return OP_STOREX_MEMBASE;
364 return OP_STOREV_MEMBASE;
365 case MONO_TYPE_TYPEDBYREF:
366 return OP_STOREV_MEMBASE;
367 case MONO_TYPE_GENERICINST:
368 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
369 return OP_STOREX_MEMBASE;
370 type = &type->data.generic_class->container_class->byval_arg;
374 g_assert (mini_type_var_is_vt (type));
375 return OP_STOREV_MEMBASE;
377 g_error ("unknown type 0x%02x in type_to_store_membase", type->type);
383 mono_type_to_load_membase (MonoCompile *cfg, MonoType *type)
385 type = mini_get_underlying_type (type);
387 switch (type->type) {
389 return OP_LOADI1_MEMBASE;
391 return OP_LOADU1_MEMBASE;
393 return OP_LOADI2_MEMBASE;
395 return OP_LOADU2_MEMBASE;
397 return OP_LOADI4_MEMBASE;
399 return OP_LOADU4_MEMBASE;
403 case MONO_TYPE_FNPTR:
404 return OP_LOAD_MEMBASE;
405 case MONO_TYPE_CLASS:
406 case MONO_TYPE_STRING:
407 case MONO_TYPE_OBJECT:
408 case MONO_TYPE_SZARRAY:
409 case MONO_TYPE_ARRAY:
410 return OP_LOAD_MEMBASE;
413 return OP_LOADI8_MEMBASE;
415 return OP_LOADR4_MEMBASE;
417 return OP_LOADR8_MEMBASE;
418 case MONO_TYPE_VALUETYPE:
419 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
420 return OP_LOADX_MEMBASE;
421 case MONO_TYPE_TYPEDBYREF:
422 return OP_LOADV_MEMBASE;
423 case MONO_TYPE_GENERICINST:
424 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
425 return OP_LOADX_MEMBASE;
426 if (mono_type_generic_inst_is_valuetype (type))
427 return OP_LOADV_MEMBASE;
429 return OP_LOAD_MEMBASE;
433 g_assert (cfg->gshared);
434 g_assert (mini_type_var_is_vt (type));
435 return OP_LOADV_MEMBASE;
437 g_error ("unknown type 0x%02x in type_to_load_membase", type->type);
443 mini_type_to_stind (MonoCompile* cfg, MonoType *type)
445 type = mini_get_underlying_type (type);
446 if (cfg->gshared && !type->byref && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)) {
447 g_assert (mini_type_var_is_vt (type));
450 return mono_type_to_stind (type);
454 mono_op_imm_to_op (int opcode)
458 #if SIZEOF_REGISTER == 4
476 #if SIZEOF_REGISTER == 4
482 #if SIZEOF_REGISTER == 4
488 #if SIZEOF_REGISTER == 4
534 #if SIZEOF_REGISTER == 4
540 #if SIZEOF_REGISTER == 4
559 case OP_ICOMPARE_IMM:
561 case OP_LOCALLOC_IMM:
569 * mono_decompose_op_imm:
571 * Replace the OP_.._IMM INS with its non IMM variant.
574 mono_decompose_op_imm (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins)
576 int opcode2 = mono_op_imm_to_op (ins->opcode);
579 const char *spec = INS_INFO (ins->opcode);
581 if (spec [MONO_INST_SRC2] == 'l') {
582 dreg = mono_alloc_lreg (cfg);
584 /* Load the 64bit constant using decomposed ops */
585 MONO_INST_NEW (cfg, temp, OP_ICONST);
586 temp->inst_c0 = ins->inst_ls_word;
587 temp->dreg = MONO_LVREG_LS (dreg);
588 mono_bblock_insert_before_ins (bb, ins, temp);
590 MONO_INST_NEW (cfg, temp, OP_ICONST);
591 temp->inst_c0 = ins->inst_ms_word;
592 temp->dreg = MONO_LVREG_MS (dreg);
594 dreg = mono_alloc_ireg (cfg);
596 MONO_INST_NEW (cfg, temp, OP_ICONST);
597 temp->inst_c0 = ins->inst_imm;
601 mono_bblock_insert_before_ins (bb, ins, temp);
604 g_error ("mono_op_imm_to_op failed for %s\n", mono_inst_name (ins->opcode));
605 ins->opcode = opcode2;
607 if (ins->opcode == OP_LOCALLOC)
612 bb->max_vreg = MAX (bb->max_vreg, cfg->next_vreg);
616 set_vreg_to_inst (MonoCompile *cfg, int vreg, MonoInst *inst)
618 if (vreg >= cfg->vreg_to_inst_len) {
619 MonoInst **tmp = cfg->vreg_to_inst;
620 int size = cfg->vreg_to_inst_len;
622 while (vreg >= cfg->vreg_to_inst_len)
623 cfg->vreg_to_inst_len = cfg->vreg_to_inst_len ? cfg->vreg_to_inst_len * 2 : 32;
624 cfg->vreg_to_inst = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * cfg->vreg_to_inst_len);
626 memcpy (cfg->vreg_to_inst, tmp, size * sizeof (MonoInst*));
628 cfg->vreg_to_inst [vreg] = inst;
631 #define mono_type_is_long(type) (!(type)->byref && ((mono_type_get_underlying_type (type)->type == MONO_TYPE_I8) || (mono_type_get_underlying_type (type)->type == MONO_TYPE_U8)))
632 #define mono_type_is_float(type) (!(type)->byref && (((type)->type == MONO_TYPE_R8) || ((type)->type == MONO_TYPE_R4)))
635 mono_compile_create_var_for_vreg (MonoCompile *cfg, MonoType *type, int opcode, int vreg)
638 int num = cfg->num_varinfo;
641 type = mini_get_underlying_type (type);
643 if ((num + 1) >= cfg->varinfo_count) {
644 int orig_count = cfg->varinfo_count;
645 cfg->varinfo_count = cfg->varinfo_count ? (cfg->varinfo_count * 2) : 32;
646 cfg->varinfo = (MonoInst **)g_realloc (cfg->varinfo, sizeof (MonoInst*) * cfg->varinfo_count);
647 cfg->vars = (MonoMethodVar *)g_realloc (cfg->vars, sizeof (MonoMethodVar) * cfg->varinfo_count);
648 memset (&cfg->vars [orig_count], 0, (cfg->varinfo_count - orig_count) * sizeof (MonoMethodVar));
651 cfg->stat_allocate_var++;
653 MONO_INST_NEW (cfg, inst, opcode);
655 inst->inst_vtype = type;
656 inst->klass = mono_class_from_mono_type (type);
657 type_to_eval_stack_type (cfg, type, inst);
658 /* if set to 1 the variable is native */
659 inst->backend.is_pinvoke = 0;
662 if (mono_class_has_failure (inst->klass))
663 mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD);
665 if (cfg->compute_gc_maps) {
667 mono_mark_vreg_as_mp (cfg, vreg);
669 if ((MONO_TYPE_ISSTRUCT (type) && inst->klass->has_references) || mini_type_is_reference (type)) {
670 inst->flags |= MONO_INST_GC_TRACK;
671 mono_mark_vreg_as_ref (cfg, vreg);
676 cfg->varinfo [num] = inst;
678 MONO_INIT_VARINFO (&cfg->vars [num], num);
679 MONO_VARINFO (cfg, num)->vreg = vreg;
682 set_vreg_to_inst (cfg, vreg, inst);
684 #if SIZEOF_REGISTER == 4
685 if (mono_arch_is_soft_float ()) {
686 regpair = mono_type_is_long (type) || mono_type_is_float (type);
688 regpair = mono_type_is_long (type);
698 * These two cannot be allocated using create_var_for_vreg since that would
699 * put it into the cfg->varinfo array, confusing many parts of the JIT.
703 * Set flags to VOLATILE so SSA skips it.
706 if (cfg->verbose_level >= 4) {
707 printf (" Create LVAR R%d (R%d, R%d)\n", inst->dreg, MONO_LVREG_LS (inst->dreg), MONO_LVREG_MS (inst->dreg));
710 if (mono_arch_is_soft_float () && cfg->opt & MONO_OPT_SSA) {
711 if (mono_type_is_float (type))
712 inst->flags = MONO_INST_VOLATILE;
715 /* Allocate a dummy MonoInst for the first vreg */
716 MONO_INST_NEW (cfg, tree, OP_LOCAL);
717 tree->dreg = MONO_LVREG_LS (inst->dreg);
718 if (cfg->opt & MONO_OPT_SSA)
719 tree->flags = MONO_INST_VOLATILE;
721 tree->type = STACK_I4;
722 tree->inst_vtype = &mono_defaults.int32_class->byval_arg;
723 tree->klass = mono_class_from_mono_type (tree->inst_vtype);
725 set_vreg_to_inst (cfg, MONO_LVREG_LS (inst->dreg), tree);
727 /* Allocate a dummy MonoInst for the second vreg */
728 MONO_INST_NEW (cfg, tree, OP_LOCAL);
729 tree->dreg = MONO_LVREG_MS (inst->dreg);
730 if (cfg->opt & MONO_OPT_SSA)
731 tree->flags = MONO_INST_VOLATILE;
733 tree->type = STACK_I4;
734 tree->inst_vtype = &mono_defaults.int32_class->byval_arg;
735 tree->klass = mono_class_from_mono_type (tree->inst_vtype);
737 set_vreg_to_inst (cfg, MONO_LVREG_MS (inst->dreg), tree);
741 if (cfg->verbose_level > 2)
742 g_print ("created temp %d (R%d) of type %s\n", num, vreg, mono_type_get_name (type));
747 mono_compile_create_var (MonoCompile *cfg, MonoType *type, int opcode)
750 type = mini_get_underlying_type (type);
752 if (mono_type_is_long (type))
753 dreg = mono_alloc_dreg (cfg, STACK_I8);
754 else if (mono_arch_is_soft_float () && mono_type_is_float (type))
755 dreg = mono_alloc_dreg (cfg, STACK_R8);
757 /* All the others are unified */
758 dreg = mono_alloc_preg (cfg);
760 return mono_compile_create_var_for_vreg (cfg, type, opcode, dreg);
764 mini_get_int_to_float_spill_area (MonoCompile *cfg)
767 if (!cfg->iconv_raw_var) {
768 cfg->iconv_raw_var = mono_compile_create_var (cfg, &mono_defaults.int32_class->byval_arg, OP_LOCAL);
769 cfg->iconv_raw_var->flags |= MONO_INST_VOLATILE; /*FIXME, use the don't regalloc flag*/
771 return cfg->iconv_raw_var;
778 mono_mark_vreg_as_ref (MonoCompile *cfg, int vreg)
780 if (vreg >= cfg->vreg_is_ref_len) {
781 gboolean *tmp = cfg->vreg_is_ref;
782 int size = cfg->vreg_is_ref_len;
784 while (vreg >= cfg->vreg_is_ref_len)
785 cfg->vreg_is_ref_len = cfg->vreg_is_ref_len ? cfg->vreg_is_ref_len * 2 : 32;
786 cfg->vreg_is_ref = (gboolean *)mono_mempool_alloc0 (cfg->mempool, sizeof (gboolean) * cfg->vreg_is_ref_len);
788 memcpy (cfg->vreg_is_ref, tmp, size * sizeof (gboolean));
790 cfg->vreg_is_ref [vreg] = TRUE;
794 mono_mark_vreg_as_mp (MonoCompile *cfg, int vreg)
796 if (vreg >= cfg->vreg_is_mp_len) {
797 gboolean *tmp = cfg->vreg_is_mp;
798 int size = cfg->vreg_is_mp_len;
800 while (vreg >= cfg->vreg_is_mp_len)
801 cfg->vreg_is_mp_len = cfg->vreg_is_mp_len ? cfg->vreg_is_mp_len * 2 : 32;
802 cfg->vreg_is_mp = (gboolean *)mono_mempool_alloc0 (cfg->mempool, sizeof (gboolean) * cfg->vreg_is_mp_len);
804 memcpy (cfg->vreg_is_mp, tmp, size * sizeof (gboolean));
806 cfg->vreg_is_mp [vreg] = TRUE;
810 type_from_stack_type (MonoInst *ins)
813 case STACK_I4: return &mono_defaults.int32_class->byval_arg;
814 case STACK_I8: return &mono_defaults.int64_class->byval_arg;
815 case STACK_PTR: return &mono_defaults.int_class->byval_arg;
816 case STACK_R8: return &mono_defaults.double_class->byval_arg;
819 * this if used to be commented without any specific reason, but
820 * it breaks #80235 when commented
823 return &ins->klass->this_arg;
825 return &mono_defaults.object_class->this_arg;
827 /* ins->klass may not be set for ldnull.
828 * Also, if we have a boxed valuetype, we want an object lass,
829 * not the valuetype class
831 if (ins->klass && !ins->klass->valuetype)
832 return &ins->klass->byval_arg;
833 return &mono_defaults.object_class->byval_arg;
834 case STACK_VTYPE: return &ins->klass->byval_arg;
836 g_error ("stack type %d to montype not handled\n", ins->type);
842 mono_type_from_stack_type (MonoInst *ins)
844 return type_from_stack_type (ins);
848 * mono_add_ins_to_end:
850 * Same as MONO_ADD_INS, but add INST before any branches at the end of BB.
853 mono_add_ins_to_end (MonoBasicBlock *bb, MonoInst *inst)
858 MONO_ADD_INS (bb, inst);
862 switch (bb->last_ins->opcode) {
876 mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
879 if (MONO_IS_COND_BRANCH_OP (bb->last_ins)) {
880 /* Need to insert the ins before the compare */
881 if (bb->code == bb->last_ins) {
882 mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
886 if (bb->code->next == bb->last_ins) {
887 /* Only two instructions */
888 opcode = bb->code->opcode;
890 if ((opcode == OP_COMPARE) || (opcode == OP_COMPARE_IMM) || (opcode == OP_ICOMPARE) || (opcode == OP_ICOMPARE_IMM) || (opcode == OP_FCOMPARE) || (opcode == OP_LCOMPARE) || (opcode == OP_LCOMPARE_IMM) || (opcode == OP_RCOMPARE)) {
892 mono_bblock_insert_before_ins (bb, bb->code, inst);
894 mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
897 opcode = bb->last_ins->prev->opcode;
899 if ((opcode == OP_COMPARE) || (opcode == OP_COMPARE_IMM) || (opcode == OP_ICOMPARE) || (opcode == OP_ICOMPARE_IMM) || (opcode == OP_FCOMPARE) || (opcode == OP_LCOMPARE) || (opcode == OP_LCOMPARE_IMM) || (opcode == OP_RCOMPARE)) {
901 mono_bblock_insert_before_ins (bb, bb->last_ins->prev, inst);
903 mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
908 MONO_ADD_INS (bb, inst);
914 mono_create_jump_table (MonoCompile *cfg, MonoInst *label, MonoBasicBlock **bbs, int num_blocks)
916 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
917 MonoJumpInfoBBTable *table;
919 table = (MonoJumpInfoBBTable *)mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfoBBTable));
921 table->table_size = num_blocks;
923 ji->ip.label = label;
924 ji->type = MONO_PATCH_INFO_SWITCH;
925 ji->data.table = table;
926 ji->next = cfg->patch_info;
927 cfg->patch_info = ji;
930 static MonoMethodSignature *
931 mono_get_array_new_va_signature (int arity)
933 static GHashTable *sighash;
934 MonoMethodSignature *res;
939 sighash = g_hash_table_new (NULL, NULL);
941 else if ((res = (MonoMethodSignature *)g_hash_table_lookup (sighash, GINT_TO_POINTER (arity)))) {
946 res = mono_metadata_signature_alloc (mono_defaults.corlib, arity + 1);
949 if (ARCH_VARARG_ICALLS)
950 /* Only set this only some archs since not all backends can handle varargs+pinvoke */
951 res->call_convention = MONO_CALL_VARARG;
954 res->call_convention = MONO_CALL_C;
957 res->params [0] = &mono_defaults.int_class->byval_arg;
958 for (i = 0; i < arity; i++)
959 res->params [i + 1] = &mono_defaults.int_class->byval_arg;
961 res->ret = &mono_defaults.object_class->byval_arg;
963 g_hash_table_insert (sighash, GINT_TO_POINTER (arity), res);
970 mono_get_array_new_va_icall (int rank)
972 MonoMethodSignature *esig;
973 char icall_name [256];
975 MonoJitICallInfo *info;
977 /* Need to register the icall so it gets an icall wrapper */
978 sprintf (icall_name, "ves_array_new_va_%d", rank);
981 info = mono_find_jit_icall_by_name (icall_name);
983 esig = mono_get_array_new_va_signature (rank);
984 name = g_strdup (icall_name);
985 info = mono_register_jit_icall (mono_array_new_va, name, esig, FALSE);
993 mini_class_is_system_array (MonoClass *klass)
995 if (klass->parent == mono_defaults.array_class)
1002 mini_assembly_can_skip_verification (MonoDomain *domain, MonoMethod *method)
1004 MonoAssembly *assembly = method->klass->image->assembly;
1005 if (method->wrapper_type != MONO_WRAPPER_NONE && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
1007 if (assembly->in_gac || assembly->image == mono_defaults.corlib)
1009 return mono_assembly_has_skip_verification (assembly);
1013 * mini_method_verify:
1015 * Verify the method using the verfier.
1017 * Returns true if the method is invalid.
1020 mini_method_verify (MonoCompile *cfg, MonoMethod *method, gboolean fail_compile)
1023 gboolean is_fulltrust;
1025 if (method->verification_success)
1028 if (!mono_verifier_is_enabled_for_method (method))
1031 /*skip verification implies the assembly must be */
1032 is_fulltrust = mono_verifier_is_method_full_trust (method) || mini_assembly_can_skip_verification (cfg->domain, method);
1034 res = mono_method_verify_with_current_settings (method, cfg->skip_visibility, is_fulltrust);
1037 for (tmp = res; tmp; tmp = tmp->next) {
1038 MonoVerifyInfoExtended *info = (MonoVerifyInfoExtended *)tmp->data;
1039 if (info->info.status == MONO_VERIFY_ERROR) {
1041 char *method_name = mono_method_full_name (method, TRUE);
1042 cfg->exception_type = info->exception_type;
1043 cfg->exception_message = g_strdup_printf ("Error verifying %s: %s", method_name, info->info.message);
1044 g_free (method_name);
1046 mono_free_verify_list (res);
1049 if (info->info.status == MONO_VERIFY_NOT_VERIFIABLE && (!is_fulltrust || info->exception_type == MONO_EXCEPTION_METHOD_ACCESS || info->exception_type == MONO_EXCEPTION_FIELD_ACCESS)) {
1051 char *method_name = mono_method_full_name (method, TRUE);
1052 char *msg = g_strdup_printf ("Error verifying %s: %s", method_name, info->info.message);
1054 if (info->exception_type == MONO_EXCEPTION_METHOD_ACCESS)
1055 mono_error_set_generic_error (&cfg->error, "System", "MethodAccessException", "%s", msg);
1056 else if (info->exception_type == MONO_EXCEPTION_FIELD_ACCESS)
1057 mono_error_set_generic_error (&cfg->error, "System", "FieldAccessException", "%s", msg);
1058 else if (info->exception_type == MONO_EXCEPTION_UNVERIFIABLE_IL)
1059 mono_error_set_generic_error (&cfg->error, "System.Security", "VerificationException", "%s", msg);
1060 if (!mono_error_ok (&cfg->error)) {
1061 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
1064 cfg->exception_type = info->exception_type;
1065 cfg->exception_message = msg;
1067 g_free (method_name);
1069 mono_free_verify_list (res);
1073 mono_free_verify_list (res);
1075 method->verification_success = 1;
1079 /*Returns true if something went wrong*/
1081 mono_compile_is_broken (MonoCompile *cfg, MonoMethod *method, gboolean fail_compile)
1083 MonoMethod *method_definition = method;
1084 gboolean dont_verify = method->klass->image->assembly->corlib_internal;
1086 while (method_definition->is_inflated) {
1087 MonoMethodInflated *imethod = (MonoMethodInflated *) method_definition;
1088 method_definition = imethod->declaring;
1091 return !dont_verify && mini_method_verify (cfg, method_definition, fail_compile);
1095 mono_dynamic_code_hash_insert (MonoDomain *domain, MonoMethod *method, MonoJitDynamicMethodInfo *ji)
1097 if (!domain_jit_info (domain)->dynamic_code_hash)
1098 domain_jit_info (domain)->dynamic_code_hash = g_hash_table_new (NULL, NULL);
1099 g_hash_table_insert (domain_jit_info (domain)->dynamic_code_hash, method, ji);
1102 static MonoJitDynamicMethodInfo*
1103 mono_dynamic_code_hash_lookup (MonoDomain *domain, MonoMethod *method)
1105 MonoJitDynamicMethodInfo *res;
1107 if (domain_jit_info (domain)->dynamic_code_hash)
1108 res = (MonoJitDynamicMethodInfo *)g_hash_table_lookup (domain_jit_info (domain)->dynamic_code_hash, method);
1116 GList *active, *inactive;
1121 compare_by_interval_start_pos_func (gconstpointer a, gconstpointer b)
1123 MonoMethodVar *v1 = (MonoMethodVar*)a;
1124 MonoMethodVar *v2 = (MonoMethodVar*)b;
1128 else if (v1->interval->range && v2->interval->range)
1129 return v1->interval->range->from - v2->interval->range->from;
1130 else if (v1->interval->range)
1137 #define LSCAN_DEBUG(a) do { a; } while (0)
1139 #define LSCAN_DEBUG(a)
1143 mono_allocate_stack_slots2 (MonoCompile *cfg, gboolean backward, guint32 *stack_size, guint32 *stack_align)
1145 int i, slot, offset, size;
1150 GList *vars = NULL, *l, *unhandled;
1151 StackSlotInfo *scalar_stack_slots, *vtype_stack_slots, *slot_info;
1154 gboolean reuse_slot;
1156 LSCAN_DEBUG (printf ("Allocate Stack Slots 2 for %s:\n", mono_method_full_name (cfg->method, TRUE)));
1158 scalar_stack_slots = (StackSlotInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * MONO_TYPE_PINNED);
1159 vtype_stack_slots = NULL;
1162 offsets = (gint32 *)mono_mempool_alloc (cfg->mempool, sizeof (gint32) * cfg->num_varinfo);
1163 for (i = 0; i < cfg->num_varinfo; ++i)
1166 for (i = cfg->locals_start; i < cfg->num_varinfo; i++) {
1167 inst = cfg->varinfo [i];
1168 vmv = MONO_VARINFO (cfg, i);
1170 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR || inst->opcode == OP_REGOFFSET)
1173 vars = g_list_prepend (vars, vmv);
1176 vars = g_list_sort (vars, compare_by_interval_start_pos_func);
1181 for (unhandled = vars; unhandled; unhandled = unhandled->next) {
1182 MonoMethodVar *current = unhandled->data;
1184 if (current->interval->range) {
1185 g_assert (current->interval->range->from >= i);
1186 i = current->interval->range->from;
1193 for (unhandled = vars; unhandled; unhandled = unhandled->next) {
1194 MonoMethodVar *current = (MonoMethodVar *)unhandled->data;
1197 inst = cfg->varinfo [vmv->idx];
1199 t = mono_type_get_underlying_type (inst->inst_vtype);
1200 if (cfg->gsharedvt && mini_is_gsharedvt_variable_type (t))
1203 /* inst->backend.is_pinvoke indicates native sized value types, this is used by the
1204 * pinvoke wrappers when they call functions returning structures */
1205 if (inst->backend.is_pinvoke && MONO_TYPE_ISSTRUCT (t) && t->type != MONO_TYPE_TYPEDBYREF) {
1206 size = mono_class_native_size (mono_class_from_mono_type (t), &align);
1211 size = mini_type_stack_size (t, &ialign);
1214 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (t)))
1219 if (cfg->disable_reuse_stack_slots)
1222 t = mini_get_underlying_type (t);
1224 case MONO_TYPE_GENERICINST:
1225 if (!mono_type_generic_inst_is_valuetype (t)) {
1226 slot_info = &scalar_stack_slots [t->type];
1230 case MONO_TYPE_VALUETYPE:
1231 if (!vtype_stack_slots)
1232 vtype_stack_slots = (StackSlotInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * 256);
1233 for (i = 0; i < nvtypes; ++i)
1234 if (t->data.klass == vtype_stack_slots [i].vtype)
1237 slot_info = &vtype_stack_slots [i];
1239 g_assert (nvtypes < 256);
1240 vtype_stack_slots [nvtypes].vtype = t->data.klass;
1241 slot_info = &vtype_stack_slots [nvtypes];
1244 if (cfg->disable_reuse_ref_stack_slots)
1251 #if SIZEOF_VOID_P == 4
1256 if (cfg->disable_ref_noref_stack_slot_share) {
1257 slot_info = &scalar_stack_slots [MONO_TYPE_I];
1262 case MONO_TYPE_CLASS:
1263 case MONO_TYPE_OBJECT:
1264 case MONO_TYPE_ARRAY:
1265 case MONO_TYPE_SZARRAY:
1266 case MONO_TYPE_STRING:
1267 /* Share non-float stack slots of the same size */
1268 slot_info = &scalar_stack_slots [MONO_TYPE_CLASS];
1269 if (cfg->disable_reuse_ref_stack_slots)
1274 slot_info = &scalar_stack_slots [t->type];
1278 if (cfg->comp_done & MONO_COMP_LIVENESS) {
1282 //printf ("START %2d %08x %08x\n", vmv->idx, vmv->range.first_use.abs_pos, vmv->range.last_use.abs_pos);
1284 if (!current->interval->range) {
1285 if (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))
1289 inst->flags |= MONO_INST_IS_DEAD;
1294 pos = current->interval->range->from;
1296 LSCAN_DEBUG (printf ("process R%d ", inst->dreg));
1297 if (current->interval->range)
1298 LSCAN_DEBUG (mono_linterval_print (current->interval));
1299 LSCAN_DEBUG (printf ("\n"));
1301 /* Check for intervals in active which expired or inactive */
1303 /* FIXME: Optimize this */
1306 for (l = slot_info->active; l != NULL; l = l->next) {
1307 MonoMethodVar *v = (MonoMethodVar*)l->data;
1309 if (v->interval->last_range->to < pos) {
1310 slot_info->active = g_list_delete_link (slot_info->active, l);
1311 slot_info->slots = g_slist_prepend_mempool (cfg->mempool, slot_info->slots, GINT_TO_POINTER (offsets [v->idx]));
1312 LSCAN_DEBUG (printf ("Interval R%d has expired, adding 0x%x to slots\n", cfg->varinfo [v->idx]->dreg, offsets [v->idx]));
1316 else if (!mono_linterval_covers (v->interval, pos)) {
1317 slot_info->inactive = g_list_append (slot_info->inactive, v);
1318 slot_info->active = g_list_delete_link (slot_info->active, l);
1319 LSCAN_DEBUG (printf ("Interval R%d became inactive\n", cfg->varinfo [v->idx]->dreg));
1326 /* Check for intervals in inactive which expired or active */
1328 /* FIXME: Optimize this */
1331 for (l = slot_info->inactive; l != NULL; l = l->next) {
1332 MonoMethodVar *v = (MonoMethodVar*)l->data;
1334 if (v->interval->last_range->to < pos) {
1335 slot_info->inactive = g_list_delete_link (slot_info->inactive, l);
1336 // FIXME: Enabling this seems to cause impossible to debug crashes
1337 //slot_info->slots = g_slist_prepend_mempool (cfg->mempool, slot_info->slots, GINT_TO_POINTER (offsets [v->idx]));
1338 LSCAN_DEBUG (printf ("Interval R%d has expired, adding 0x%x to slots\n", cfg->varinfo [v->idx]->dreg, offsets [v->idx]));
1342 else if (mono_linterval_covers (v->interval, pos)) {
1343 slot_info->active = g_list_append (slot_info->active, v);
1344 slot_info->inactive = g_list_delete_link (slot_info->inactive, l);
1345 LSCAN_DEBUG (printf ("\tInterval R%d became active\n", cfg->varinfo [v->idx]->dreg));
1353 * This also handles the case when the variable is used in an
1354 * exception region, as liveness info is not computed there.
1357 * FIXME: All valuetypes are marked as INDIRECT because of LDADDR
1360 if (! (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
1361 if (slot_info->slots) {
1362 slot = GPOINTER_TO_INT (slot_info->slots->data);
1364 slot_info->slots = slot_info->slots->next;
1367 /* FIXME: We might want to consider the inactive intervals as well if slot_info->slots is empty */
1369 slot_info->active = mono_varlist_insert_sorted (cfg, slot_info->active, vmv, TRUE);
1375 static int count = 0;
1378 if (count == atoi (g_getenv ("COUNT3")))
1379 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
1380 if (count > atoi (g_getenv ("COUNT3")))
1383 mono_print_ins (inst);
1388 LSCAN_DEBUG (printf ("R%d %s -> 0x%x\n", inst->dreg, mono_type_full_name (t), slot));
1390 if (inst->flags & MONO_INST_LMF) {
1391 size = sizeof (MonoLMF);
1392 align = sizeof (mgreg_t);
1399 if (slot == 0xffffff) {
1401 * Allways allocate valuetypes to sizeof (gpointer) to allow more
1402 * efficient copying (and to work around the fact that OP_MEMCPY
1403 * and OP_MEMSET ignores alignment).
1405 if (MONO_TYPE_ISSTRUCT (t)) {
1406 align = MAX (align, sizeof (gpointer));
1407 align = MAX (align, mono_class_min_align (mono_class_from_mono_type (t)));
1412 offset += align - 1;
1413 offset &= ~(align - 1);
1417 offset += align - 1;
1418 offset &= ~(align - 1);
1423 if (*stack_align == 0)
1424 *stack_align = align;
1427 offsets [vmv->idx] = slot;
1430 for (i = 0; i < MONO_TYPE_PINNED; ++i) {
1431 if (scalar_stack_slots [i].active)
1432 g_list_free (scalar_stack_slots [i].active);
1434 for (i = 0; i < nvtypes; ++i) {
1435 if (vtype_stack_slots [i].active)
1436 g_list_free (vtype_stack_slots [i].active);
1439 cfg->stat_locals_stack_size += offset;
1441 *stack_size = offset;
1446 * mono_allocate_stack_slots:
1448 * Allocate stack slots for all non register allocated variables using a
1449 * linear scan algorithm.
1450 * Returns: an array of stack offsets.
1451 * STACK_SIZE is set to the amount of stack space needed.
1452 * STACK_ALIGN is set to the alignment needed by the locals area.
1455 mono_allocate_stack_slots (MonoCompile *cfg, gboolean backward, guint32 *stack_size, guint32 *stack_align)
1457 int i, slot, offset, size;
1462 GList *vars = NULL, *l;
1463 StackSlotInfo *scalar_stack_slots, *vtype_stack_slots, *slot_info;
1466 gboolean reuse_slot;
1468 if ((cfg->num_varinfo > 0) && MONO_VARINFO (cfg, 0)->interval)
1469 return mono_allocate_stack_slots2 (cfg, backward, stack_size, stack_align);
1471 scalar_stack_slots = (StackSlotInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * MONO_TYPE_PINNED);
1472 vtype_stack_slots = NULL;
1475 offsets = (gint32 *)mono_mempool_alloc (cfg->mempool, sizeof (gint32) * cfg->num_varinfo);
1476 for (i = 0; i < cfg->num_varinfo; ++i)
1479 for (i = cfg->locals_start; i < cfg->num_varinfo; i++) {
1480 inst = cfg->varinfo [i];
1481 vmv = MONO_VARINFO (cfg, i);
1483 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR || inst->opcode == OP_REGOFFSET)
1486 vars = g_list_prepend (vars, vmv);
1489 vars = mono_varlist_sort (cfg, vars, 0);
1491 *stack_align = sizeof(mgreg_t);
1492 for (l = vars; l; l = l->next) {
1493 vmv = (MonoMethodVar *)l->data;
1494 inst = cfg->varinfo [vmv->idx];
1496 t = mono_type_get_underlying_type (inst->inst_vtype);
1497 if (cfg->gsharedvt && mini_is_gsharedvt_variable_type (t))
1500 /* inst->backend.is_pinvoke indicates native sized value types, this is used by the
1501 * pinvoke wrappers when they call functions returning structures */
1502 if (inst->backend.is_pinvoke && MONO_TYPE_ISSTRUCT (t) && t->type != MONO_TYPE_TYPEDBYREF) {
1503 size = mono_class_native_size (mono_class_from_mono_type (t), &align);
1507 size = mini_type_stack_size (t, &ialign);
1510 if (mono_class_has_failure (mono_class_from_mono_type (t)))
1511 mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD);
1513 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (t)))
1518 if (cfg->disable_reuse_stack_slots)
1521 t = mini_get_underlying_type (t);
1523 case MONO_TYPE_GENERICINST:
1524 if (!mono_type_generic_inst_is_valuetype (t)) {
1525 slot_info = &scalar_stack_slots [t->type];
1529 case MONO_TYPE_VALUETYPE:
1530 if (!vtype_stack_slots)
1531 vtype_stack_slots = (StackSlotInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * 256);
1532 for (i = 0; i < nvtypes; ++i)
1533 if (t->data.klass == vtype_stack_slots [i].vtype)
1536 slot_info = &vtype_stack_slots [i];
1538 g_assert (nvtypes < 256);
1539 vtype_stack_slots [nvtypes].vtype = t->data.klass;
1540 slot_info = &vtype_stack_slots [nvtypes];
1543 if (cfg->disable_reuse_ref_stack_slots)
1550 #if SIZEOF_VOID_P == 4
1555 if (cfg->disable_ref_noref_stack_slot_share) {
1556 slot_info = &scalar_stack_slots [MONO_TYPE_I];
1561 case MONO_TYPE_CLASS:
1562 case MONO_TYPE_OBJECT:
1563 case MONO_TYPE_ARRAY:
1564 case MONO_TYPE_SZARRAY:
1565 case MONO_TYPE_STRING:
1566 /* Share non-float stack slots of the same size */
1567 slot_info = &scalar_stack_slots [MONO_TYPE_CLASS];
1568 if (cfg->disable_reuse_ref_stack_slots)
1572 case MONO_TYPE_MVAR:
1573 slot_info = &scalar_stack_slots [t->type];
1576 slot_info = &scalar_stack_slots [t->type];
1581 if (cfg->comp_done & MONO_COMP_LIVENESS) {
1582 //printf ("START %2d %08x %08x\n", vmv->idx, vmv->range.first_use.abs_pos, vmv->range.last_use.abs_pos);
1584 /* expire old intervals in active */
1585 while (slot_info->active) {
1586 MonoMethodVar *amv = (MonoMethodVar *)slot_info->active->data;
1588 if (amv->range.last_use.abs_pos > vmv->range.first_use.abs_pos)
1591 //printf ("EXPIR %2d %08x %08x C%d R%d\n", amv->idx, amv->range.first_use.abs_pos, amv->range.last_use.abs_pos, amv->spill_costs, amv->reg);
1593 slot_info->active = g_list_delete_link (slot_info->active, slot_info->active);
1594 slot_info->slots = g_slist_prepend_mempool (cfg->mempool, slot_info->slots, GINT_TO_POINTER (offsets [amv->idx]));
1598 * This also handles the case when the variable is used in an
1599 * exception region, as liveness info is not computed there.
1602 * FIXME: All valuetypes are marked as INDIRECT because of LDADDR
1605 if (! (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
1606 if (slot_info->slots) {
1607 slot = GPOINTER_TO_INT (slot_info->slots->data);
1609 slot_info->slots = slot_info->slots->next;
1612 slot_info->active = mono_varlist_insert_sorted (cfg, slot_info->active, vmv, TRUE);
1617 static int count = 0;
1621 if (count == atoi (g_getenv ("COUNT")))
1622 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
1623 if (count > atoi (g_getenv ("COUNT")))
1626 mono_print_ins (inst);
1631 if (inst->flags & MONO_INST_LMF) {
1633 * This variable represents a MonoLMF structure, which has no corresponding
1634 * CLR type, so hard-code its size/alignment.
1636 size = sizeof (MonoLMF);
1637 align = sizeof (mgreg_t);
1644 if (slot == 0xffffff) {
1646 * Allways allocate valuetypes to sizeof (gpointer) to allow more
1647 * efficient copying (and to work around the fact that OP_MEMCPY
1648 * and OP_MEMSET ignores alignment).
1650 if (MONO_TYPE_ISSTRUCT (t)) {
1651 align = MAX (align, sizeof (gpointer));
1652 align = MAX (align, mono_class_min_align (mono_class_from_mono_type (t)));
1654 * Align the size too so the code generated for passing vtypes in
1655 * registers doesn't overwrite random locals.
1657 size = (size + (align - 1)) & ~(align -1);
1662 offset += align - 1;
1663 offset &= ~(align - 1);
1667 offset += align - 1;
1668 offset &= ~(align - 1);
1673 *stack_align = MAX (*stack_align, align);
1676 offsets [vmv->idx] = slot;
1679 for (i = 0; i < MONO_TYPE_PINNED; ++i) {
1680 if (scalar_stack_slots [i].active)
1681 g_list_free (scalar_stack_slots [i].active);
1683 for (i = 0; i < nvtypes; ++i) {
1684 if (vtype_stack_slots [i].active)
1685 g_list_free (vtype_stack_slots [i].active);
1688 cfg->stat_locals_stack_size += offset;
1690 *stack_size = offset;
1694 #define EMUL_HIT_SHIFT 3
1695 #define EMUL_HIT_MASK ((1 << EMUL_HIT_SHIFT) - 1)
1696 /* small hit bitmap cache */
1697 static mono_byte emul_opcode_hit_cache [(OP_LAST>>EMUL_HIT_SHIFT) + 1] = {0};
1698 static short emul_opcode_num = 0;
1699 static short emul_opcode_alloced = 0;
1700 static short *emul_opcode_opcodes;
1701 static MonoJitICallInfo **emul_opcode_map;
1704 mono_find_jit_opcode_emulation (int opcode)
1706 g_assert (opcode >= 0 && opcode <= OP_LAST);
1707 if (emul_opcode_hit_cache [opcode >> (EMUL_HIT_SHIFT + 3)] & (1 << (opcode & EMUL_HIT_MASK))) {
1709 for (i = 0; i < emul_opcode_num; ++i) {
1710 if (emul_opcode_opcodes [i] == opcode)
1711 return emul_opcode_map [i];
1718 mini_register_opcode_emulation (int opcode, const char *name, const char *sigstr, gpointer func, const char *symbol, gboolean no_throw)
1720 MonoJitICallInfo *info;
1721 MonoMethodSignature *sig = mono_create_icall_signature (sigstr);
1723 g_assert (!sig->hasthis);
1724 g_assert (sig->param_count < 3);
1726 /* Opcode emulation functions are assumed to don't call mono_raise_exception () */
1727 info = mono_register_jit_icall_full (func, name, sig, no_throw, TRUE, symbol);
1729 if (emul_opcode_num >= emul_opcode_alloced) {
1730 int incr = emul_opcode_alloced? emul_opcode_alloced/2: 16;
1731 emul_opcode_alloced += incr;
1732 emul_opcode_map = (MonoJitICallInfo **)g_realloc (emul_opcode_map, sizeof (emul_opcode_map [0]) * emul_opcode_alloced);
1733 emul_opcode_opcodes = (short *)g_realloc (emul_opcode_opcodes, sizeof (emul_opcode_opcodes [0]) * emul_opcode_alloced);
1735 emul_opcode_map [emul_opcode_num] = info;
1736 emul_opcode_opcodes [emul_opcode_num] = opcode;
1738 emul_opcode_hit_cache [opcode >> (EMUL_HIT_SHIFT + 3)] |= (1 << (opcode & EMUL_HIT_MASK));
1742 print_dfn (MonoCompile *cfg)
1750 char *method_name = mono_method_full_name (cfg->method, TRUE);
1751 g_print ("IR code for method %s\n", method_name);
1752 g_free (method_name);
1755 for (i = 0; i < cfg->num_bblocks; ++i) {
1756 bb = cfg->bblocks [i];
1757 /*if (bb->cil_code) {
1758 char* code1, *code2;
1759 code1 = mono_disasm_code_one (NULL, cfg->method, bb->cil_code, NULL);
1760 if (bb->last_ins->cil_code)
1761 code2 = mono_disasm_code_one (NULL, cfg->method, bb->last_ins->cil_code, NULL);
1763 code2 = g_strdup ("");
1765 code1 [strlen (code1) - 1] = 0;
1766 code = g_strdup_printf ("%s -> %s", code1, code2);
1770 code = g_strdup ("\n");
1771 g_print ("\nBB%d (%d) (len: %d): %s", bb->block_num, i, bb->cil_length, code);
1772 MONO_BB_FOR_EACH_INS (bb, c) {
1773 mono_print_ins_index (-1, c);
1776 g_print ("\tprev:");
1777 for (j = 0; j < bb->in_count; ++j) {
1778 g_print (" BB%d", bb->in_bb [j]->block_num);
1780 g_print ("\t\tsucc:");
1781 for (j = 0; j < bb->out_count; ++j) {
1782 g_print (" BB%d", bb->out_bb [j]->block_num);
1784 g_print ("\n\tidom: BB%d\n", bb->idom? bb->idom->block_num: -1);
1787 g_assert (mono_bitset_test_fast (bb->dominators, bb->idom->dfn));
1790 mono_blockset_print (cfg, bb->dominators, "\tdominators", bb->idom? bb->idom->dfn: -1);
1792 mono_blockset_print (cfg, bb->dfrontier, "\tdfrontier", -1);
1800 mono_bblock_add_inst (MonoBasicBlock *bb, MonoInst *inst)
1802 MONO_ADD_INS (bb, inst);
1806 mono_bblock_insert_after_ins (MonoBasicBlock *bb, MonoInst *ins, MonoInst *ins_to_insert)
1810 bb->code = ins_to_insert;
1812 /* Link with next */
1813 ins_to_insert->next = ins;
1815 ins->prev = ins_to_insert;
1817 if (bb->last_ins == NULL)
1818 bb->last_ins = ins_to_insert;
1820 /* Link with next */
1821 ins_to_insert->next = ins->next;
1823 ins->next->prev = ins_to_insert;
1825 /* Link with previous */
1826 ins->next = ins_to_insert;
1827 ins_to_insert->prev = ins;
1829 if (bb->last_ins == ins)
1830 bb->last_ins = ins_to_insert;
1835 mono_bblock_insert_before_ins (MonoBasicBlock *bb, MonoInst *ins, MonoInst *ins_to_insert)
1840 ins->prev = ins_to_insert;
1841 bb->code = ins_to_insert;
1842 ins_to_insert->next = ins;
1843 if (bb->last_ins == NULL)
1844 bb->last_ins = ins_to_insert;
1846 /* Link with previous */
1848 ins->prev->next = ins_to_insert;
1849 ins_to_insert->prev = ins->prev;
1851 /* Link with next */
1852 ins->prev = ins_to_insert;
1853 ins_to_insert->next = ins;
1855 if (bb->code == ins)
1856 bb->code = ins_to_insert;
1861 * mono_verify_bblock:
1863 * Verify that the next and prev pointers are consistent inside the instructions in BB.
1866 mono_verify_bblock (MonoBasicBlock *bb)
1868 MonoInst *ins, *prev;
1871 for (ins = bb->code; ins; ins = ins->next) {
1872 g_assert (ins->prev == prev);
1876 g_assert (!bb->last_ins->next);
1882 * Perform consistency checks on the JIT data structures and the IR
1885 mono_verify_cfg (MonoCompile *cfg)
1889 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
1890 mono_verify_bblock (bb);
1893 // This will free many fields in cfg to save
1894 // memory. Note that this must be safe to call
1895 // multiple times. It must be idempotent.
1897 mono_empty_compile (MonoCompile *cfg)
1899 mono_free_loop_info (cfg);
1901 // These live in the mempool, and so must be freed
1903 for (GSList *l = cfg->headers_to_free; l; l = l->next) {
1904 mono_metadata_free_mh ((MonoMethodHeader *)l->data);
1906 cfg->headers_to_free = NULL;
1909 //mono_mempool_stats (cfg->mempool);
1910 mono_mempool_destroy (cfg->mempool);
1911 cfg->mempool = NULL;
1914 g_free (cfg->varinfo);
1915 cfg->varinfo = NULL;
1921 mono_regstate_free (cfg->rs);
1927 mono_destroy_compile (MonoCompile *cfg)
1929 mono_empty_compile (cfg);
1932 mono_metadata_free_mh (cfg->header);
1935 g_hash_table_destroy (cfg->spvars);
1937 g_hash_table_destroy (cfg->exvars);
1939 g_list_free (cfg->ldstr_list);
1941 if (cfg->token_info_hash)
1942 g_hash_table_destroy (cfg->token_info_hash);
1944 if (cfg->abs_patches)
1945 g_hash_table_destroy (cfg->abs_patches);
1947 mono_debug_free_method (cfg);
1949 g_free (cfg->varinfo);
1951 g_free (cfg->exception_message);
1956 mono_create_tls_get_offset (MonoCompile *cfg, int offset)
1960 if (!cfg->backend->have_tls_get)
1966 MONO_INST_NEW (cfg, ins, OP_TLS_GET);
1967 ins->dreg = mono_alloc_preg (cfg);
1968 ins->inst_offset = offset;
1973 mini_tls_get_supported (MonoCompile *cfg, MonoTlsKey key)
1975 if (!cfg->backend->have_tls_get)
1978 if (cfg->compile_aot)
1979 return cfg->backend->have_tls_get_reg;
1981 return mini_get_tls_offset (key) != -1;
1985 mono_create_tls_get (MonoCompile *cfg, MonoTlsKey key)
1987 if (!cfg->backend->have_tls_get)
1990 #ifdef HAVE_KW_THREAD
1992 * MONO_THREAD_VAR_OFFSET definitions don't work when loading mono as a
1993 * dynamic library. This means that we need to be conservative and don't
1994 * aot code that contains these tls chunks.
1996 * FIXME Remove HAVE_KW_THREAD altogether and use only pthread since it
1997 * simplifies the code alot.
2000 cfg->disable_aot = TRUE;
2003 * TLS offsets might be different at AOT time, so load them from a GOT slot and
2004 * use a different opcode.
2006 if (cfg->compile_aot) {
2007 if (cfg->backend->have_tls_get_reg) {
2010 EMIT_NEW_TLS_OFFSETCONST (cfg, c, key);
2011 MONO_INST_NEW (cfg, ins, OP_TLS_GET_REG);
2012 ins->dreg = mono_alloc_preg (cfg);
2013 ins->sreg1 = c->dreg;
2020 return mono_create_tls_get_offset (cfg, mini_get_tls_offset (key));
2024 mono_get_jit_tls_intrinsic (MonoCompile *cfg)
2026 return mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
2030 mono_get_domain_intrinsic (MonoCompile* cfg)
2032 return mono_create_tls_get (cfg, TLS_KEY_DOMAIN);
2036 mono_get_thread_intrinsic (MonoCompile* cfg)
2038 return mono_create_tls_get (cfg, TLS_KEY_THREAD);
2042 mono_get_lmf_intrinsic (MonoCompile* cfg)
2044 return mono_create_tls_get (cfg, TLS_KEY_LMF);
2048 mono_get_lmf_addr_intrinsic (MonoCompile* cfg)
2050 return mono_create_tls_get (cfg, TLS_KEY_LMF_ADDR);
2054 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
2056 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfo));
2060 ji->data.target = target;
2061 ji->next = cfg->patch_info;
2063 cfg->patch_info = ji;
2067 mono_add_patch_info_rel (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target, int relocation)
2069 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfo));
2073 ji->relocation = relocation;
2074 ji->data.target = target;
2075 ji->next = cfg->patch_info;
2077 cfg->patch_info = ji;
2081 mono_remove_patch_info (MonoCompile *cfg, int ip)
2083 MonoJumpInfo **ji = &cfg->patch_info;
2086 if ((*ji)->ip.i == ip)
2089 ji = &((*ji)->next);
2094 mono_add_seq_point (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins, int native_offset)
2096 ins->inst_offset = native_offset;
2097 g_ptr_array_add (cfg->seq_points, ins);
2099 bb->seq_points = g_slist_prepend_mempool (cfg->mempool, bb->seq_points, ins);
2100 bb->last_seq_point = ins;
2105 mono_add_var_location (MonoCompile *cfg, MonoInst *var, gboolean is_reg, int reg, int offset, int from, int to)
2107 MonoDwarfLocListEntry *entry = (MonoDwarfLocListEntry *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoDwarfLocListEntry));
2110 g_assert (offset == 0);
2112 entry->is_reg = is_reg;
2114 entry->offset = offset;
2118 if (var == cfg->args [0])
2119 cfg->this_loclist = g_slist_append_mempool (cfg->mempool, cfg->this_loclist, entry);
2120 else if (var == cfg->rgctx_var)
2121 cfg->rgctx_loclist = g_slist_append_mempool (cfg->mempool, cfg->rgctx_loclist, entry);
2125 mono_compile_create_vars (MonoCompile *cfg)
2127 MonoMethodSignature *sig;
2128 MonoMethodHeader *header;
2131 header = cfg->header;
2133 sig = mono_method_signature (cfg->method);
2135 if (!MONO_TYPE_IS_VOID (sig->ret)) {
2136 cfg->ret = mono_compile_create_var (cfg, sig->ret, OP_ARG);
2137 /* Inhibit optimizations */
2138 cfg->ret->flags |= MONO_INST_VOLATILE;
2140 if (cfg->verbose_level > 2)
2141 g_print ("creating vars\n");
2143 cfg->args = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, (sig->param_count + sig->hasthis) * sizeof (MonoInst*));
2146 cfg->args [0] = mono_compile_create_var (cfg, &cfg->method->klass->this_arg, OP_ARG);
2148 for (i = 0; i < sig->param_count; ++i) {
2149 cfg->args [i + sig->hasthis] = mono_compile_create_var (cfg, sig->params [i], OP_ARG);
2152 if (cfg->verbose_level > 2) {
2154 printf ("\treturn : ");
2155 mono_print_ins (cfg->ret);
2159 printf ("\tthis: ");
2160 mono_print_ins (cfg->args [0]);
2163 for (i = 0; i < sig->param_count; ++i) {
2164 printf ("\targ [%d]: ", i);
2165 mono_print_ins (cfg->args [i + sig->hasthis]);
2169 cfg->locals_start = cfg->num_varinfo;
2170 cfg->locals = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, header->num_locals * sizeof (MonoInst*));
2172 if (cfg->verbose_level > 2)
2173 g_print ("creating locals\n");
2175 for (i = 0; i < header->num_locals; ++i)
2176 cfg->locals [i] = mono_compile_create_var (cfg, header->locals [i], OP_LOCAL);
2178 if (cfg->verbose_level > 2)
2179 g_print ("locals done\n");
2182 if (COMPILE_LLVM (cfg))
2183 mono_llvm_create_vars (cfg);
2185 mono_arch_create_vars (cfg);
2187 mono_arch_create_vars (cfg);
2190 if (cfg->method->save_lmf && cfg->create_lmf_var) {
2191 MonoInst *lmf_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
2192 lmf_var->flags |= MONO_INST_VOLATILE;
2193 lmf_var->flags |= MONO_INST_LMF;
2194 cfg->lmf_var = lmf_var;
2199 mono_print_code (MonoCompile *cfg, const char* msg)
2203 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
2204 mono_print_bb (bb, msg);
2208 mono_postprocess_patches (MonoCompile *cfg)
2210 MonoJumpInfo *patch_info;
2213 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2214 switch (patch_info->type) {
2215 case MONO_PATCH_INFO_ABS: {
2216 MonoJitICallInfo *info = mono_find_jit_icall_by_addr (patch_info->data.target);
2219 * Change patches of type MONO_PATCH_INFO_ABS into patches describing the
2223 //printf ("TEST %s %p\n", info->name, patch_info->data.target);
2224 /* for these array methods we currently register the same function pointer
2225 * since it's a vararg function. But this means that mono_find_jit_icall_by_addr ()
2226 * will return the incorrect one depending on the order they are registered.
2227 * See tests/test-arr.cs
2229 if (strstr (info->name, "ves_array_new_va_") == NULL && strstr (info->name, "ves_array_element_address_") == NULL) {
2230 patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
2231 patch_info->data.name = info->name;
2235 if (patch_info->type == MONO_PATCH_INFO_ABS) {
2236 if (cfg->abs_patches) {
2237 MonoJumpInfo *abs_ji = (MonoJumpInfo *)g_hash_table_lookup (cfg->abs_patches, patch_info->data.target);
2239 patch_info->type = abs_ji->type;
2240 patch_info->data.target = abs_ji->data.target;
2247 case MONO_PATCH_INFO_SWITCH: {
2249 #if defined(__native_client__) && defined(__native_client_codegen__)
2250 /* This memory will leak. */
2251 /* TODO: can we free this when */
2252 /* making the final jump table? */
2253 table = g_malloc0 (sizeof(gpointer) * patch_info->data.table->table_size);
2255 if (cfg->method->dynamic) {
2256 table = (void **)mono_code_manager_reserve (cfg->dynamic_info->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
2258 table = (void **)mono_domain_code_reserve (cfg->domain, sizeof (gpointer) * patch_info->data.table->table_size);
2262 for (i = 0; i < patch_info->data.table->table_size; i++) {
2263 /* Might be NULL if the switch is eliminated */
2264 if (patch_info->data.table->table [i]) {
2265 g_assert (patch_info->data.table->table [i]->native_offset);
2266 table [i] = GINT_TO_POINTER (patch_info->data.table->table [i]->native_offset);
2271 patch_info->data.table->table = (MonoBasicBlock**)table;
2274 case MONO_PATCH_INFO_METHOD_JUMP: {
2275 MonoJumpList *jlist;
2276 MonoDomain *domain = cfg->domain;
2277 unsigned char *ip = cfg->native_code + patch_info->ip.i;
2279 mono_domain_lock (domain);
2280 jlist = (MonoJumpList *)g_hash_table_lookup (domain_jit_info (domain)->jump_target_hash, patch_info->data.method);
2282 jlist = (MonoJumpList *)mono_domain_alloc0 (domain, sizeof (MonoJumpList));
2283 g_hash_table_insert (domain_jit_info (domain)->jump_target_hash, patch_info->data.method, jlist);
2285 jlist->list = g_slist_prepend (jlist->list, ip);
2286 mono_domain_unlock (domain);
2297 mono_codegen (MonoCompile *cfg)
2300 int max_epilog_size;
2302 MonoDomain *code_domain;
2303 guint unwindlen = 0;
2305 if (mono_using_xdebug)
2307 * Recent gdb versions have trouble processing symbol files containing
2308 * overlapping address ranges, so allocate all code from the code manager
2309 * of the root domain. (#666152).
2311 code_domain = mono_get_root_domain ();
2313 code_domain = cfg->domain;
2315 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2316 cfg->spill_count = 0;
2317 /* we reuse dfn here */
2318 /* bb->dfn = bb_count++; */
2320 mono_arch_lowering_pass (cfg, bb);
2322 if (cfg->opt & MONO_OPT_PEEPHOLE)
2323 mono_arch_peephole_pass_1 (cfg, bb);
2325 mono_local_regalloc (cfg, bb);
2327 if (cfg->opt & MONO_OPT_PEEPHOLE)
2328 mono_arch_peephole_pass_2 (cfg, bb);
2330 if (cfg->gen_seq_points && !cfg->gen_sdb_seq_points)
2331 mono_bb_deduplicate_op_il_seq_points (cfg, bb);
2334 if (cfg->prof_options & MONO_PROFILE_COVERAGE)
2335 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, cfg->num_bblocks);
2337 code = mono_arch_emit_prolog (cfg);
2339 cfg->code_len = code - cfg->native_code;
2340 cfg->prolog_end = cfg->code_len;
2341 cfg->cfa_reg = cfg->cur_cfa_reg;
2342 cfg->cfa_offset = cfg->cur_cfa_offset;
2344 mono_debug_open_method (cfg);
2346 /* emit code all basic blocks */
2347 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2348 bb->native_offset = cfg->code_len;
2349 bb->real_native_offset = cfg->code_len;
2350 //if ((bb == cfg->bb_entry) || !(bb->region == -1 && !bb->dfn))
2351 mono_arch_output_basic_block (cfg, bb);
2352 bb->native_length = cfg->code_len - bb->native_offset;
2354 if (bb == cfg->bb_exit) {
2355 cfg->epilog_begin = cfg->code_len;
2356 mono_arch_emit_epilog (cfg);
2357 cfg->epilog_end = cfg->code_len;
2361 mono_arch_emit_exceptions (cfg);
2363 max_epilog_size = 0;
2365 /* we always allocate code in cfg->domain->code_mp to increase locality */
2366 cfg->code_size = cfg->code_len + max_epilog_size;
2368 /* fixme: align to MONO_ARCH_CODE_ALIGNMENT */
2370 #ifdef MONO_ARCH_HAVE_UNWIND_TABLE
2371 unwindlen = mono_arch_unwindinfo_get_size (cfg->arch.unwindinfo);
2374 if (cfg->method->dynamic) {
2375 /* Allocate the code into a separate memory pool so it can be freed */
2376 cfg->dynamic_info = g_new0 (MonoJitDynamicMethodInfo, 1);
2377 cfg->dynamic_info->code_mp = mono_code_manager_new_dynamic ();
2378 mono_domain_lock (cfg->domain);
2379 mono_dynamic_code_hash_insert (cfg->domain, cfg->method, cfg->dynamic_info);
2380 mono_domain_unlock (cfg->domain);
2382 if (mono_using_xdebug)
2383 /* See the comment for cfg->code_domain */
2384 code = (guint8 *)mono_domain_code_reserve (code_domain, cfg->code_size + cfg->thunk_area + unwindlen);
2386 code = (guint8 *)mono_code_manager_reserve (cfg->dynamic_info->code_mp, cfg->code_size + cfg->thunk_area + unwindlen);
2388 code = (guint8 *)mono_domain_code_reserve (code_domain, cfg->code_size + cfg->thunk_area + unwindlen);
2391 if (cfg->thunk_area) {
2392 cfg->thunks_offset = cfg->code_size + unwindlen;
2393 cfg->thunks = code + cfg->thunks_offset;
2394 memset (cfg->thunks, 0, cfg->thunk_area);
2398 memcpy (code, cfg->native_code, cfg->code_len);
2399 g_free (cfg->native_code);
2400 cfg->native_code = code;
2401 code = cfg->native_code + cfg->code_len;
2403 /* g_assert (((int)cfg->native_code & (MONO_ARCH_CODE_ALIGNMENT - 1)) == 0); */
2404 mono_postprocess_patches (cfg);
2406 #ifdef VALGRIND_JIT_REGISTER_MAP
2407 if (valgrind_register){
2408 char* nm = mono_method_full_name (cfg->method, TRUE);
2409 VALGRIND_JIT_REGISTER_MAP (nm, cfg->native_code, cfg->native_code + cfg->code_len);
2414 if (cfg->verbose_level > 0) {
2415 char* nm = mono_method_get_full_name (cfg->method);
2416 char *opt_descr = mono_opt_descr (cfg->opt);
2417 g_print ("Method %s emitted at %p to %p (code length %d) [%s] with opts %s\n",
2419 cfg->native_code, cfg->native_code + cfg->code_len, cfg->code_len, cfg->domain->friendly_name,
2426 gboolean is_generic = FALSE;
2428 if (cfg->method->is_inflated || mono_method_get_generic_container (cfg->method) ||
2429 mono_class_is_gtd (cfg->method->klass) || mono_class_is_ginst (cfg->method->klass)) {
2434 g_assert (is_generic);
2437 #ifdef MONO_ARCH_HAVE_SAVE_UNWIND_INFO
2438 mono_arch_save_unwind_info (cfg);
2441 #ifdef MONO_ARCH_HAVE_PATCH_CODE_NEW
2446 for (ji = cfg->patch_info; ji; ji = ji->next) {
2447 if (cfg->compile_aot) {
2449 case MONO_PATCH_INFO_BB:
2450 case MONO_PATCH_INFO_LABEL:
2453 /* No need to patch these */
2458 if (ji->type == MONO_PATCH_INFO_NONE)
2461 target = mono_resolve_patch_target (cfg->method, cfg->domain, cfg->native_code, ji, cfg->run_cctors, &cfg->error);
2462 if (!mono_error_ok (&cfg->error)) {
2463 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
2466 mono_arch_patch_code_new (cfg, cfg->domain, cfg->native_code, ji, target);
2470 mono_arch_patch_code (cfg, cfg->method, cfg->domain, cfg->native_code, cfg->patch_info, cfg->run_cctors, &cfg->error);
2471 if (!is_ok (&cfg->error)) {
2472 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
2477 if (cfg->method->dynamic) {
2478 if (mono_using_xdebug)
2479 mono_domain_code_commit (code_domain, cfg->native_code, cfg->code_size, cfg->code_len);
2481 mono_code_manager_commit (cfg->dynamic_info->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
2483 mono_domain_code_commit (code_domain, cfg->native_code, cfg->code_size, cfg->code_len);
2485 #if defined(__native_client_codegen__) && defined(__native_client__)
2486 cfg->native_code = code_dest;
2488 mono_profiler_code_buffer_new (cfg->native_code, cfg->code_len, MONO_PROFILER_CODE_BUFFER_METHOD, cfg->method);
2490 mono_arch_flush_icache (cfg->native_code, cfg->code_len);
2492 mono_debug_close_method (cfg);
2494 #ifdef MONO_ARCH_HAVE_UNWIND_TABLE
2495 mono_arch_unwindinfo_install_unwind_info (&cfg->arch.unwindinfo, cfg->native_code, cfg->code_len);
2500 compute_reachable (MonoBasicBlock *bb)
2504 if (!(bb->flags & BB_VISITED)) {
2505 bb->flags |= BB_VISITED;
2506 for (i = 0; i < bb->out_count; ++i)
2507 compute_reachable (bb->out_bb [i]);
2511 static void mono_bb_ordering (MonoCompile *cfg)
2514 /* Depth-first ordering on basic blocks */
2515 cfg->bblocks = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
2517 cfg->max_block_num = cfg->num_bblocks;
2519 df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
2520 if (cfg->num_bblocks != dfn + 1) {
2523 cfg->num_bblocks = dfn + 1;
2525 /* remove unreachable code, because the code in them may be
2526 * inconsistent (access to dead variables for example) */
2527 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
2528 bb->flags &= ~BB_VISITED;
2529 compute_reachable (cfg->bb_entry);
2530 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
2531 if (bb->flags & BB_EXCEPTION_HANDLER)
2532 compute_reachable (bb);
2533 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2534 if (!(bb->flags & BB_VISITED)) {
2535 if (cfg->verbose_level > 1)
2536 g_print ("found unreachable code in BB%d\n", bb->block_num);
2537 bb->code = bb->last_ins = NULL;
2538 while (bb->out_count)
2539 mono_unlink_bblock (cfg, bb, bb->out_bb [0]);
2542 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
2543 bb->flags &= ~BB_VISITED;
2548 mono_handle_out_of_line_bblock (MonoCompile *cfg)
2551 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2552 if (bb->next_bb && bb->next_bb->out_of_line && bb->last_ins && !MONO_IS_BRANCH_OP (bb->last_ins)) {
2554 MONO_INST_NEW (cfg, ins, OP_BR);
2555 MONO_ADD_INS (bb, ins);
2556 ins->inst_target_bb = bb->next_bb;
2562 create_jit_info (MonoCompile *cfg, MonoMethod *method_to_compile)
2565 MonoMethodHeader *header;
2567 MonoJitInfoFlags flags = JIT_INFO_NONE;
2568 int num_clauses, num_holes = 0;
2569 guint32 stack_size = 0;
2571 g_assert (method_to_compile == cfg->method);
2572 header = cfg->header;
2575 flags = (MonoJitInfoFlags)(flags | JIT_INFO_HAS_GENERIC_JIT_INFO);
2577 if (cfg->arch_eh_jit_info) {
2578 MonoJitArgumentInfo *arg_info;
2579 MonoMethodSignature *sig = mono_method_signature (cfg->method_to_register);
2582 * This cannot be computed during stack walking, as
2583 * mono_arch_get_argument_info () is not signal safe.
2585 arg_info = g_newa (MonoJitArgumentInfo, sig->param_count + 1);
2586 stack_size = mono_arch_get_argument_info (sig, sig->param_count, arg_info);
2589 flags = (MonoJitInfoFlags)(flags | JIT_INFO_HAS_ARCH_EH_INFO);
2592 if (cfg->has_unwind_info_for_epilog && !(flags & JIT_INFO_HAS_ARCH_EH_INFO))
2593 flags = (MonoJitInfoFlags)(flags | JIT_INFO_HAS_ARCH_EH_INFO);
2595 if (cfg->thunk_area)
2596 flags = (MonoJitInfoFlags)(flags | JIT_INFO_HAS_THUNK_INFO);
2598 if (cfg->try_block_holes) {
2599 for (tmp = cfg->try_block_holes; tmp; tmp = tmp->next) {
2600 TryBlockHole *hole = (TryBlockHole *)tmp->data;
2601 MonoExceptionClause *ec = hole->clause;
2602 int hole_end = hole->basic_block->native_offset + hole->basic_block->native_length;
2603 MonoBasicBlock *clause_last_bb = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
2604 g_assert (clause_last_bb);
2606 /* Holes at the end of a try region can be represented by simply reducing the size of the block itself.*/
2607 if (clause_last_bb->native_offset != hole_end)
2611 flags = (MonoJitInfoFlags)(flags | JIT_INFO_HAS_TRY_BLOCK_HOLES);
2612 if (G_UNLIKELY (cfg->verbose_level >= 4))
2613 printf ("Number of try block holes %d\n", num_holes);
2616 if (COMPILE_LLVM (cfg))
2617 num_clauses = cfg->llvm_ex_info_len;
2619 num_clauses = header->num_clauses;
2621 if (cfg->method->dynamic)
2622 jinfo = (MonoJitInfo *)g_malloc0 (mono_jit_info_size (flags, num_clauses, num_holes));
2624 jinfo = (MonoJitInfo *)mono_domain_alloc0 (cfg->domain, mono_jit_info_size (flags, num_clauses, num_holes));
2625 mono_jit_info_init (jinfo, cfg->method_to_register, cfg->native_code, cfg->code_len, flags, num_clauses, num_holes);
2626 jinfo->domain_neutral = (cfg->opt & MONO_OPT_SHARED) != 0;
2628 if (COMPILE_LLVM (cfg))
2629 jinfo->from_llvm = TRUE;
2633 MonoGenericJitInfo *gi;
2634 GSList *loclist = NULL;
2636 gi = mono_jit_info_get_generic_jit_info (jinfo);
2639 if (cfg->method->dynamic)
2640 gi->generic_sharing_context = g_new0 (MonoGenericSharingContext, 1);
2642 gi->generic_sharing_context = (MonoGenericSharingContext *)mono_domain_alloc0 (cfg->domain, sizeof (MonoGenericSharingContext));
2643 mini_init_gsctx (cfg->method->dynamic ? NULL : cfg->domain, NULL, cfg->gsctx_context, gi->generic_sharing_context);
2645 if ((method_to_compile->flags & METHOD_ATTRIBUTE_STATIC) ||
2646 mini_method_get_context (method_to_compile)->method_inst ||
2647 method_to_compile->klass->valuetype) {
2648 g_assert (cfg->rgctx_var);
2653 if ((method_to_compile->flags & METHOD_ATTRIBUTE_STATIC) ||
2654 mini_method_get_context (method_to_compile)->method_inst ||
2655 method_to_compile->klass->valuetype) {
2656 inst = cfg->rgctx_var;
2657 if (!COMPILE_LLVM (cfg))
2658 g_assert (inst->opcode == OP_REGOFFSET);
2659 loclist = cfg->rgctx_loclist;
2661 inst = cfg->args [0];
2662 loclist = cfg->this_loclist;
2666 /* Needed to handle async exceptions */
2670 gi->nlocs = g_slist_length (loclist);
2671 if (cfg->method->dynamic)
2672 gi->locations = (MonoDwarfLocListEntry *)g_malloc0 (gi->nlocs * sizeof (MonoDwarfLocListEntry));
2674 gi->locations = (MonoDwarfLocListEntry *)mono_domain_alloc0 (cfg->domain, gi->nlocs * sizeof (MonoDwarfLocListEntry));
2676 for (l = loclist; l; l = l->next) {
2677 memcpy (&(gi->locations [i]), l->data, sizeof (MonoDwarfLocListEntry));
2682 if (COMPILE_LLVM (cfg)) {
2683 g_assert (cfg->llvm_this_reg != -1);
2684 gi->this_in_reg = 0;
2685 gi->this_reg = cfg->llvm_this_reg;
2686 gi->this_offset = cfg->llvm_this_offset;
2687 } else if (inst->opcode == OP_REGVAR) {
2688 gi->this_in_reg = 1;
2689 gi->this_reg = inst->dreg;
2691 g_assert (inst->opcode == OP_REGOFFSET);
2693 g_assert (inst->inst_basereg == X86_EBP);
2694 #elif defined(TARGET_AMD64)
2695 g_assert (inst->inst_basereg == X86_EBP || inst->inst_basereg == X86_ESP);
2697 g_assert (inst->inst_offset >= G_MININT32 && inst->inst_offset <= G_MAXINT32);
2699 gi->this_in_reg = 0;
2700 gi->this_reg = inst->inst_basereg;
2701 gi->this_offset = inst->inst_offset;
2706 MonoTryBlockHoleTableJitInfo *table;
2709 table = mono_jit_info_get_try_block_hole_table_info (jinfo);
2710 table->num_holes = (guint16)num_holes;
2712 for (tmp = cfg->try_block_holes; tmp; tmp = tmp->next) {
2713 guint32 start_bb_offset;
2714 MonoTryBlockHoleJitInfo *hole;
2715 TryBlockHole *hole_data = (TryBlockHole *)tmp->data;
2716 MonoExceptionClause *ec = hole_data->clause;
2717 int hole_end = hole_data->basic_block->native_offset + hole_data->basic_block->native_length;
2718 MonoBasicBlock *clause_last_bb = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
2719 g_assert (clause_last_bb);
2721 /* Holes at the end of a try region can be represented by simply reducing the size of the block itself.*/
2722 if (clause_last_bb->native_offset == hole_end)
2725 start_bb_offset = hole_data->start_offset - hole_data->basic_block->native_offset;
2726 hole = &table->holes [i++];
2727 hole->clause = hole_data->clause - &header->clauses [0];
2728 hole->offset = (guint32)hole_data->start_offset;
2729 hole->length = (guint16)(hole_data->basic_block->native_length - start_bb_offset);
2731 if (G_UNLIKELY (cfg->verbose_level >= 4))
2732 printf ("\tTry block hole at eh clause %d offset %x length %x\n", hole->clause, hole->offset, hole->length);
2734 g_assert (i == num_holes);
2737 if (jinfo->has_arch_eh_info) {
2738 MonoArchEHJitInfo *info;
2740 info = mono_jit_info_get_arch_eh_info (jinfo);
2742 info->stack_size = stack_size;
2745 if (cfg->thunk_area) {
2746 MonoThunkJitInfo *info;
2748 info = mono_jit_info_get_thunk_info (jinfo);
2749 info->thunks_offset = cfg->thunks_offset;
2750 info->thunks_size = cfg->thunk_area;
2753 if (COMPILE_LLVM (cfg)) {
2755 memcpy (&jinfo->clauses [0], &cfg->llvm_ex_info [0], num_clauses * sizeof (MonoJitExceptionInfo));
2756 } else if (header->num_clauses) {
2759 for (i = 0; i < header->num_clauses; i++) {
2760 MonoExceptionClause *ec = &header->clauses [i];
2761 MonoJitExceptionInfo *ei = &jinfo->clauses [i];
2762 MonoBasicBlock *tblock;
2763 MonoInst *exvar, *spvar;
2765 ei->flags = ec->flags;
2767 if (G_UNLIKELY (cfg->verbose_level >= 4))
2768 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);
2771 * The spvars are needed by mono_arch_install_handler_block_guard ().
2773 if (ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY) {
2776 region = ((i + 1) << 8) | MONO_REGION_FINALLY | ec->flags;
2777 spvar = mono_find_spvar_for_region (cfg, region);
2779 ei->exvar_offset = spvar->inst_offset;
2781 exvar = mono_find_exvar_for_offset (cfg, ec->handler_offset);
2782 ei->exvar_offset = exvar ? exvar->inst_offset : 0;
2785 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
2786 tblock = cfg->cil_offset_to_bb [ec->data.filter_offset];
2788 ei->data.filter = cfg->native_code + tblock->native_offset;
2790 ei->data.catch_class = ec->data.catch_class;
2793 tblock = cfg->cil_offset_to_bb [ec->try_offset];
2795 g_assert (tblock->native_offset);
2796 ei->try_start = cfg->native_code + tblock->native_offset;
2797 if (tblock->extend_try_block) {
2799 * Extend the try block backwards to include parts of the previous call
2802 ei->try_start = (guint8*)ei->try_start - cfg->backend->monitor_enter_adjustment;
2804 if (ec->try_offset + ec->try_len < header->code_size)
2805 tblock = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
2807 tblock = cfg->bb_exit;
2808 if (G_UNLIKELY (cfg->verbose_level >= 4))
2809 printf ("looking for end of try [%d, %d] -> %p (code size %d)\n", ec->try_offset, ec->try_len, tblock, header->code_size);
2811 if (!tblock->native_offset) {
2813 for (j = ec->try_offset + ec->try_len, end = ec->try_offset; j >= end; --j) {
2814 MonoBasicBlock *bb = cfg->cil_offset_to_bb [j];
2815 if (bb && bb->native_offset) {
2821 ei->try_end = cfg->native_code + tblock->native_offset;
2822 g_assert (tblock->native_offset);
2823 tblock = cfg->cil_offset_to_bb [ec->handler_offset];
2825 ei->handler_start = cfg->native_code + tblock->native_offset;
2827 for (tmp = cfg->try_block_holes; tmp; tmp = tmp->next) {
2828 TryBlockHole *hole = (TryBlockHole *)tmp->data;
2829 gpointer hole_end = cfg->native_code + (hole->basic_block->native_offset + hole->basic_block->native_length);
2830 if (hole->clause == ec && hole_end == ei->try_end) {
2831 if (G_UNLIKELY (cfg->verbose_level >= 4))
2832 printf ("\tShortening try block %d from %x to %x\n", i, (int)((guint8*)ei->try_end - cfg->native_code), hole->start_offset);
2834 ei->try_end = cfg->native_code + hole->start_offset;
2839 if (ec->flags == MONO_EXCEPTION_CLAUSE_FINALLY) {
2841 if (ec->handler_offset + ec->handler_len < header->code_size) {
2842 tblock = cfg->cil_offset_to_bb [ec->handler_offset + ec->handler_len];
2843 if (tblock->native_offset) {
2844 end_offset = tblock->native_offset;
2848 for (j = ec->handler_offset + ec->handler_len, end = ec->handler_offset; j >= end; --j) {
2849 MonoBasicBlock *bb = cfg->cil_offset_to_bb [j];
2850 if (bb && bb->native_offset) {
2855 end_offset = tblock->native_offset + tblock->native_length;
2858 end_offset = cfg->epilog_begin;
2860 ei->data.handler_end = cfg->native_code + end_offset;
2865 if (G_UNLIKELY (cfg->verbose_level >= 4)) {
2867 for (i = 0; i < jinfo->num_clauses; i++) {
2868 MonoJitExceptionInfo *ei = &jinfo->clauses [i];
2869 int start = (guint8*)ei->try_start - cfg->native_code;
2870 int end = (guint8*)ei->try_end - cfg->native_code;
2871 int handler = (guint8*)ei->handler_start - cfg->native_code;
2872 int handler_end = (guint8*)ei->data.handler_end - cfg->native_code;
2874 printf ("JitInfo EH clause %d flags %x try %x-%x handler %x-%x\n", i, ei->flags, start, end, handler, handler_end);
2878 if (cfg->encoded_unwind_ops) {
2879 /* Generated by LLVM */
2880 jinfo->unwind_info = mono_cache_unwind_info (cfg->encoded_unwind_ops, cfg->encoded_unwind_ops_len);
2881 g_free (cfg->encoded_unwind_ops);
2882 } else if (cfg->unwind_ops) {
2884 guint8 *unwind_info = mono_unwind_ops_encode (cfg->unwind_ops, &info_len);
2885 guint32 unwind_desc;
2887 unwind_desc = mono_cache_unwind_info (unwind_info, info_len);
2889 if (cfg->has_unwind_info_for_epilog) {
2890 MonoArchEHJitInfo *info;
2892 info = mono_jit_info_get_arch_eh_info (jinfo);
2894 info->epilog_size = cfg->code_len - cfg->epilog_begin;
2896 jinfo->unwind_info = unwind_desc;
2897 g_free (unwind_info);
2899 jinfo->unwind_info = cfg->used_int_regs;
2905 /* Return whenever METHOD is a gsharedvt method */
2907 is_gsharedvt_method (MonoMethod *method)
2909 MonoGenericContext *context;
2910 MonoGenericInst *inst;
2913 if (!method->is_inflated)
2915 context = mono_method_get_context (method);
2916 inst = context->class_inst;
2918 for (i = 0; i < inst->type_argc; ++i)
2919 if (mini_is_gsharedvt_gparam (inst->type_argv [i]))
2922 inst = context->method_inst;
2924 for (i = 0; i < inst->type_argc; ++i)
2925 if (mini_is_gsharedvt_gparam (inst->type_argv [i]))
2932 is_open_method (MonoMethod *method)
2934 MonoGenericContext *context;
2936 if (!method->is_inflated)
2938 context = mono_method_get_context (method);
2939 if (context->class_inst && context->class_inst->is_open)
2941 if (context->method_inst && context->method_inst->is_open)
2946 static void mono_insert_nop_in_empty_bb (MonoCompile *cfg)
2949 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2953 MONO_INST_NEW (cfg, nop, OP_NOP);
2954 MONO_ADD_INS (bb, nop);
2958 mono_create_gc_safepoint (MonoCompile *cfg, MonoBasicBlock *bblock)
2960 MonoInst *poll_addr, *ins;
2962 if (cfg->disable_gc_safe_points)
2965 if (cfg->verbose_level > 1)
2966 printf ("ADDING SAFE POINT TO BB %d\n", bblock->block_num);
2968 #if defined(__native_client_codegen__)
2969 NEW_AOTCONST (cfg, poll_addr, MONO_PATCH_INFO_GC_SAFE_POINT_FLAG, (gpointer)&__nacl_thread_suspension_needed);
2971 g_assert (mono_threads_is_coop_enabled ());
2972 NEW_AOTCONST (cfg, poll_addr, MONO_PATCH_INFO_GC_SAFE_POINT_FLAG, (gpointer)&mono_polling_required);
2975 MONO_INST_NEW (cfg, ins, OP_GC_SAFE_POINT);
2976 ins->sreg1 = poll_addr->dreg;
2978 if (bblock->flags & BB_EXCEPTION_HANDLER) {
2979 MonoInst *eh_op = bblock->code;
2981 if (eh_op && eh_op->opcode != OP_START_HANDLER && eh_op->opcode != OP_GET_EX_OBJ) {
2984 MonoInst *next_eh_op = eh_op ? eh_op->next : NULL;
2985 // skip all EH relateds ops
2986 while (next_eh_op && (next_eh_op->opcode == OP_START_HANDLER || next_eh_op->opcode == OP_GET_EX_OBJ)) {
2988 next_eh_op = eh_op->next;
2992 mono_bblock_insert_after_ins (bblock, eh_op, poll_addr);
2993 mono_bblock_insert_after_ins (bblock, poll_addr, ins);
2994 } else if (bblock == cfg->bb_entry) {
2995 mono_bblock_insert_after_ins (bblock, bblock->last_ins, poll_addr);
2996 mono_bblock_insert_after_ins (bblock, poll_addr, ins);
2999 mono_bblock_insert_before_ins (bblock, NULL, poll_addr);
3000 mono_bblock_insert_after_ins (bblock, poll_addr, ins);
3005 This code inserts safepoints into managed code at important code paths.
3008 -the first basic block
3009 -landing BB for exception handlers
3014 mono_insert_safepoints (MonoCompile *cfg)
3018 #if !defined(__native_client_codegen__)
3019 if (!mono_threads_is_coop_enabled ())
3023 if (cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3024 WrapperInfo *info = mono_marshal_get_wrapper_info (cfg->method);
3025 #if defined(__native_client__) || defined(__native_client_codegen__)
3026 gpointer poll_func = &mono_nacl_gc;
3028 g_assert (mono_threads_is_coop_enabled ());
3029 gpointer poll_func = &mono_threads_state_poll;
3032 if (info && info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER && info->d.icall.func == poll_func) {
3033 if (cfg->verbose_level > 1)
3034 printf ("SKIPPING SAFEPOINTS for the polling function icall\n");
3039 if (cfg->method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
3040 if (cfg->verbose_level > 1)
3041 printf ("SKIPPING SAFEPOINTS for native-to-managed wrappers.\n");
3045 if (cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3046 WrapperInfo *info = mono_marshal_get_wrapper_info (cfg->method);
3048 if (info && info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER &&
3049 (info->d.icall.func == mono_thread_interruption_checkpoint ||
3050 info->d.icall.func == mono_threads_exit_gc_safe_region_unbalanced)) {
3051 /* These wrappers are called from the wrapper for the polling function, leading to potential stack overflow */
3052 if (cfg->verbose_level > 1)
3053 printf ("SKIPPING SAFEPOINTS for wrapper %s\n", cfg->method->name);
3058 if (cfg->verbose_level > 1)
3059 printf ("INSERTING SAFEPOINTS\n");
3060 if (cfg->verbose_level > 2)
3061 mono_print_code (cfg, "BEFORE SAFEPOINTS");
3063 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3064 if (bb->loop_body_start || bb == cfg->bb_entry || bb->flags & BB_EXCEPTION_HANDLER)
3065 mono_create_gc_safepoint (cfg, bb);
3068 if (cfg->verbose_level > 2)
3069 mono_print_code (cfg, "AFTER SAFEPOINTS");
3075 mono_insert_branches_between_bblocks (MonoCompile *cfg)
3079 /* Add branches between non-consecutive bblocks */
3080 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3081 if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins) &&
3082 bb->last_ins->inst_false_bb && bb->next_bb != bb->last_ins->inst_false_bb) {
3083 /* we are careful when inverting, since bugs like #59580
3084 * could show up when dealing with NaNs.
3086 if (MONO_IS_COND_BRANCH_NOFP(bb->last_ins) && bb->next_bb == bb->last_ins->inst_true_bb) {
3087 MonoBasicBlock *tmp = bb->last_ins->inst_true_bb;
3088 bb->last_ins->inst_true_bb = bb->last_ins->inst_false_bb;
3089 bb->last_ins->inst_false_bb = tmp;
3091 bb->last_ins->opcode = mono_reverse_branch_op (bb->last_ins->opcode);
3093 MonoInst *inst = (MonoInst *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
3094 inst->opcode = OP_BR;
3095 inst->inst_target_bb = bb->last_ins->inst_false_bb;
3096 mono_bblock_add_inst (bb, inst);
3101 if (cfg->verbose_level >= 4) {
3102 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3103 MonoInst *tree = bb->code;
3104 g_print ("DUMP BLOCK %d:\n", bb->block_num);
3107 for (; tree; tree = tree->next) {
3108 mono_print_ins_index (-1, tree);
3114 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3115 bb->max_vreg = cfg->next_vreg;
3120 init_backend (MonoBackend *backend)
3122 #ifdef MONO_ARCH_NEED_GOT_VAR
3123 backend->need_got_var = 1;
3125 #ifdef MONO_ARCH_HAVE_CARD_TABLE_WBARRIER
3126 backend->have_card_table_wb = 1;
3128 #ifdef MONO_ARCH_HAVE_OP_GENERIC_CLASS_INIT
3129 backend->have_op_generic_class_init = 1;
3131 #ifdef MONO_ARCH_EMULATE_MUL_DIV
3132 backend->emulate_mul_div = 1;
3134 #ifdef MONO_ARCH_EMULATE_DIV
3135 backend->emulate_div = 1;
3137 #if !defined(MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS)
3138 backend->emulate_long_shift_opts = 1;
3140 #ifdef MONO_ARCH_HAVE_OBJC_GET_SELECTOR
3141 backend->have_objc_get_selector = 1;
3143 #ifdef MONO_ARCH_HAVE_GENERALIZED_IMT_TRAMPOLINE
3144 backend->have_generalized_imt_trampoline = 1;
3146 #ifdef MONO_ARCH_GSHARED_SUPPORTED
3147 backend->gshared_supported = 1;
3149 if (MONO_ARCH_HAVE_TLS_GET)
3150 backend->have_tls_get = 1;
3151 #ifdef MONO_ARCH_HAVE_TLS_GET_REG
3152 backend->have_tls_get_reg = 1;
3154 if (MONO_ARCH_USE_FPSTACK)
3155 backend->use_fpstack = 1;
3156 #ifdef MONO_ARCH_HAVE_LIVERANGE_OPS
3157 backend->have_liverange_ops = 1;
3159 #ifdef MONO_ARCH_HAVE_OP_TAIL_CALL
3160 backend->have_op_tail_call = 1;
3162 #ifndef MONO_ARCH_MONITOR_ENTER_ADJUSTMENT
3163 backend->monitor_enter_adjustment = 1;
3165 backend->monitor_enter_adjustment = MONO_ARCH_MONITOR_ENTER_ADJUSTMENT;
3167 #if defined(__mono_ilp32__)
3170 #ifdef MONO_ARCH_HAVE_DUMMY_INIT
3171 backend->have_dummy_init = 1;
3173 #ifdef MONO_ARCH_NEED_DIV_CHECK
3174 backend->need_div_check = 1;
3176 #ifdef NO_UNALIGNED_ACCESS
3177 backend->no_unaligned_access = 1;
3179 #ifdef MONO_ARCH_DYN_CALL_PARAM_AREA
3180 backend->dyn_call_param_area = MONO_ARCH_DYN_CALL_PARAM_AREA;
3182 #ifdef MONO_ARCH_NO_DIV_WITH_MUL
3183 backend->disable_div_with_mul = 1;
3188 * mini_method_compile:
3189 * @method: the method to compile
3190 * @opts: the optimization flags to use
3191 * @domain: the domain where the method will be compiled in
3192 * @flags: compilation flags
3193 * @parts: debug flag
3195 * Returns: a MonoCompile* pointer. Caller must check the exception_type
3196 * field in the returned struct to see if compilation succeded.
3199 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFlags flags, int parts, int aot_method_index)
3201 MonoMethodHeader *header;
3202 MonoMethodSignature *sig;
3205 int i, code_size_ratio;
3206 gboolean try_generic_shared, try_llvm = FALSE;
3207 MonoMethod *method_to_compile, *method_to_register;
3208 gboolean method_is_gshared = FALSE;
3209 gboolean run_cctors = (flags & JIT_FLAG_RUN_CCTORS) ? 1 : 0;
3210 gboolean compile_aot = (flags & JIT_FLAG_AOT) ? 1 : 0;
3211 gboolean full_aot = (flags & JIT_FLAG_FULL_AOT) ? 1 : 0;
3212 gboolean disable_direct_icalls = (flags & JIT_FLAG_NO_DIRECT_ICALLS) ? 1 : 0;
3213 gboolean gsharedvt_method = FALSE;
3215 gboolean llvm = (flags & JIT_FLAG_LLVM) ? 1 : 0;
3217 static gboolean verbose_method_inited;
3218 static const char *verbose_method_name;
3220 InterlockedIncrement (&mono_jit_stats.methods_compiled);
3221 if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)
3222 mono_profiler_method_jit (method);
3223 if (MONO_METHOD_COMPILE_BEGIN_ENABLED ())
3224 MONO_PROBE_METHOD_COMPILE_BEGIN (method);
3226 gsharedvt_method = is_gsharedvt_method (method);
3229 * In AOT mode, method can be the following:
3230 * - a gsharedvt method.
3231 * - a method inflated with type parameters. This is for ref/partial sharing.
3232 * - a method inflated with concrete types.
3235 if (is_open_method (method)) {
3236 try_generic_shared = TRUE;
3237 method_is_gshared = TRUE;
3239 try_generic_shared = FALSE;
3241 g_assert (opts & MONO_OPT_GSHARED);
3243 try_generic_shared = mono_class_generic_sharing_enabled (method->klass) &&
3244 (opts & MONO_OPT_GSHARED) && mono_method_is_generic_sharable (method, FALSE);
3245 if (mini_is_gsharedvt_sharable_method (method)) {
3247 if (!mono_debug_count ())
3248 try_generic_shared = FALSE;
3254 if (try_generic_shared && !mono_debug_count ())
3255 try_generic_shared = FALSE;
3258 if (opts & MONO_OPT_GSHARED) {
3259 if (try_generic_shared)
3260 mono_stats.generics_sharable_methods++;
3261 else if (mono_method_is_generic_impl (method))
3262 mono_stats.generics_unsharable_methods++;
3266 try_llvm = mono_use_llvm || llvm;
3270 if (method_is_gshared) {
3271 method_to_compile = method;
3273 if (try_generic_shared) {
3274 method_to_compile = mini_get_shared_method (method);
3275 g_assert (method_to_compile);
3277 method_to_compile = method;
3281 cfg = g_new0 (MonoCompile, 1);
3282 cfg->method = method_to_compile;
3283 cfg->mempool = mono_mempool_new ();
3285 cfg->prof_options = mono_profiler_get_events ();
3286 cfg->run_cctors = run_cctors;
3287 cfg->domain = domain;
3288 cfg->verbose_level = mini_verbose;
3289 cfg->compile_aot = compile_aot;
3290 cfg->full_aot = full_aot;
3291 cfg->disable_omit_fp = debug_options.disable_omit_fp;
3292 cfg->skip_visibility = method->skip_visibility;
3293 cfg->orig_method = method;
3294 cfg->gen_seq_points = !debug_options.no_seq_points_compact_data || debug_options.gen_sdb_seq_points;
3295 cfg->gen_sdb_seq_points = debug_options.gen_sdb_seq_points;
3296 cfg->llvm_only = (flags & JIT_FLAG_LLVM_ONLY) != 0;
3297 cfg->backend = current_backend;
3299 #ifdef PLATFORM_ANDROID
3300 if (cfg->method->wrapper_type != MONO_WRAPPER_NONE) {
3301 /* FIXME: Why is this needed */
3302 cfg->gen_seq_points = FALSE;
3303 cfg->gen_sdb_seq_points = FALSE;
3306 if (cfg->method->wrapper_type == MONO_WRAPPER_ALLOC) {
3307 /* We can't have seq points inside gc critical regions */
3308 cfg->gen_seq_points = FALSE;
3309 cfg->gen_sdb_seq_points = FALSE;
3311 /* coop / nacl requires loop detection to happen */
3312 #if defined(__native_client_codegen__)
3313 cfg->opt |= MONO_OPT_LOOP;
3315 if (mono_threads_is_coop_enabled ())
3316 cfg->opt |= MONO_OPT_LOOP;
3318 cfg->explicit_null_checks = debug_options.explicit_null_checks || (flags & JIT_FLAG_EXPLICIT_NULL_CHECKS);
3319 cfg->soft_breakpoints = debug_options.soft_breakpoints;
3320 cfg->check_pinvoke_callconv = debug_options.check_pinvoke_callconv;
3321 cfg->disable_direct_icalls = disable_direct_icalls;
3322 cfg->direct_pinvoke = (flags & JIT_FLAG_DIRECT_PINVOKE) != 0;
3323 if (try_generic_shared)
3324 cfg->gshared = TRUE;
3325 cfg->compile_llvm = try_llvm;
3326 cfg->token_info_hash = g_hash_table_new (NULL, NULL);
3327 if (cfg->compile_aot)
3328 cfg->method_index = aot_method_index;
3331 if (!mono_debug_count ())
3332 cfg->opt &= ~MONO_OPT_FLOAT32;
3335 cfg->opt &= ~MONO_OPT_SIMD;
3336 cfg->r4fp = (cfg->opt & MONO_OPT_FLOAT32) ? 1 : 0;
3337 cfg->r4_stack_type = cfg->r4fp ? STACK_R4 : STACK_R8;
3339 if (cfg->gen_seq_points)
3340 cfg->seq_points = g_ptr_array_new ();
3341 mono_error_init (&cfg->error);
3343 if (cfg->compile_aot && !try_generic_shared && (method->is_generic || mono_class_is_gtd (method->klass) || method_is_gshared)) {
3344 cfg->exception_type = MONO_EXCEPTION_GENERIC_SHARING_FAILED;
3348 if (cfg->gshared && (gsharedvt_method || mini_is_gsharedvt_sharable_method (method))) {
3349 MonoMethodInflated *inflated;
3350 MonoGenericContext *context;
3352 if (gsharedvt_method) {
3353 g_assert (method->is_inflated);
3354 inflated = (MonoMethodInflated*)method;
3355 context = &inflated->context;
3357 /* We are compiling a gsharedvt method directly */
3358 g_assert (compile_aot);
3360 g_assert (method_to_compile->is_inflated);
3361 inflated = (MonoMethodInflated*)method_to_compile;
3362 context = &inflated->context;
3365 mini_init_gsctx (NULL, cfg->mempool, context, &cfg->gsctx);
3366 cfg->gsctx_context = context;
3368 cfg->gsharedvt = TRUE;
3369 if (!cfg->llvm_only) {
3370 cfg->disable_llvm = TRUE;
3371 cfg->exception_message = g_strdup ("gsharedvt");
3376 method_to_register = method_to_compile;
3378 g_assert (method == method_to_compile);
3379 method_to_register = method;
3381 cfg->method_to_register = method_to_register;
3383 mono_error_init (&err);
3384 sig = mono_method_signature_checked (cfg->method, &err);
3386 cfg->exception_type = MONO_EXCEPTION_TYPE_LOAD;
3387 cfg->exception_message = g_strdup (mono_error_get_message (&err));
3388 mono_error_cleanup (&err);
3389 if (MONO_METHOD_COMPILE_END_ENABLED ())
3390 MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
3394 header = cfg->header = mono_method_get_header_checked (cfg->method, &cfg->error);
3396 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
3397 if (MONO_METHOD_COMPILE_END_ENABLED ())
3398 MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
3404 static gboolean inited;
3410 * Check for methods which cannot be compiled by LLVM early, to avoid
3411 * the extra compilation pass.
3413 if (COMPILE_LLVM (cfg)) {
3414 mono_llvm_check_method_supported (cfg);
3415 if (cfg->disable_llvm) {
3416 if (cfg->verbose_level >= (cfg->llvm_only ? 0 : 1)) {
3417 //nm = mono_method_full_name (cfg->method, TRUE);
3418 printf ("LLVM failed for '%s': %s\n", method->name, cfg->exception_message);
3421 if (cfg->llvm_only) {
3422 g_free (cfg->exception_message);
3423 cfg->disable_aot = TRUE;
3426 mono_destroy_compile (cfg);
3428 goto restart_compile;
3434 /* The debugger has no liveness information, so avoid sharing registers/stack slots */
3435 if (debug_options.mdb_optimizations) {
3436 cfg->disable_reuse_registers = TRUE;
3437 cfg->disable_reuse_stack_slots = TRUE;
3439 * This decreases the change the debugger will read registers/stack slots which are
3440 * not yet initialized.
3442 cfg->disable_initlocals_opt = TRUE;
3444 cfg->extend_live_ranges = TRUE;
3446 /* The debugger needs all locals to be on the stack or in a global register */
3447 cfg->disable_vreg_to_lvreg = TRUE;
3449 /* Don't remove unused variables when running inside the debugger since the user
3450 * may still want to view them. */
3451 cfg->disable_deadce_vars = TRUE;
3453 cfg->opt &= ~MONO_OPT_DEADCE;
3454 cfg->opt &= ~MONO_OPT_INLINE;
3455 cfg->opt &= ~MONO_OPT_COPYPROP;
3456 cfg->opt &= ~MONO_OPT_CONSPROP;
3458 /* This is needed for the soft debugger, which doesn't like code after the epilog */
3459 cfg->disable_out_of_line_bblocks = TRUE;
3462 if (mono_using_xdebug) {
3464 * Make each variable use its own register/stack slot and extend
3465 * their liveness to cover the whole method, making them displayable
3466 * in gdb even after they are dead.
3468 cfg->disable_reuse_registers = TRUE;
3469 cfg->disable_reuse_stack_slots = TRUE;
3470 cfg->extend_live_ranges = TRUE;
3471 cfg->compute_precise_live_ranges = TRUE;
3474 mini_gc_init_cfg (cfg);
3476 if (method->wrapper_type == MONO_WRAPPER_UNKNOWN) {
3477 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3479 /* These wrappers are using linkonce linkage, so they can't access GOT slots */
3480 if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG))) {
3481 cfg->disable_gc_safe_points = TRUE;
3482 /* This is safe, these wrappers only store to the stack */
3483 cfg->gen_write_barriers = FALSE;
3487 if (COMPILE_LLVM (cfg)) {
3488 cfg->opt |= MONO_OPT_ABCREM;
3491 if (!verbose_method_inited) {
3492 verbose_method_name = g_getenv ("MONO_VERBOSE_METHOD");
3493 verbose_method_inited = TRUE;
3495 if (verbose_method_name) {
3496 const char *name = verbose_method_name;
3498 if ((strchr (name, '.') > name) || strchr (name, ':')) {
3499 MonoMethodDesc *desc;
3501 desc = mono_method_desc_new (name, TRUE);
3502 if (mono_method_desc_full_match (desc, cfg->method)) {
3503 cfg->verbose_level = 4;
3505 mono_method_desc_free (desc);
3507 if (strcmp (cfg->method->name, name) == 0)
3508 cfg->verbose_level = 4;
3512 cfg->intvars = (guint16 *)mono_mempool_alloc0 (cfg->mempool, sizeof (guint16) * STACK_MAX * header->max_stack);
3514 if (cfg->verbose_level > 0) {
3517 method_name = mono_method_get_full_name (method);
3518 g_print ("converting %s%s%smethod %s\n", COMPILE_LLVM (cfg) ? "llvm " : "", cfg->gsharedvt ? "gsharedvt " : "", (cfg->gshared && !cfg->gsharedvt) ? "gshared " : "", method_name);
3520 if (COMPILE_LLVM (cfg))
3521 g_print ("converting llvm method %s\n", method_name = mono_method_full_name (method, TRUE));
3522 else if (cfg->gsharedvt)
3523 g_print ("converting gsharedvt method %s\n", method_name = mono_method_full_name (method_to_compile, TRUE));
3524 else if (cfg->gshared)
3525 g_print ("converting shared method %s\n", method_name = mono_method_full_name (method_to_compile, TRUE));
3527 g_print ("converting method %s\n", method_name = mono_method_full_name (method, TRUE));
3529 g_free (method_name);
3532 if (cfg->opt & MONO_OPT_ABCREM)
3533 cfg->opt |= MONO_OPT_SSA;
3535 cfg->rs = mono_regstate_new ();
3536 cfg->next_vreg = cfg->rs->next_vreg;
3538 /* FIXME: Fix SSA to handle branches inside bblocks */
3539 if (cfg->opt & MONO_OPT_SSA)
3540 cfg->enable_extended_bblocks = FALSE;
3543 * FIXME: This confuses liveness analysis because variables which are assigned after
3544 * a branch inside a bblock become part of the kill set, even though the assignment
3545 * might not get executed. This causes the optimize_initlocals pass to delete some
3546 * assignments which are needed.
3547 * Also, the mono_if_conversion pass needs to be modified to recognize the code
3550 //cfg->enable_extended_bblocks = TRUE;
3552 /*We must verify the method before doing any IR generation as mono_compile_create_vars can assert.*/
3553 if (mono_compile_is_broken (cfg, cfg->method, TRUE)) {
3554 if (mini_get_debug_options ()->break_on_unverified)
3560 * create MonoInst* which represents arguments and local variables
3562 mono_compile_create_vars (cfg);
3564 mono_cfg_dump_create_context (cfg);
3565 mono_cfg_dump_begin_group (cfg);
3567 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));
3568 mono_cfg_dump_ir (cfg, "method-to-ir");
3570 if (cfg->gdump_ctx != NULL) {
3571 /* workaround for graph visualization, as it doesn't handle empty basic blocks properly */
3572 mono_insert_nop_in_empty_bb (cfg);
3573 mono_cfg_dump_ir (cfg, "mono_insert_nop_in_empty_bb");
3577 if (try_generic_shared && cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
3579 if (MONO_METHOD_COMPILE_END_ENABLED ())
3580 MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
3583 mono_destroy_compile (cfg);
3584 try_generic_shared = FALSE;
3585 goto restart_compile;
3587 g_assert (cfg->exception_type != MONO_EXCEPTION_GENERIC_SHARING_FAILED);
3589 if (MONO_METHOD_COMPILE_END_ENABLED ())
3590 MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
3591 /* cfg contains the details of the failure, so let the caller cleanup */
3595 cfg->stat_basic_blocks += cfg->num_bblocks;
3597 if (COMPILE_LLVM (cfg)) {
3600 /* The IR has to be in SSA form for LLVM */
3601 cfg->opt |= MONO_OPT_SSA;
3605 // Allow SSA on the result value
3606 cfg->ret->flags &= ~MONO_INST_VOLATILE;
3608 // Add an explicit return instruction referencing the return value
3609 MONO_INST_NEW (cfg, ins, OP_SETRET);
3610 ins->sreg1 = cfg->ret->dreg;
3612 MONO_ADD_INS (cfg->bb_exit, ins);
3615 cfg->opt &= ~MONO_OPT_LINEARS;
3618 cfg->opt &= ~MONO_OPT_BRANCH;
3621 /* todo: remove code when we have verified that the liveness for try/catch blocks
3625 * Currently, this can't be commented out since exception blocks are not
3626 * processed during liveness analysis.
3627 * It is also needed, because otherwise the local optimization passes would
3628 * delete assignments in cases like this:
3630 * <something which throws>
3632 * This also allows SSA to be run on methods containing exception clauses, since
3633 * SSA will ignore variables marked VOLATILE.
3635 MONO_TIME_TRACK (mono_jit_stats.jit_liveness_handle_exception_clauses, mono_liveness_handle_exception_clauses (cfg));
3636 mono_cfg_dump_ir (cfg, "liveness_handle_exception_clauses");
3638 MONO_TIME_TRACK (mono_jit_stats.jit_handle_out_of_line_bblock, mono_handle_out_of_line_bblock (cfg));
3639 mono_cfg_dump_ir (cfg, "handle_out_of_line_bblock");
3641 /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/
3643 if (!COMPILE_LLVM (cfg)) {
3644 MONO_TIME_TRACK (mono_jit_stats.jit_decompose_long_opts, mono_decompose_long_opts (cfg));
3645 mono_cfg_dump_ir (cfg, "decompose_long_opts");
3648 /* Should be done before branch opts */
3649 if (cfg->opt & (MONO_OPT_CONSPROP | MONO_OPT_COPYPROP)) {
3650 MONO_TIME_TRACK (mono_jit_stats.jit_local_cprop, mono_local_cprop (cfg));
3651 mono_cfg_dump_ir (cfg, "local_cprop");
3654 if (cfg->flags & MONO_CFG_HAS_TYPE_CHECK) {
3655 MONO_TIME_TRACK (mono_jit_stats.jit_decompose_typechecks, mono_decompose_typechecks (cfg));
3656 if (cfg->gdump_ctx != NULL) {
3657 /* workaround for graph visualization, as it doesn't handle empty basic blocks properly */
3658 mono_insert_nop_in_empty_bb (cfg);
3660 mono_cfg_dump_ir (cfg, "decompose_typechecks");
3664 * Should be done after cprop which can do strength reduction on
3665 * some of these ops, after propagating immediates.
3667 if (cfg->has_emulated_ops) {
3668 MONO_TIME_TRACK (mono_jit_stats.jit_local_emulate_ops, mono_local_emulate_ops (cfg));
3669 mono_cfg_dump_ir (cfg, "local_emulate_ops");
3672 if (cfg->opt & MONO_OPT_BRANCH) {
3673 MONO_TIME_TRACK (mono_jit_stats.jit_optimize_branches, mono_optimize_branches (cfg));
3674 mono_cfg_dump_ir (cfg, "optimize_branches");
3677 /* This must be done _before_ global reg alloc and _after_ decompose */
3678 MONO_TIME_TRACK (mono_jit_stats.jit_handle_global_vregs, mono_handle_global_vregs (cfg));
3679 mono_cfg_dump_ir (cfg, "handle_global_vregs");
3680 if (cfg->opt & MONO_OPT_DEADCE) {
3681 MONO_TIME_TRACK (mono_jit_stats.jit_local_deadce, mono_local_deadce (cfg));
3682 mono_cfg_dump_ir (cfg, "local_deadce");
3684 if (cfg->opt & MONO_OPT_ALIAS_ANALYSIS) {
3685 MONO_TIME_TRACK (mono_jit_stats.jit_local_alias_analysis, mono_local_alias_analysis (cfg));
3686 mono_cfg_dump_ir (cfg, "local_alias_analysis");
3688 /* Disable this for LLVM to make the IR easier to handle */
3689 if (!COMPILE_LLVM (cfg)) {
3690 MONO_TIME_TRACK (mono_jit_stats.jit_if_conversion, mono_if_conversion (cfg));
3691 mono_cfg_dump_ir (cfg, "if_conversion");
3694 mono_threads_safepoint ();
3696 MONO_TIME_TRACK (mono_jit_stats.jit_bb_ordering, mono_bb_ordering (cfg));
3697 mono_cfg_dump_ir (cfg, "bb_ordering");
3699 if (((cfg->num_varinfo > 2000) || (cfg->num_bblocks > 1000)) && !cfg->compile_aot) {
3701 * we disable some optimizations if there are too many variables
3702 * because JIT time may become too expensive. The actual number needs
3703 * to be tweaked and eventually the non-linear algorithms should be fixed.
3705 cfg->opt &= ~ (MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP);
3706 cfg->disable_ssa = TRUE;
3709 if (cfg->opt & MONO_OPT_LOOP) {
3710 MONO_TIME_TRACK (mono_jit_stats.jit_compile_dominator_info, mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM));
3711 MONO_TIME_TRACK (mono_jit_stats.jit_compute_natural_loops, mono_compute_natural_loops (cfg));
3714 MONO_TIME_TRACK (mono_jit_stats.jit_insert_safepoints, mono_insert_safepoints (cfg));
3715 mono_cfg_dump_ir (cfg, "insert_safepoints");
3717 /* after method_to_ir */
3719 if (MONO_METHOD_COMPILE_END_ENABLED ())
3720 MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
3725 if (header->num_clauses)
3726 cfg->disable_ssa = TRUE;
3729 //#define DEBUGSSA "logic_run"
3730 //#define DEBUGSSA_CLASS "Tests"
3733 if (!cfg->disable_ssa) {
3734 mono_local_cprop (cfg);
3737 mono_ssa_compute (cfg);
3741 if (cfg->opt & MONO_OPT_SSA) {
3742 if (!(cfg->comp_done & MONO_COMP_SSA) && !cfg->disable_ssa) {
3744 MONO_TIME_TRACK (mono_jit_stats.jit_ssa_compute, mono_ssa_compute (cfg));
3745 mono_cfg_dump_ir (cfg, "ssa_compute");
3748 if (cfg->verbose_level >= 2) {
3755 /* after SSA translation */
3757 if (MONO_METHOD_COMPILE_END_ENABLED ())
3758 MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
3762 if ((cfg->opt & MONO_OPT_CONSPROP) || (cfg->opt & MONO_OPT_COPYPROP)) {
3763 if (cfg->comp_done & MONO_COMP_SSA && !COMPILE_LLVM (cfg)) {
3765 MONO_TIME_TRACK (mono_jit_stats.jit_ssa_cprop, mono_ssa_cprop (cfg));
3766 mono_cfg_dump_ir (cfg, "ssa_cprop");
3772 if (cfg->comp_done & MONO_COMP_SSA && !COMPILE_LLVM (cfg)) {
3773 //mono_ssa_strength_reduction (cfg);
3775 if (cfg->opt & MONO_OPT_DEADCE) {
3776 MONO_TIME_TRACK (mono_jit_stats.jit_ssa_deadce, mono_ssa_deadce (cfg));
3777 mono_cfg_dump_ir (cfg, "ssa_deadce");
3780 if ((cfg->flags & (MONO_CFG_HAS_LDELEMA|MONO_CFG_HAS_CHECK_THIS)) && (cfg->opt & MONO_OPT_ABCREM)) {
3781 MONO_TIME_TRACK (mono_jit_stats.jit_perform_abc_removal, mono_perform_abc_removal (cfg));
3782 mono_cfg_dump_ir (cfg, "perform_abc_removal");
3785 MONO_TIME_TRACK (mono_jit_stats.jit_ssa_remove, mono_ssa_remove (cfg));
3786 mono_cfg_dump_ir (cfg, "ssa_remove");
3787 MONO_TIME_TRACK (mono_jit_stats.jit_local_cprop2, mono_local_cprop (cfg));
3788 mono_cfg_dump_ir (cfg, "local_cprop2");
3789 MONO_TIME_TRACK (mono_jit_stats.jit_handle_global_vregs2, mono_handle_global_vregs (cfg));
3790 mono_cfg_dump_ir (cfg, "handle_global_vregs2");
3791 if (cfg->opt & MONO_OPT_DEADCE) {
3792 MONO_TIME_TRACK (mono_jit_stats.jit_local_deadce2, mono_local_deadce (cfg));
3793 mono_cfg_dump_ir (cfg, "local_deadce2");
3796 if (cfg->opt & MONO_OPT_BRANCH) {
3797 MONO_TIME_TRACK (mono_jit_stats.jit_optimize_branches2, mono_optimize_branches (cfg));
3798 mono_cfg_dump_ir (cfg, "optimize_branches2");
3803 if (cfg->comp_done & MONO_COMP_SSA && COMPILE_LLVM (cfg)) {
3804 mono_ssa_loop_invariant_code_motion (cfg);
3805 mono_cfg_dump_ir (cfg, "loop_invariant_code_motion");
3806 /* This removes MONO_INST_FAULT flags too so perform it unconditionally */
3807 if (cfg->opt & MONO_OPT_ABCREM) {
3808 mono_perform_abc_removal (cfg);
3809 mono_cfg_dump_ir (cfg, "abc_removal");
3813 /* after SSA removal */
3815 if (MONO_METHOD_COMPILE_END_ENABLED ())
3816 MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
3820 if (cfg->llvm_only && cfg->gsharedvt)
3821 mono_ssa_remove_gsharedvt (cfg);
3823 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
3824 if (COMPILE_SOFT_FLOAT (cfg))
3825 mono_decompose_soft_float (cfg);
3827 MONO_TIME_TRACK (mono_jit_stats.jit_decompose_vtype_opts, mono_decompose_vtype_opts (cfg));
3828 if (cfg->flags & MONO_CFG_HAS_ARRAY_ACCESS) {
3829 MONO_TIME_TRACK (mono_jit_stats.jit_decompose_array_access_opts, mono_decompose_array_access_opts (cfg));
3830 mono_cfg_dump_ir (cfg, "decompose_array_access_opts");
3834 #ifndef MONO_ARCH_GOT_REG
3839 g_assert (cfg->got_var_allocated);
3842 * Allways allocate the GOT var to a register, because keeping it
3843 * in memory will increase the number of live temporaries in some
3844 * code created by inssel.brg, leading to the well known spills+
3845 * branches problem. Testcase: mcs crash in
3846 * System.MonoCustomAttrs:GetCustomAttributes.
3848 #ifdef MONO_ARCH_GOT_REG
3849 got_reg = MONO_ARCH_GOT_REG;
3851 regs = mono_arch_get_global_int_regs (cfg);
3853 got_reg = GPOINTER_TO_INT (regs->data);
3856 cfg->got_var->opcode = OP_REGVAR;
3857 cfg->got_var->dreg = got_reg;
3858 cfg->used_int_regs |= 1LL << cfg->got_var->dreg;
3862 * Have to call this again to process variables added since the first call.
3864 MONO_TIME_TRACK(mono_jit_stats.jit_liveness_handle_exception_clauses2, mono_liveness_handle_exception_clauses (cfg));
3866 if (cfg->opt & MONO_OPT_LINEARS) {
3867 GList *vars, *regs, *l;
3869 /* fixme: maybe we can avoid to compute livenesss here if already computed ? */
3870 cfg->comp_done &= ~MONO_COMP_LIVENESS;
3871 if (!(cfg->comp_done & MONO_COMP_LIVENESS))
3872 MONO_TIME_TRACK (mono_jit_stats.jit_analyze_liveness, mono_analyze_liveness (cfg));
3874 if ((vars = mono_arch_get_allocatable_int_vars (cfg))) {
3875 regs = mono_arch_get_global_int_regs (cfg);
3876 /* Remove the reg reserved for holding the GOT address */
3878 for (l = regs; l; l = l->next) {
3879 if (GPOINTER_TO_UINT (l->data) == cfg->got_var->dreg) {
3880 regs = g_list_delete_link (regs, l);
3885 MONO_TIME_TRACK (mono_jit_stats.jit_linear_scan, mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs));
3886 mono_cfg_dump_ir (cfg, "linear_scan");
3890 //mono_print_code (cfg, "");
3894 /* variables are allocated after decompose, since decompose could create temps */
3895 if (!COMPILE_LLVM (cfg)) {
3896 MONO_TIME_TRACK (mono_jit_stats.jit_arch_allocate_vars, mono_arch_allocate_vars (cfg));
3897 mono_cfg_dump_ir (cfg, "arch_allocate_vars");
3898 if (cfg->exception_type)
3903 mono_allocate_gsharedvt_vars (cfg);
3905 if (!COMPILE_LLVM (cfg)) {
3906 gboolean need_local_opts;
3907 MONO_TIME_TRACK (mono_jit_stats.jit_spill_global_vars, mono_spill_global_vars (cfg, &need_local_opts));
3908 mono_cfg_dump_ir (cfg, "spill_global_vars");
3910 if (need_local_opts || cfg->compile_aot) {
3911 /* To optimize code created by spill_global_vars */
3912 MONO_TIME_TRACK (mono_jit_stats.jit_local_cprop3, mono_local_cprop (cfg));
3913 if (cfg->opt & MONO_OPT_DEADCE)
3914 MONO_TIME_TRACK (mono_jit_stats.jit_local_deadce3, mono_local_deadce (cfg));
3915 mono_cfg_dump_ir (cfg, "needs_local_opts");
3919 mono_insert_branches_between_bblocks (cfg);
3921 if (COMPILE_LLVM (cfg)) {
3925 /* The IR has to be in SSA form for LLVM */
3926 if (!(cfg->comp_done & MONO_COMP_SSA)) {
3927 cfg->exception_message = g_strdup ("SSA disabled.");
3928 cfg->disable_llvm = TRUE;
3931 if (cfg->flags & MONO_CFG_HAS_ARRAY_ACCESS)
3932 mono_decompose_array_access_opts (cfg);
3934 if (!cfg->disable_llvm)
3935 mono_llvm_emit_method (cfg);
3936 if (cfg->disable_llvm) {
3937 if (cfg->verbose_level >= (cfg->llvm_only ? 0 : 1)) {
3938 //nm = mono_method_full_name (cfg->method, TRUE);
3939 printf ("LLVM failed for '%s': %s\n", method->name, cfg->exception_message);
3942 if (cfg->llvm_only) {
3943 cfg->disable_aot = TRUE;
3946 mono_destroy_compile (cfg);
3948 goto restart_compile;
3951 if (cfg->verbose_level > 0 && !cfg->compile_aot) {
3952 nm = mono_method_full_name (cfg->method, TRUE);
3953 g_print ("LLVM Method %s emitted at %p to %p (code length %d) [%s]\n",
3955 cfg->native_code, cfg->native_code + cfg->code_len, cfg->code_len, cfg->domain->friendly_name);
3960 MONO_TIME_TRACK (mono_jit_stats.jit_codegen, mono_codegen (cfg));
3961 mono_cfg_dump_ir (cfg, "codegen");
3962 if (cfg->exception_type)
3966 if (COMPILE_LLVM (cfg))
3967 InterlockedIncrement (&mono_jit_stats.methods_with_llvm);
3969 InterlockedIncrement (&mono_jit_stats.methods_without_llvm);
3971 MONO_TIME_TRACK (mono_jit_stats.jit_create_jit_info, cfg->jit_info = create_jit_info (cfg, method_to_compile));
3973 #ifdef MONO_ARCH_HAVE_LIVERANGE_OPS
3974 if (cfg->extend_live_ranges) {
3975 /* Extend live ranges to cover the whole method */
3976 for (i = 0; i < cfg->num_varinfo; ++i)
3977 MONO_VARINFO (cfg, i)->live_range_end = cfg->code_len;
3981 if (!cfg->compile_aot)
3982 mono_save_xdebug_info (cfg);
3984 MONO_TIME_TRACK (mono_jit_stats.jit_gc_create_gc_map, mini_gc_create_gc_map (cfg));
3986 MONO_TIME_TRACK (mono_jit_stats.jit_save_seq_point_info, mono_save_seq_point_info (cfg));
3988 if (cfg->verbose_level >= 2) {
3989 char *id = mono_method_full_name (cfg->method, FALSE);
3990 mono_disassemble_code (cfg, cfg->native_code, cfg->code_len, id + 3);
3994 if (!cfg->compile_aot) {
3995 mono_domain_lock (cfg->domain);
3996 mono_jit_info_table_add (cfg->domain, cfg->jit_info);
3998 if (cfg->method->dynamic)
3999 mono_dynamic_code_hash_lookup (cfg->domain, cfg->method)->ji = cfg->jit_info;
4000 mono_domain_unlock (cfg->domain);
4005 printf ("GSHAREDVT: %s\n", mono_method_full_name (cfg->method, TRUE));
4008 /* collect statistics */
4009 #ifndef DISABLE_PERFCOUNTERS
4010 mono_perfcounters->jit_methods++;
4011 mono_perfcounters->jit_bytes += header->code_size;
4013 mono_jit_stats.allocated_code_size += cfg->code_len;
4014 code_size_ratio = cfg->code_len;
4015 if (code_size_ratio > mono_jit_stats.biggest_method_size && mono_jit_stats.enabled) {
4016 mono_jit_stats.biggest_method_size = code_size_ratio;
4017 g_free (mono_jit_stats.biggest_method);
4018 mono_jit_stats.biggest_method = g_strdup_printf ("%s::%s)", method->klass->name, method->name);
4020 code_size_ratio = (code_size_ratio * 100) / header->code_size;
4021 if (code_size_ratio > mono_jit_stats.max_code_size_ratio && mono_jit_stats.enabled) {
4022 mono_jit_stats.max_code_size_ratio = code_size_ratio;
4023 g_free (mono_jit_stats.max_ratio_method);
4024 mono_jit_stats.max_ratio_method = g_strdup_printf ("%s::%s)", method->klass->name, method->name);
4026 mono_jit_stats.native_code_size += cfg->code_len;
4028 if (MONO_METHOD_COMPILE_END_ENABLED ())
4029 MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
4031 mono_cfg_dump_close_group (cfg);
4037 mono_arch_instrument_epilog (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments)
4039 return mono_arch_instrument_epilog_full (cfg, func, p, enable_arguments, FALSE);
4043 mono_cfg_add_try_hole (MonoCompile *cfg, MonoExceptionClause *clause, guint8 *start, MonoBasicBlock *bb)
4045 TryBlockHole *hole = (TryBlockHole *)mono_mempool_alloc (cfg->mempool, sizeof (TryBlockHole));
4046 hole->clause = clause;
4047 hole->start_offset = start - cfg->native_code;
4048 hole->basic_block = bb;
4050 cfg->try_block_holes = g_slist_append_mempool (cfg->mempool, cfg->try_block_holes, hole);
4054 mono_cfg_set_exception (MonoCompile *cfg, int type)
4056 cfg->exception_type = type;
4059 /* Assumes ownership of the MSG argument */
4061 mono_cfg_set_exception_invalid_program (MonoCompile *cfg, char *msg)
4063 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
4064 mono_error_set_generic_error (&cfg->error, "System", "InvalidProgramException", "%s", msg);
4067 #endif /* DISABLE_JIT */
4070 create_jit_info_for_trampoline (MonoMethod *wrapper, MonoTrampInfo *info)
4072 MonoDomain *domain = mono_get_root_domain ();
4077 if (info->uw_info) {
4078 uw_info = info->uw_info;
4079 info_len = info->uw_info_len;
4081 uw_info = mono_unwind_ops_encode (info->unwind_ops, &info_len);
4084 jinfo = (MonoJitInfo *)mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO);
4085 jinfo->d.method = wrapper;
4086 jinfo->code_start = info->code;
4087 jinfo->code_size = info->code_size;
4088 jinfo->unwind_info = mono_cache_unwind_info (uw_info, info_len);
4096 GTimer *mono_time_track_start ()
4098 return g_timer_new ();
4101 void mono_time_track_end (double *time, GTimer *timer)
4103 g_timer_stop (timer);
4104 *time += g_timer_elapsed (timer, NULL);
4105 g_timer_destroy (timer);
4108 void mono_update_jit_stats (MonoCompile *cfg)
4110 mono_jit_stats.allocate_var += cfg->stat_allocate_var;
4111 mono_jit_stats.locals_stack_size += cfg->stat_locals_stack_size;
4112 mono_jit_stats.basic_blocks += cfg->stat_basic_blocks;
4113 mono_jit_stats.max_basic_blocks = MAX (cfg->stat_basic_blocks, mono_jit_stats.max_basic_blocks);
4114 mono_jit_stats.cil_code_size += cfg->stat_cil_code_size;
4115 mono_jit_stats.regvars += cfg->stat_n_regvars;
4116 mono_jit_stats.inlineable_methods += cfg->stat_inlineable_methods;
4117 mono_jit_stats.inlined_methods += cfg->stat_inlined_methods;
4118 mono_jit_stats.code_reallocs += cfg->stat_code_reallocs;
4122 * mono_jit_compile_method_inner:
4124 * Main entry point for the JIT.
4127 mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain, int opt, MonoError *error)
4130 gpointer code = NULL;
4131 MonoJitInfo *jinfo, *info;
4133 MonoException *ex = NULL;
4134 guint32 prof_options;
4136 MonoMethod *prof_method, *shared;
4138 mono_error_init (error);
4140 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
4141 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4143 MonoMethodPInvoke* piinfo = (MonoMethodPInvoke *) method;
4145 if (!piinfo->addr) {
4146 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
4147 piinfo->addr = mono_lookup_internal_call (method);
4148 else if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)
4150 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);
4152 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);
4155 mono_lookup_pinvoke_call (method, NULL, NULL);
4157 nm = mono_marshal_get_native_wrapper (method, TRUE, mono_aot_only);
4158 gpointer compiled_method = mono_compile_method_checked (nm, error);
4159 return_val_if_nok (error, NULL);
4160 code = mono_get_addr_from_ftnptr (compiled_method);
4161 jinfo = mono_jit_info_table_find (target_domain, (char *)code);
4163 jinfo = mono_jit_info_table_find (mono_domain_get (), (char *)code);
4165 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
4167 } else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
4168 const char *name = method->name;
4169 char *full_name, *msg;
4172 if (method->klass->parent == mono_defaults.multicastdelegate_class) {
4173 if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
4174 MonoJitICallInfo *mi = mono_find_jit_icall_by_name ("ves_icall_mono_delegate_ctor");
4177 * We need to make sure this wrapper
4178 * is compiled because it might end up
4179 * in an (M)RGCTX if generic sharing
4180 * is enabled, and would be called
4181 * indirectly. If it were a
4182 * trampoline we'd try to patch that
4183 * indirect call, which is not
4186 return mono_get_addr_from_ftnptr ((gpointer)mono_icall_get_wrapper_full (mi, TRUE));
4187 } else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
4188 if (mono_llvm_only) {
4189 nm = mono_marshal_get_delegate_invoke (method, NULL);
4190 gpointer compiled_ptr = mono_compile_method_checked (nm, error);
4191 mono_error_assert_ok (error);
4192 return mono_get_addr_from_ftnptr (compiled_ptr);
4194 return mono_create_delegate_trampoline (target_domain, method->klass);
4195 } else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
4196 nm = mono_marshal_get_delegate_begin_invoke (method);
4197 gpointer compiled_ptr = mono_compile_method_checked (nm, error);
4198 mono_error_assert_ok (error);
4199 return mono_get_addr_from_ftnptr (compiled_ptr);
4200 } else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
4201 nm = mono_marshal_get_delegate_end_invoke (method);
4202 gpointer compiled_ptr = mono_compile_method_checked (nm, error);
4203 mono_error_assert_ok (error);
4204 return mono_get_addr_from_ftnptr (compiled_ptr);
4208 full_name = mono_method_full_name (method, TRUE);
4209 msg = g_strdup_printf ("Unrecognizable runtime implemented method '%s'", full_name);
4210 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "InvalidProgramException", msg);
4211 mono_error_set_exception_instance (error, ex);
4217 if (method->wrapper_type == MONO_WRAPPER_UNKNOWN) {
4218 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
4220 if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT) {
4221 static MonoTrampInfo *in_tinfo, *out_tinfo;
4222 MonoTrampInfo *tinfo;
4224 gboolean is_in = info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN;
4226 if (is_in && in_tinfo)
4227 return in_tinfo->code;
4228 else if (!is_in && out_tinfo)
4229 return out_tinfo->code;
4232 * This is a special wrapper whose body is implemented in assembly, like a trampoline. We use a wrapper so EH
4234 * FIXME: The caller signature doesn't match the callee, which might cause problems on some platforms
4237 mono_aot_get_trampoline_full (is_in ? "gsharedvt_trampoline" : "gsharedvt_out_trampoline", &tinfo);
4239 mono_arch_get_gsharedvt_trampoline (&tinfo, FALSE);
4240 jinfo = create_jit_info_for_trampoline (method, tinfo);
4241 mono_jit_info_table_add (mono_get_root_domain (), jinfo);
4250 if (mono_aot_only) {
4251 char *fullname = mono_method_full_name (method, TRUE);
4252 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);
4258 jit_timer = mono_time_track_start ();
4259 cfg = mini_method_compile (method, opt, target_domain, JIT_FLAG_RUN_CCTORS, 0, -1);
4260 mono_time_track_end (&mono_jit_stats.jit_time, jit_timer);
4262 prof_method = cfg->method;
4264 switch (cfg->exception_type) {
4265 case MONO_EXCEPTION_NONE:
4267 case MONO_EXCEPTION_TYPE_LOAD:
4268 case MONO_EXCEPTION_MISSING_FIELD:
4269 case MONO_EXCEPTION_MISSING_METHOD:
4270 case MONO_EXCEPTION_FILE_NOT_FOUND:
4271 case MONO_EXCEPTION_BAD_IMAGE:
4272 case MONO_EXCEPTION_INVALID_PROGRAM: {
4273 /* Throw a type load exception if needed */
4274 if (cfg->exception_ptr) {
4275 ex = mono_class_get_exception_for_failure ((MonoClass *)cfg->exception_ptr);
4277 if (cfg->exception_type == MONO_EXCEPTION_MISSING_FIELD)
4278 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingFieldException", cfg->exception_message);
4279 else if (cfg->exception_type == MONO_EXCEPTION_MISSING_METHOD)
4280 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingMethodException", cfg->exception_message);
4281 else if (cfg->exception_type == MONO_EXCEPTION_TYPE_LOAD)
4282 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "TypeLoadException", cfg->exception_message);
4283 else if (cfg->exception_type == MONO_EXCEPTION_FILE_NOT_FOUND)
4284 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System.IO", "FileNotFoundException", cfg->exception_message);
4285 else if (cfg->exception_type == MONO_EXCEPTION_BAD_IMAGE)
4286 ex = mono_get_exception_bad_image_format (cfg->exception_message);
4287 else if (cfg->exception_type == MONO_EXCEPTION_INVALID_PROGRAM)
4288 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "InvalidProgramException", cfg->exception_message);
4290 g_assert_not_reached ();
4294 case MONO_EXCEPTION_MONO_ERROR:
4295 // FIXME: MonoError has no copy ctor
4296 g_assert (!mono_error_ok (&cfg->error));
4297 ex = mono_error_convert_to_exception (&cfg->error);
4300 g_assert_not_reached ();
4304 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
4305 mono_profiler_method_end_jit (method, NULL, MONO_PROFILE_FAILED);
4307 mono_destroy_compile (cfg);
4308 mono_error_set_exception_instance (error, ex);
4313 if (mono_method_is_generic_sharable (method, FALSE))
4314 shared = mini_get_shared_method (method);
4318 mono_domain_lock (target_domain);
4320 /* Check if some other thread already did the job. In this case, we can
4321 discard the code this thread generated. */
4323 info = mini_lookup_method (target_domain, method, shared);
4325 /* We can't use a domain specific method in another domain */
4326 if ((target_domain == mono_domain_get ()) || info->domain_neutral) {
4327 code = info->code_start;
4328 // printf("Discarding code for method %s\n", method->name);
4332 /* The lookup + insert is atomic since this is done inside the domain lock */
4333 mono_domain_jit_code_hash_lock (target_domain);
4334 mono_internal_hash_table_insert (&target_domain->jit_code_hash, cfg->jit_info->d.method, cfg->jit_info);
4335 mono_domain_jit_code_hash_unlock (target_domain);
4337 code = cfg->native_code;
4339 if (cfg->gshared && mono_method_is_generic_sharable (method, FALSE))
4340 mono_stats.generics_shared_methods++;
4342 mono_stats.gsharedvt_methods++;
4345 jinfo = cfg->jit_info;
4347 prof_options = cfg->prof_options;
4350 * Update global stats while holding a lock, instead of doing many
4351 * InterlockedIncrement operations during JITting.
4353 mono_update_jit_stats (cfg);
4355 mono_destroy_compile (cfg);
4358 if (domain_jit_info (target_domain)->jump_target_hash) {
4359 MonoJumpInfo patch_info;
4360 MonoJumpList *jlist;
4362 jlist = (MonoJumpList *)g_hash_table_lookup (domain_jit_info (target_domain)->jump_target_hash, method);
4364 patch_info.next = NULL;
4365 patch_info.ip.i = 0;
4366 patch_info.type = MONO_PATCH_INFO_METHOD_JUMP;
4367 patch_info.data.method = method;
4368 g_hash_table_remove (domain_jit_info (target_domain)->jump_target_hash, method);
4370 #ifdef MONO_ARCH_HAVE_PATCH_CODE_NEW
4371 for (tmp = jlist->list; tmp; tmp = tmp->next) {
4372 gpointer target = mono_resolve_patch_target (NULL, target_domain, (guint8 *)tmp->data, &patch_info, TRUE, error);
4373 if (!mono_error_ok (error))
4375 mono_arch_patch_code_new (NULL, target_domain, (guint8 *)tmp->data, &patch_info, target);
4378 for (tmp = jlist->list; tmp; tmp = tmp->next) {
4379 mono_arch_patch_code (NULL, NULL, target_domain, tmp->data, &patch_info, TRUE, error);
4387 /* Update llvm callees */
4388 if (domain_jit_info (target_domain)->llvm_jit_callees) {
4389 GSList *callees = g_hash_table_lookup (domain_jit_info (target_domain)->llvm_jit_callees, method);
4392 for (l = callees; l; l = l->next) {
4393 gpointer *addr = (gpointer*)l->data;
4399 mono_emit_jit_map (jinfo);
4401 mono_domain_unlock (target_domain);
4403 if (!mono_error_ok (error))
4406 vtable = mono_class_vtable (target_domain, method->klass);
4408 g_assert (mono_class_has_failure (method->klass));
4409 mono_error_set_for_class_failure (error, method->klass);
4413 if (prof_options & MONO_PROFILE_JIT_COMPILATION) {
4414 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
4415 if (mono_marshal_method_from_wrapper (method)) {
4416 /* Native func wrappers have no method */
4417 /* The profiler doesn't know about wrappers, so pass the original icall method */
4418 mono_profiler_method_end_jit (mono_marshal_method_from_wrapper (method), jinfo, MONO_PROFILE_OK);
4421 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
4422 if (prof_method != method) {
4423 mono_profiler_method_end_jit (prof_method, jinfo, MONO_PROFILE_OK);
4427 if (!mono_runtime_class_init_full (vtable, error))
4433 * mini_get_underlying_type:
4435 * Return the type the JIT will use during compilation.
4436 * Handles: byref, enums, native types, generic sharing.
4437 * For gsharedvt types, it will return the original VAR/MVAR.
4440 mini_get_underlying_type (MonoType *type)
4442 return mini_type_get_underlying_type (type);
4446 mini_jit_init (void)
4448 mono_os_mutex_init_recursive (&jit_mutex);
4450 current_backend = g_new0 (MonoBackend, 1);
4451 init_backend (current_backend);
4456 mini_jit_cleanup (void)
4459 g_free (emul_opcode_map);
4460 g_free (emul_opcode_opcodes);
4466 mono_llvm_emit_aot_file_info (MonoAotFileInfo *info, gboolean has_jitted_code)
4468 g_assert_not_reached ();
4471 void mono_llvm_emit_aot_data (const char *symbol, guint8 *data, int data_len)
4473 g_assert_not_reached ();
4478 #if !defined(ENABLE_LLVM_RUNTIME) && !defined(ENABLE_LLVM)
4481 mono_llvm_cpp_throw_exception (void)
4483 g_assert_not_reached ();
4491 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFlags flags, int parts, int aot_method_index)
4493 g_assert_not_reached ();
4498 mono_destroy_compile (MonoCompile *cfg)
4500 g_assert_not_reached ();
4504 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
4506 g_assert_not_reached ();
4509 #endif /* DISABLE_JIT */