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